Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(server-handler): forward original request #592

Merged
merged 3 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/afraid-terms-live.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"uploadthing": patch
---

fix(server-handler): forward original request
18 changes: 12 additions & 6 deletions packages/uploadthing/src/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,26 @@ import { createBuilder } from "./internal/upload-builder";

export type { FileRouter };

type MiddlewareArgs = {
req: ExpressRequest;
res: ExpressResponse;
event: undefined;
};

export const createUploadthing = <TErrorShape extends Json>(
opts?: CreateBuilderOptions<TErrorShape>,
) =>
createBuilder<
{ req: ExpressRequest; res: ExpressResponse; event: undefined },
TErrorShape
>(opts);
) => createBuilder<MiddlewareArgs, TErrorShape>(opts);

export const createRouteHandler = <TRouter extends FileRouter>(
opts: RouterWithConfig<TRouter>,
): ExpressRouter => {
initLogger(opts.config?.logLevel);
incompatibleNodeGuard();

const requestHandler = buildRequestHandler<TRouter>(opts, "express");
const requestHandler = buildRequestHandler<TRouter, MiddlewareArgs>(
opts,
"express",
);
const getBuildPerms = buildPermissionsInfoHandler<TRouter>(opts);
const router = ExpressRouter();

Expand Down Expand Up @@ -72,6 +77,7 @@ export const createRouteHandler = <TRouter extends FileRouter>(
nativeRequest: toWebRequest(req, url, bodyResult.data),
originalRequest: req,
res,
event: undefined,
});

if (response instanceof UploadThingError) {
Expand Down
18 changes: 12 additions & 6 deletions packages/uploadthing/src/fastify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ import { createBuilder } from "./internal/upload-builder";

export type { FileRouter };

type MiddlewareArgs = {
req: FastifyRequest;
res: FastifyReply;
event: undefined;
};

export const createUploadthing = <TErrorShape extends Json>(
opts?: CreateBuilderOptions<TErrorShape>,
) =>
createBuilder<
{ req: FastifyRequest; res: FastifyReply; event: undefined },
TErrorShape
>(opts);
) => createBuilder<MiddlewareArgs, TErrorShape>(opts);

