Skip to content

Commit

Permalink
fix: skip content type for non-body methods (#954)
Browse files Browse the repository at this point in the history
  • Loading branch information
juliusmarminge committed Sep 16, 2024
1 parent a769be0 commit 21677bb
Show file tree
Hide file tree
Showing 2 changed files with 167 additions and 3 deletions.
10 changes: 8 additions & 2 deletions packages/uploadthing/src/internal/to-web-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,19 @@ const parseURL = (req: IncomingMessageLike): Effect.Effect<URL, InvalidURL> => {
);
};

const isBodyAllowed = (method: string) =>
["POST", "PUT", "PATCH"].includes(method);

export const getPostBody = <TBody = unknown>(opts: {
req: IncomingMessageLike & {
on: (event: string, listener: (data: any) => void) => void;
};
}) =>
Effect.async<TBody, UploadThingError>((resume) => {
Effect.async<TBody | undefined, UploadThingError>((resume) => {
const { req } = opts;
if (!req.method || !isBodyAllowed(req.method)) {
return resume(Effect.succeed(undefined));
}
const contentType = req.headers?.["content-type"];

if ("body" in req) {
Expand Down Expand Up @@ -118,7 +124,7 @@ export const toWebRequest = (
body ??= req.body;
const bodyStr = typeof body === "string" ? body : JSON.stringify(body);
const method = req.method ?? "GET";
const allowsBody = ["POST", "PUT", "PATCH"].includes(method);
const allowsBody = isBodyAllowed(method);

const headers = new Headers();
for (const [key, value] of Object.entries(req.headers ?? [])) {
Expand Down
160 changes: 159 additions & 1 deletion packages/uploadthing/test/adapters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,28 @@ describe("adapters:h3", async () => {
.onUploadComplete(uploadCompleteMock),
};

it("returns router config on GET requests", async ({ db }) => {
const eventHandler = createRouteHandler({
router,
config: { token: testToken.encoded },
});

const res = await toWebHandler(createApp().use(eventHandler))(
new Request("http://localhost:3000"),
);

expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/json");

const json = await res.json();
expect(json).toEqual([
{
slug: "middleware",
config: expect.objectContaining({ blob: expect.objectContaining({}) }),
},
]);
});

it("gets H3Event in middleware args", async ({ db }) => {
const eventHandler = createRouteHandler({
router,
Expand Down Expand Up @@ -134,6 +156,26 @@ describe("adapters:server", async () => {
.onUploadComplete(uploadCompleteMock),
};

it("returns router config on GET requests", async ({ db }) => {
const eventHandler = createRouteHandler({
router,
config: { token: testToken.encoded },
});

const res = await eventHandler(new Request("http://localhost:3000"));

expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/json");

const json = await res.json();
expect(json).toEqual([
{
slug: "middleware",
config: expect.objectContaining({ blob: expect.objectContaining({}) }),
},
]);
});

it("gets Request in middleware args", async ({ db }) => {
const handler = createRouteHandler({
router,
Expand Down Expand Up @@ -211,6 +253,28 @@ describe("adapters:next", async () => {
.onUploadComplete(uploadCompleteMock),
};

it("returns router config on GET requests", async ({ db }) => {
const eventHandler = createRouteHandler({
router,
config: { token: testToken.encoded },
});

const res = await eventHandler.GET(
new NextRequest("http://localhost:3000"),
);

expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/json");

const json = await res.json();
expect(json).toEqual([
{
slug: "middleware",
config: expect.objectContaining({ blob: expect.objectContaining({}) }),
},
]);
});

it("gets NextRequest in middleware args", async ({ db }) => {
const handlers = createRouteHandler({
router,
Expand Down Expand Up @@ -291,7 +355,7 @@ describe("adapters:next-legacy", async () => {
};

function mockReq(opts: {
query: Record<string, any>;
query?: Record<string, any>;
method: string;
body?: unknown;
headers?: Record<string, string>;
Expand Down Expand Up @@ -324,6 +388,30 @@ describe("adapters:next-legacy", async () => {
return { res, json, setHeader, status };
}

it("returns router config on GET requests", async ({ db }) => {
const eventHandler = createRouteHandler({
router,
config: { token: testToken.encoded },
});

const { req } = mockReq({
method: "GET",
});
const { res, json, status } = mockRes();

await eventHandler(req, res);

expect(res.status).toHaveBeenCalledWith(200);

const resJson = (json.mock.calls[0] as any[])[0];
expect(resJson).toEqual([
{
slug: "middleware",
config: expect.objectContaining({ blob: expect.objectContaining({}) }),
},
]);
});

it("gets NextApiRequest and NextApiResponse in middleware args", async ({
db,
}) => {
Expand Down Expand Up @@ -425,6 +513,24 @@ describe("adapters:express", async () => {
return { url, close: () => server.close() };
};

it("returns router config on GET requests", async ({ db }) => {
const server = startServer();

const url = `${server.url}/api/uploadthing/`;
const res = await fetch(url);

expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/json");

const json = await res.json();
expect(json).toEqual([
{
slug: "middleware",
config: expect.objectContaining({ blob: expect.objectContaining({}) }),
},
]);
});

it("gets express.Request and express.Response in middleware args", async ({
db,
}) => {
Expand Down Expand Up @@ -563,6 +669,24 @@ describe("adapters:fastify", async () => {
return { url, close: () => app.close() };
};

it("returns router config on GET requests", async ({ db }) => {
const server = await startServer();

const url = `${server.url}api/uploadthing`;
const res = await fetch(url);

expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/json");

const json = await res.json();
expect(json).toEqual([
{
slug: "middleware",
config: expect.objectContaining({ blob: expect.objectContaining({}) }),
},
]);
});

it("gets fastify.FastifyRequest and fastify.FastifyReply in middleware args", async ({
db,
}) => {
Expand Down Expand Up @@ -648,6 +772,40 @@ describe("adapters:effect-platform", async () => {
.onUploadComplete(uploadCompleteMock),
};

it.effect("returns router config on GET requests", () =>
Effect.gen(function* () {
const eventHandler = createRouteHandler({
router,
config: { token: testToken.encoded },
}).pipe(Effect.provide(HttpClient.layer));

const serverRequest = HttpServerRequest.fromWeb(
new Request("http://localhost:3000"),
);
const response = yield* eventHandler.pipe(
Effect.provideService(
HttpServerRequest.HttpServerRequest,
serverRequest,
),
);
expect(response.status).toBe(200);
expect(response.headers["content-type"]).toBe("application/json");

const json = yield* Effect.promise(() =>
HttpServerResponse.toWeb(response).json(),
);

expect(json).toEqual([
{
slug: "middleware",
config: expect.objectContaining({
blob: expect.objectContaining({}),
}),
},
]);
}),
);

it.effect("gets HttpServerRequest in middleware args", () =>
Effect.gen(function* () {
const handler = createRouteHandler({
Expand Down

0 comments on commit 21677bb

Please sign in to comment.