Skip to content

Commit

Permalink
fix: send error when token returns Unauthorized
Browse files Browse the repository at this point in the history
  • Loading branch information
aalemayhu committed Jul 12, 2023
1 parent 18d21f2 commit 087473e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
21 changes: 18 additions & 3 deletions src/controllers/NotionController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import { blockToStaticMarkup } from '../services/NotionService/helpers/blockToSt
import NotionService from '../services/NotionService';
import { getDatabase } from '../data_layer';
import { getNotionId } from '../services/NotionService/getNotionId';
import { getOwner } from '../lib/User/getOwner';
import { APIErrorCode, APIResponseError } from '@notionhq/client';
import sendErrorResponse from '../lib/sendErrorResponse';

class NotionController {
constructor(private readonly service: NotionService) {}
Expand All @@ -32,9 +35,21 @@ class NotionController {
}

async search(req: Request, res: Response) {
const query = req.body.query.toString() || '';
const result = await this.service.search(query, res.locals.owner);
res.json(result);
try {
const query = req.body.query.toString() || '';
const result = await this.service.search(query, getOwner(res));
res.json(result);
} catch (err) {
if (err instanceof APIResponseError) {
if (err.code === APIErrorCode.Unauthorized) {
const renewalLink = this.service.getNotionAuthorizationLink(
this.service.getClientId()
);
err.message += `You can renew it <a href='${renewalLink}'>here</a>.`;
}
sendErrorResponse(err, res);
}
}
}

async getNotionLink(_req: Request, res: Response) {
Expand Down
9 changes: 5 additions & 4 deletions src/services/NotionService/NotionService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ export interface NotionLinkInfo {
workspace: string | null;
}

const getNotionAuthorizationLink = (clientId: string) =>
`https://api.notion.com/v1/oauth/authorize?owner=user&client_id=${clientId}&response_type=code`;

export class NotionService {
clientId: string;

Expand All @@ -28,6 +25,10 @@ export class NotionService {
this.redirectURI = process.env.NOTION_REDIRECT_URI!;
}

getNotionAuthorizationLink(clientId: string) {
return `https://api.notion.com/v1/oauth/authorize?owner=user&client_id=${clientId}&response_type=code`;
}

isValidUUID(id: string | undefined | null) {
if (!id) {
return false;
Expand Down Expand Up @@ -68,7 +69,7 @@ export class NotionService {
async getNotionLinkInfo(owner: number): Promise<NotionLinkInfo> {
const notionData = await this.notionRepository.getNotionData(owner);
const clientId = this.clientId;
const link = getNotionAuthorizationLink(clientId);
const link = this.getNotionAuthorizationLink(clientId);

if (!notionData) {
return {
Expand Down

0 comments on commit 087473e

Please sign in to comment.