gql-multipart
Complementary middleware for express-graphql and koa-graphql which adds support parsing multipart request and file uploads.
Installation
$ npm install gql-multipart
API
gqlMultipartExpress()
This method creates middleware for Express library
gqlMultipartKoa()
This method creates middleware for Koa library
GQLMultipartOptions
- highWaterMark - integer: highWaterMark to use for multipart parser instance (Default: WritableStream default).
- fileHwm - integer: highWaterMark to use for temp file streams (Default: ReadableStream default).
- defCharset - string: Default character set to use when one isn't defined (Default: 'utf8').
- tempDir - string: Determines temp directory. Default OS temp directory.
- maxFieldNameSize - integer: Max field name size (in bytes) (Default: 100 bytes).
- maxFieldSize - integer: Max field value size (in bytes) (Default: 1MB).
- maxFields - integer: Max number of non-file fields (Default: Infinity).
- maxFileSize - integer: The max file size (in bytes) (Default: Infinity).
- maxFiles - integer: The max number of file fields (Default: Infinity).
- maxHeaderPairs - integer: The max number of header key=>value pairs to parse Default: 2000 (same as node's http).
Setup
Just mount express-graphql as a route handler before any graphql handler middleware.
Setup for Express
GraphQL schema used in following examples:
; const schema = ; const resolvers = { // return user instance } { // do anything with file const data = fs; return 'OK' } { for const f of files // do anything with file const data = fs; return 'OK'; } ; moduleexports = schema resolvers;
;;;; const app = ;app; // Must be mounted before express-graphqlapp;
Setup for Koa
;;;; const app = ;app; // Must be mounted before koa-graphqlapp;
Client implementation
Request can be send easily using any client implementation which supports multipart form data.
SPEC
Consider the following guidelines:
-
First part must contain graphql payload data as JSON encoded string and part name must be "payload"
-
Following parts must contain variables and names must start with "$" character.
-
Non string variables (number, boolean, array, object) must be encoded as JSON and Content-Type must be application/json.
-
To send array of file for single variable, use same part name.
Simple client using fetch
gql-multipart spec is very simple and you do not need any client implementations. Following example uses FormData and fetch() method.
{ const form = ; const payload = query: ` mutation ($userId: Int!, $file: File!) { uploadFile(userId: $userId, file: $file) }` ; form; form; form; return ;}
{ const form = ; const payload = query: ` mutation ($userId: Int!, $files: [File!]!) { uploadFiles(userId: $userId, files: $files) }` ; form; form; for const f of files form; return ;}
Sample request body
--------------------------5743007ba5b4Content-Disposition: form-data; name="payload"
Known client implementations
Compatibility
- node with Express
>= 6.x
; - node with Koa
>= 8.x
;