Skip to content

Commit

Permalink
Notion and logger connverted to typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
anoopkarnik committed Jun 20, 2024
1 parent 2716610 commit f15edad
Show file tree
Hide file tree
Showing 28 changed files with 172 additions and 62 deletions.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion apps/scheduler-app/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client'
import React, { useEffect } from 'react'
import { initializeScheduler } from '../../lib/scheduler'
import { initializeScheduler } from '../../actions/scheduler'

const page = () => {
useEffect(() =>{
Expand Down
2 changes: 1 addition & 1 deletion apps/scheduler-app/components/ForgotPasswordClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import ForgotPasswordCard from '@repo/ui/components/ForgotPasswordCard';
import { ForgotPassword } from '../ actions/forgot-password';
import { ForgotPassword } from '../actions/forgot-password';


export default function ForgotPasswordClient() {
Expand Down
2 changes: 1 addition & 1 deletion apps/scheduler-app/components/LoginClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import LoginCard from '@repo/ui/components/LoginCard';
import { signIn} from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { login } from '../ actions/login';
import { login } from '../actions/login';
import { DEFAULT_LOGIN_REDIRECT } from '../routes';


Expand Down
4 changes: 2 additions & 2 deletions apps/scheduler-app/components/NavbarClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import { Navbar } from "@repo/ui/components/Navbar"
import { useTheme } from "next-themes"
import { useRouter } from "next/navigation";
import { logout } from "../ actions/logout";
import { logout } from "../actions/logout";
import { useCurrentUser } from "../hooks/useCurrentUser";
import { resetPasswordSettings } from "../ actions/reset-password-settings";
import { resetPasswordSettings } from "../actions/reset-password-settings";
import { signOut } from "next-auth/react";

export default function NavbarClient() {
Expand Down
2 changes: 1 addition & 1 deletion apps/scheduler-app/components/RegisterClient.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client"
import RegisterCard from '@repo/ui/components/RegisterCard';
import { useRouter } from 'next/navigation';
import { register } from '../ actions/register';
import { register } from '../actions/register';
import { signIn,useSession } from 'next-auth/react';
import { DEFAULT_LOGIN_REDIRECT } from '../routes';

Expand Down
4 changes: 2 additions & 2 deletions apps/scheduler-app/components/ResetPasswordClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import ResetPasswordCard from '@repo/ui/components/ResetPasswordCard';
import { resetPassword} from '../ actions/reset-password';
import { verifyResetToken } from '../ actions/verify-reset-token';
import { resetPassword} from '../actions/reset-password';
import { verifyResetToken } from '../actions/verify-reset-token';
import ErrorCard from '@repo/ui/components/ErrorCard';


Expand Down
2 changes: 1 addition & 1 deletion apps/scheduler-app/components/VerificationClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import VerificationCard from '@repo/ui/components/VerificationCard';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { newVerification } from '../ actions/new-verification';
import { newVerification } from '../actions/new-verification';


export default function VerificationClient() {
Expand Down
2 changes: 2 additions & 0 deletions apps/scheduler-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
"@repo/next-auth": "*",
"@repo/resend-email": "*",
"@repo/ui": "*",
"@repo/notion": "*",
"@repo/winston-logger": "*",
"bcryptjs": "^2.4.3",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
Expand Down
2 changes: 2 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 8 additions & 3 deletions packages/notion/src/calendar/add_calendar_to_page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ interface CalendarPageProps {
timebox_db_id?: string
}

interface SchedulerDetailsProps {
location?: string
scheduler_db_id: string
}

export const createCalendarPage = async({
calendar_db_id=process.env.CALENDAR_DB_ID,
scheduler_db_id=process.env.SCHEDULER_DB_ID,
Expand Down Expand Up @@ -97,7 +102,7 @@ export const createCalendarPage = async({
return ;
}

export const getSchedulerDetails = async ({location,scheduler_db_id}:{location:string,scheduler_db_id:string}) =>{
export const getSchedulerDetails = async ({location,scheduler_db_id}:any):Promise<any> =>{
const currentTimeGmt = moment().format('YYYY-MM-DD');
let filters:any = [];
filters.push({'name': 'Start Date', 'type': 'date', 'condition': 'on_or_before', 'value': currentTimeGmt})
Expand All @@ -107,15 +112,15 @@ export const getSchedulerDetails = async ({location,scheduler_db_id}:{location:s
return results;
}

const getCurrentLocation = async ({timebox_db_id}) => {
const getCurrentLocation = async ({timebox_db_id}:any):Promise<any> => {
let filters = [];
filters.push({"name":"End Time", 'type': 'date','condition':'is_empty','value':true})
let response = await queryNotionDatabase({database_id: timebox_db_id, filters: filters})

let results = response.results;
if (results && Array.isArray(results) && results.length > 0){
for (let row =0;row<results.length;row++){
if (results[row]['Action Name'] === 'Parents'){
if (results[row]?.['Action Name'] === 'Parents'){
return results[row]['Action Name']
}
else if (results[row]['Action Name'] === 'Short Vacation'){
Expand Down
8 changes: 5 additions & 3 deletions packages/notion/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import {Client } from '@notionhq/client'

import { CreateDatabaseParameters } from '@notionhq/client/build/src/api-endpoints';
import { createDatabaseProps } from './props/request';
import { logger } from '@repo/winston-logger/index';
const notion = new Client({auth: process.env.NOTION_TOKEN})


export const createDatabase = async ({parent,title,properties}:any) =>{
let payload:any = {

export const createDatabase = async ({parent,title,properties}:createDatabaseProps) =>{
let payload:CreateDatabaseParameters = {
"parent": { "type": "page_id", "page_id": parent },
"title": [
{
Expand Down
79 changes: 40 additions & 39 deletions packages/notion/src/modify.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Client } from '@notionhq/client';
import { logger } from '@repo/winston-logger/index';
import { queryDatabase, createPage, modifyPage, createDatabase, getPage, getBlockChildren, deleteBlock, appendBlockChildren } from './index'; // Adjust the import path accordingly
import _ from 'lodash';

const notion = new Client({ auth: process.env.NOTION_API_KEY });
export const queryNotionDatabase = async ({database_id, filters, sorts = []}) => {
export const queryNotionDatabase = async ({database_id, filters, sorts = []}:any):Promise<any> => {
let has_more = true;
let cursor = null;
let results = [];
Expand All @@ -27,14 +26,14 @@ export const queryNotionDatabase = async ({database_id, filters, sorts = []}) =>
return { "results": results };
}

function constructSortBody(body, sorts) {
function constructSortBody(body:any, sorts:any) {
if (sorts.length > 0) {
body.sorts = sorts.map(modifySort);
}
return body;
}

function modifySort(sort) {
function modifySort(sort:any) {
if (sort.type === 'last_edited_time') {
return { timestamp: 'last_edited_time', direction: sort.direction };
} else if (['date', 'checkbox', 'multi_select', 'select', 'relation'].includes(sort.type)) {
Expand All @@ -44,8 +43,8 @@ function modifySort(sort) {
}
}

async function constructFilterBody(filters, cursor) {
const filtersBody = { filter: { and: [] } };
async function constructFilterBody(filters:any, cursor:any) {
const filtersBody:any = { filter: { and: [] } };
if (cursor) {
filtersBody['start_cursor'] = cursor;
}
Expand All @@ -54,57 +53,59 @@ async function constructFilterBody(filters, cursor) {
return filtersBody;
}

function modifyFilter(filter) {
function modifyFilter(filter:any) {
if (filter.type === 'last_edited_time') {
return { timestamp: 'last_edited_time', last_edited_time: { [filter.condition]: filter.value } };
} else if (['date', 'checkbox', 'multi_select', 'select', 'created_time', 'relation', 'status'].includes(filter.type)) {
return { property: filter.name, [filter.type]: { [filter.condition]: filter.value } };
}
}

async function modifyResult(result) {
const resultBody = { id: result.id };
async function modifyResult(result:any):Promise<any> {
const resultBody:any = { id: result.id };
const properties = result.properties;

for (const prop in properties) {
resultBody[prop] = unmodifyProperty(properties[prop]);
if (resultBody.hasOwnProperty(prop)) {
resultBody[prop] = unmodifyProperty(properties[prop]);
}
}
return resultBody;
}

async function queryPageBlocks(page_id, type) {
async function queryPageBlocks(page_id:any, type:any) {
const response = await getBlockChildren(page_id);

if (response.results.length > 0) {
if (type === 'parent') {
const results = {};
const results:any = {};
for (const result of response.results) {
try {
const parentResult = modifyBlock(result);
const parentResultId = parentResult.id;
const parentResultName = parentResult.name;
const parentResultId = parentResult?.id;
const parentResultName = parentResult?.name;
const childResults = await queryPageBlocks(parentResultId, 'child');
results[parentResultName] = {
id: parentResultId,
children: childResults
};
} catch (error) {
logger.info(`Error in ${JSON.stringify(result)}: ${error.message}`);
logger.info(`Error in ${JSON.stringify(result)}`);
}
}
return results;
} else if (type === 'child') {
return response.results.map(result => {
const childResult = modifyBlock(result);
const childResultName = childResult.name;
const childResultName = childResult?.name;
return childResultName.includes('\n') ? childResultName.split('\n') : childResultName;
}).flat();
}
}
return [];
}

function modifyBlock(block) {
function modifyBlock(block:any) {
if (block.heading_3) {
return {
name: block.heading_3.rich_text[0].text.content,
Expand All @@ -123,29 +124,29 @@ function modifyBlock(block) {
}
}

export const modifyNotionPage = async ({page_id, properties}) => {
export const modifyNotionPage = async ({page_id, properties}:any) => {
const body = await constructUpdateBody(properties);
const response = await modifyPage({page_id, body});
return modifyResult(response);
}

async function constructUpdateBody(properties) {
const propertiesBody = {};
async function constructUpdateBody(properties:any) {
const propertiesBody:any = {};
for (let property of properties) {
propertiesBody[property.name] = await modifyProperty(property);
};
return { properties: propertiesBody };
}

export const createNotionPage = async({database_id, properties}) => {
export const createNotionPage = async({database_id, properties}:any) => {
const body = await constructCreateBody(database_id, properties);
const response = await createPage({body});
return modifyResult(response);
}

async function constructCreateBody(database_id, properties) {
async function constructCreateBody(database_id:any, properties:any) {
console.log(properties);
const propertiesBody = {};
const propertiesBody:any = {};
for (let property of properties){
propertiesBody[property.name] = await modifyProperty(property);
console.log(propertiesBody);
Expand All @@ -159,7 +160,7 @@ async function constructCreateBody(database_id, properties) {
};
}

async function modifyProperty(property) {
async function modifyProperty(property:any) {
switch (property.type) {
case 'text':
return { rich_text: [{ text: { content: property.value } }] };
Expand All @@ -178,18 +179,18 @@ async function modifyProperty(property) {
case 'select':
return { select: { name: property.value } };
case 'multi_select':
return { multi_select: property.value.map(value => ({ name: value })) };
return { multi_select: property.value.map((value:any) => ({ name: value })) };
case 'relation':
return { relation: property.value.map(value => ({ id: value })) };
return { relation: property.value.map((value:any) => ({ id: value })) };
}
}

function unmodifyProperty(prop) {
function unmodifyProperty(prop:any) {
switch (prop.type) {
case 'unique_id':
return `${prop.unique_id.prefix}-${prop.unique_id.number}`;
case 'relation':
return prop.relation.map(x => x.id);
return prop.relation.map((x:any) => x.id);
case 'number':
return prop.number;
case 'select':
Expand All @@ -199,9 +200,9 @@ function unmodifyProperty(prop) {
case 'rich_text':
return prop.rich_text.length > 0 ? prop.rich_text[0].text.content : '';
case 'rollup':
return _.flatten(unmodifyProperty(prop.rollup));
return unmodifyProperty(prop.rollup);
case 'people':
return prop.people.map(x => x.name);
return prop.people.map((x:any) => x.name);
case 'status':
return prop.status ? prop.status.name : null;
case 'date':
Expand All @@ -211,32 +212,32 @@ function unmodifyProperty(prop) {
case 'created_time':
return prop.created_time;
case 'multi_select':
return prop.multi_select.map(x => x.name);
return prop.multi_select.map((x:any) => x.name);
case 'array':
return prop.array.map(x => unmodifyProperty(x));
return prop.array.map((x:any) => unmodifyProperty(x));
case 'files':
return prop.files.map(x => x.name);
return prop.files.map((x:any) => x.name);
case 'url':
return prop.url;
}
}

async function addChildrenToPage(page_id, children) {
async function addChildrenToPage(page_id:any, children:any) {
const body = constructChildrenBody(children);
const response = await appendBlockChildren({page_id, body});
return { message: 'Added the children' };
}

function constructChildrenBody(children) {
const childrenBodyList = children.map(child => {
function constructChildrenBody(children:any) {
const childrenBodyList = children.map((child:any) => {
return {
[child.type]: modifyChildrenProperty(child)
};
});
return { children: childrenBodyList };
}

function modifyChildrenProperty(prop) {
function modifyChildrenProperty(prop:any) {
switch (prop.type) {
case 'table_of_contents':
return { color: 'default' };
Expand All @@ -249,7 +250,7 @@ function modifyChildrenProperty(prop) {
}
}

async function deletePageBlocks(page_id) {
async function deletePageBlocks(page_id:any) {
const response = await getBlockChildren(page_id);
if (response.results.length > 0) {
for (const result of response.results) {
Expand All @@ -259,7 +260,7 @@ async function deletePageBlocks(page_id) {
return { message: 'Deleted the children' };
}

async function getNotionPage(page_id) {
async function getNotionPage(page_id:any) {
const response = await getPage(page_id);
return modifyResult(response);
}
5 changes: 5 additions & 0 deletions packages/notion/src/props/request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface createDatabaseProps {
parent: string,
title: string,
properties: Record<string, any>
}
Empty file.
Loading

0 comments on commit f15edad

Please sign in to comment.