UNPKG

graphql-upload-ts

Version:

TypeScript-first middleware and Upload scalar for GraphQL multipart requests (file uploads) with support for Apollo Server, Express, Koa, and more.

68 lines 2.9 kB
import type { ServerResponse } from 'node:http'; import { type GraphQLOperation, type IncomingReq, type UploadOptions } from './process-request'; /** * Minimal shape of a Bunway `BunRequest` that `graphqlUploadBunway` reads. * Only the surface area actually used is required, so consumers aren't locked * into a specific bunway version or even a specific framework. */ export interface BunRequestLike { /** Original Fetch Request that bun gave the router. Must expose the URL, * method, and Fetch `Headers` used to drive busboy. */ original: { url: string; method: string; headers: { get(name: string): string | null; forEach(cb: (value: string, key: string) => void): void; }; }; /** Returns the original multipart request bytes. Bunway stashes these * before its body-parser consumes the body. */ rawBody(): Promise<Uint8Array>; /** Populated by this middleware on success (the parsed GraphQL operation * with `FileUpload` scalars substituted). Downstream handlers read this. */ body?: unknown; } /** * Minimal shape of a Bunway `BunResponse`. We install `.once` / `.on` shims * if they are missing, and call the existing `.end` / `.status` on errors. */ export interface BunResponseLike { status(code: number): BunResponseLike; end(body?: unknown): unknown; once?(event: string, listener: (...args: unknown[]) => void): BunResponseLike; on?(event: string, listener: (...args: unknown[]) => void): BunResponseLike; } export type BunwayNextFunction = (err?: unknown) => void; export type BunwayHandler = (req: BunRequestLike, res: BunResponseLike, next: BunwayNextFunction) => void; type ProcessRequestFn = <T = GraphQLOperation | GraphQLOperation[]>(req: IncomingReq, res: Pick<ServerResponse, 'once'>, options?: UploadOptions) => Promise<T>; export interface GraphqlUploadBunwayOptions extends UploadOptions { processRequest?: ProcessRequestFn; } /** * Creates a Bunway middleware for handling GraphQL multipart requests. * * @example * ```ts * import bunway from 'bunway'; * import { graphqlUploadBunway } from 'graphql-upload-ts'; * import { createYoga } from 'graphql-yoga'; * * const app = bunway(); * const yoga = createYoga({ schema, multipart: false }); * * app.all( * '/graphql', * graphqlUploadBunway({ maxFileSize: 20_000_000, maxFiles: 10 }), * yogaToBunwayHandler(yoga), * ); * ``` * * On success the middleware sets `req.body` to the parsed GraphQL operation * with `FileUpload` scalars substituted into the `variables` tree, then calls * `next()`. On a parse/validation error it calls `next(error)` with an * `HttpError` the caller can translate to a status code. */ export declare function graphqlUploadBunway(options?: GraphqlUploadBunwayOptions): BunwayHandler; export {}; //# sourceMappingURL=graphql-upload-bunway.d.ts.map