From f36a689817b5349d8dba1eadb9c1e6d91482e0d4 Mon Sep 17 00:00:00 2001 From: Mike Cao Date: Fri, 28 Jul 2023 23:59:32 -0700 Subject: [PATCH] Refactored payload validation. --- pages/api/send.ts | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/pages/api/send.ts b/pages/api/send.ts index 8c88c509..f90ded77 100644 --- a/pages/api/send.ts +++ b/pages/api/send.ts @@ -54,7 +54,11 @@ export default async (req: NextApiRequestCollect, res: NextApiResponse) => { const { type, payload } = getJsonBody(req); - validateBody(res, { type, payload }); + const error = validateBody({ type, payload }); + + if (error) { + return badRequest(res, error); + } if (await hasBlockedIp(req)) { return forbidden(res); @@ -114,17 +118,19 @@ export default async (req: NextApiRequestCollect, res: NextApiResponse) => { return send(res, token); }; -function validateBody(res: NextApiResponse, { type, payload }: CollectRequestBody) { - const { data } = payload || {}; - - // Validate type - if (type !== COLLECTION_TYPE.event && type !== COLLECTION_TYPE.identify) { - return badRequest(res, 'Wrong payload type.'); +function validateBody({ type, payload }: CollectRequestBody) { + if (!type || !payload) { + return 'Invalid payload.'; } - // Validate eventData is JSON + if (type !== COLLECTION_TYPE.event && type !== COLLECTION_TYPE.identify) { + return 'Wrong payload type.'; + } + + const { data } = payload; + if (data && !(typeof data === 'object' && !Array.isArray(data))) { - return badRequest(res, 'Invalid event data.'); + return 'Invalid event data.'; } }