From 516bfb72e7f8bc34a95800640ad2045f1e4591cd Mon Sep 17 00:00:00 2001 From: Jesse Wierzbinski Date: Mon, 6 May 2024 08:31:12 +0000 Subject: [PATCH] fix(build): :bug: Add bodyOrJson middleware to server/api/v1/apps --- server/api/api/v1/apps/index.ts | 3 ++- tests/oauth.test.ts | 10 +++++++++- utils/api.ts | 34 +++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/server/api/api/v1/apps/index.ts b/server/api/api/v1/apps/index.ts index bac1335b..37b80324 100644 --- a/server/api/api/v1/apps/index.ts +++ b/server/api/api/v1/apps/index.ts @@ -1,5 +1,5 @@ import { randomBytes } from "node:crypto"; -import { applyConfig, handleZodError } from "@api"; +import { applyConfig, handleZodError, jsonOrForm } from "@api"; import { zValidator } from "@hono/zod-validator"; import { jsonResponse } from "@response"; import type { Hono } from "hono"; @@ -32,6 +32,7 @@ export default (app: Hono) => app.on( meta.allowedMethods, meta.route, + jsonOrForm(), zValidator("form", schemas.form, handleZodError), async (context) => { const { client_name, redirect_uris, scopes, website } = diff --git a/tests/oauth.test.ts b/tests/oauth.test.ts index 0b8e8329..ba3bf95b 100644 --- a/tests/oauth.test.ts +++ b/tests/oauth.test.ts @@ -34,7 +34,15 @@ describe("POST /api/v1/apps/", () => { const response = await sendTestRequest( new Request(new URL("/api/v1/apps", config.http.base_url), { method: "POST", - body: formData, + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + client_name: "Test Application", + website: "https://example.com", + redirect_uris: "https://example.com", + scopes: "read write", + }), }), ); diff --git a/utils/api.ts b/utils/api.ts index da0d7dfa..63bd38f6 100644 --- a/utils/api.ts +++ b/utils/api.ts @@ -152,3 +152,37 @@ export const qsQuery = () => { await next(); }); }; + +// Fill in queries, formData and json +export const jsonOrForm = () => { + return createMiddleware(async (context, next) => { + const contentType = context.req.header("content-type"); + + if (contentType?.includes("application/json")) { + context.req.parseBody = async () => + (await context.req.json()) as T; + context.req.bodyCache.formData = await context.req.json(); + } else if (contentType?.includes("application/x-www-form-urlencoded")) { + const parsed = parse(await context.req.text(), { + parseArrays: true, + interpretNumericEntities: true, + }); + + // @ts-ignore Very bad hack + context.req.formData = () => Promise.resolve(parsed); + // @ts-ignore I'm so sorry for this + context.req.bodyCache.formData = parsed; + } else { + const parsed = parse(await context.req.text(), { + parseArrays: true, + interpretNumericEntities: true, + }); + + // @ts-ignore Very bad hack + context.req.formData = () => Promise.resolve(parsed); + // @ts-ignore I'm so sorry for this + context.req.bodyCache.formData = parsed; + } + await next(); + }); +};