export const createRouteHandler = <TRouter extends FileRouter>(
fastify: FastifyInstance,
Expand All @@ -40,7 +42,10 @@ export const createRouteHandler = <TRouter extends FileRouter>(
initLogger(opts.config?.logLevel);
incompatibleNodeGuard();

const requestHandler = buildRequestHandler<TRouter>(opts, "fastify");
const requestHandler = buildRequestHandler<TRouter, MiddlewareArgs>(
opts,
"fastify",
);
const getBuildPerms = buildPermissionsInfoHandler<TRouter>(opts);

const POST: RouteHandlerMethod = async (req, res) => {
Expand All @@ -51,6 +56,7 @@ export const createRouteHandler = <TRouter extends FileRouter>(
nativeRequest: toWebRequest(req, url),
originalRequest: req,
res,
event: undefined,
});

if (response instanceof UploadThingError) {
Expand Down
15 changes: 9 additions & 6 deletions packages/uploadthing/src/h3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,22 @@ import { createBuilder } from "./internal/upload-builder";

export type { FileRouter };

type MiddlewareArgs = { req: undefined; res: undefined; event: H3Event };

export const createUploadthing = <TErrorShape extends Json>(
opts?: CreateBuilderOptions<TErrorShape>,
) =>
createBuilder<
{ req: undefined; res: undefined; event: H3Event },
TErrorShape
>(opts);
) => createBuilder<MiddlewareArgs, TErrorShape>(opts);

export const createRouteHandler = <TRouter extends FileRouter>(
opts: RouterWithConfig<TRouter>,
) => {
initLogger(opts.config?.logLevel);
incompatibleNodeGuard();

const requestHandler = buildRequestHandler(opts, "h3");
const requestHandler = buildRequestHandler<TRouter, MiddlewareArgs>(
opts,
"h3",
);
const getBuildPerms = buildPermissionsInfoHandler<TRouter>(opts);

return defineEventHandler(async (event) => {
Expand All @@ -55,6 +56,8 @@ export const createRouteHandler = <TRouter extends FileRouter>(
const response = await requestHandler({
nativeRequest: toWebRequest(event),
event,
originalRequest: undefined,
res: undefined,
});

if (response instanceof UploadThingError) {
Expand Down
18 changes: 13 additions & 5 deletions packages/uploadthing/src/internal/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ import type { LogLevel } from "./logger";
import { logger } from "./logger";
import { getParseFn } from "./parser";
import { VALID_ACTION_TYPES } from "./types";
import type { ActionType, FileRouter, UTEvents } from "./types";
import type {
ActionType,
FileRouter,
MiddlewareFnArgs,
UTEvents,
} from "./types";

/**
* Creates a wrapped fetch that will always forward a few headers to the server.
Expand Down Expand Up @@ -128,17 +133,20 @@ export type UploadThingResponse = {
chunkSize: number;
}[];

export const buildRequestHandler = <TRouter extends FileRouter>(
export const buildRequestHandler = <
TRouter extends FileRouter,
Args extends MiddlewareFnArgs<any, any, any>,
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added the generic here for extra typesafety and prevent future regressions when adding new adapters etc. now it must match what the adapter has put in their createUploadthing() generic

>(
opts: RouterWithConfig<TRouter>,
adapter: string,
) => {
return async (input: {
nativeRequest: Request;

// Forward to middleware handler
originalRequest?: unknown;
res?: unknown;
event?: unknown;
originalRequest: Args["req"];
res: Args["res"];
event: Args["event"];
}): Promise<
| UploadThingError
| { status: 200; body?: UploadThingResponse; cleanup?: Promise<unknown> }
Expand Down
18 changes: 12 additions & 6 deletions packages/uploadthing/src/next-legacy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,26 @@ import { createBuilder } from "./internal/upload-builder";

export type { FileRouter };

type MiddlewareArgs = {
req: NextApiRequest;
res: NextApiResponse;
event: undefined;
};

export const createUploadthing = <TErrorShape extends Json>(
opts?: CreateBuilderOptions<TErrorShape>,
) =>
createBuilder<
{ req: NextApiRequest; res: NextApiResponse; event: undefined },
TErrorShape
>(opts);
) => createBuilder<MiddlewareArgs, TErrorShape>(opts);

export const createRouteHandler = <TRouter extends FileRouter>(
opts: RouterWithConfig<TRouter>,
) => {
initLogger(opts.config?.logLevel);
incompatibleNodeGuard();

const requestHandler = buildRequestHandler<TRouter>(opts, "nextjs-pages");
const requestHandler = buildRequestHandler<TRouter, MiddlewareArgs>(
opts,
"nextjs-pages",
);
const getBuildPerms = buildPermissionsInfoHandler<TRouter>(opts);

return async (req: NextApiRequest, res: NextApiResponse) => {
Expand All @@ -53,6 +58,7 @@ export const createRouteHandler = <TRouter extends FileRouter>(
nativeRequest: toWebRequest(req, url),
originalRequest: req,
res,
event: undefined,
});

res.setHeader("x-uploadthing-version", UPLOADTHING_VERSION);
Expand Down
20 changes: 13 additions & 7 deletions packages/uploadthing/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,11 @@ export * from "./internal/types";
export { UTApi } from "./sdk";
export { UploadThingError };

type MiddlewareArgs = { req: Request; res: undefined; event: undefined };

export const createUploadthing = <TErrorShape extends Json>(
opts?: CreateBuilderOptions<TErrorShape>,
) =>
createBuilder<
{ req: Request; res: undefined; event: undefined },
TErrorShape
>(opts);
) => createBuilder<MiddlewareArgs, TErrorShape>(opts);

export interface ResponseWithCleanup extends Response {
/** custom property where a Promise may be put that you can await in for example Cloudflare Workers */
Expand All @@ -41,14 +39,22 @@ export const INTERNAL_DO_NOT_USE_createRouteHandlerCore = <
initLogger(opts.config?.logLevel);
incompatibleNodeGuard();

const requestHandler = buildRequestHandler<TRouter>(opts, adapter);
const requestHandler = buildRequestHandler<TRouter, MiddlewareArgs>(
opts,
adapter,
);
const getBuildPerms = buildPermissionsInfoHandler<TRouter>(opts);

const POST = async (
request: Request | { request: Request },
): Promise<Response | ResponseWithCleanup> => {
const req = request instanceof Request ? request : request.request;
const response = await requestHandler({ nativeRequest: req });
const response = await requestHandler({
nativeRequest: req,
originalRequest: req,
event: undefined,
res: undefined,
});

if (response instanceof UploadThingError) {
return new Response(JSON.stringify(formatError(response, opts.router)), {
Expand Down
Loading