From c196207fc35b57370dcf636ef8196a6d94167828 Mon Sep 17 00:00:00 2001 From: Wazbat Date: Thu, 22 Jun 2023 23:49:44 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Added=20logic=20for=20non-exista?= =?UTF-8?q?nt=20users?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes an internal server error when users do not exist --- src/api/user.ts | 7 ++++++- src/fetch.ts | 4 ++++ test/index.test.ts | 15 +++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/api/user.ts b/src/api/user.ts index 593c047..9230fd5 100644 --- a/src/api/user.ts +++ b/src/api/user.ts @@ -60,7 +60,12 @@ export const userAPI = async ( flags?: InputFlags ): Promise => { const userResponse = await fetchUser(username, event); - + if (!userResponse || !Object.keys(userResponse).length) { + return { + code: 404, + message: 'User not found' + }; + } /* Creating the response objects */ const response: UserAPIResponse = { code: 200, message: 'OK' } as UserAPIResponse; const apiUser: APIUser = (await populateUserProperties(userResponse)) as APIUser; diff --git a/src/fetch.ts b/src/fetch.ts index c78c579..6c6ef68 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -231,6 +231,10 @@ export const fetchUser = async ( // Validator function (_res: unknown) => { const response = _res as GraphQLUserResponse; + // If _res.data is an empty object, we have no user + if (!Object.keys(response?.data).length) { + return false; + } return !( response?.data?.user?.result?.__typename !== 'User' || typeof response.data.user.result.legacy === 'undefined' diff --git a/test/index.test.ts b/test/index.test.ts index f5b06f0..6a8af41 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -270,3 +270,18 @@ test('API fetch user', async () => { expect(user.birthday.month).toEqual(3); expect(user.birthday.year).toBeUndefined(); }); + +test.only('API fetch user that does not exist', async () => { + const result = await cacheWrapper( + new Request('https://api.fxtwitter.com/usesaahah123', { + method: 'GET', + headers: botHeaders + }) + ); + expect(result.status).toEqual(404); + const response = (await result.json()) as UserAPIResponse; + expect(response).toBeTruthy(); + expect(response.code).toEqual(404); + expect(response.message).toEqual('User not found'); + expect(response.user).toBeUndefined(); +}); \ No newline at end of file