Security News
The Unpaid Backbone of Open Source: Solo Maintainers Face Increasing Security Demands
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
graphql-upload
Advanced tools
Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.
The graphql-upload npm package provides middleware and utilities for handling file uploads in GraphQL APIs. It allows you to upload files via GraphQL mutations, making it easier to manage file uploads in a GraphQL-based server.
File Upload Middleware
This feature provides middleware for handling file uploads in an Express-based GraphQL server. The code sample demonstrates how to set up the middleware and define a mutation for uploading files.
const { graphqlUploadExpress } = require('graphql-upload');
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
const typeDefs = gql`
type File {
filename: String!
mimetype: String!
encoding: String!
}
type Query {
_ : Boolean
}
type Mutation {
uploadFile(file: Upload!): File!
}
`;
const resolvers = {
Mutation: {
uploadFile: async (parent, { file }) => {
const { createReadStream, filename, mimetype, encoding } = await file;
// Save the file to the filesystem or cloud storage here
return { filename, mimetype, encoding };
}
}
};
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
app.use(graphqlUploadExpress());
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () => {
console.log(`Server ready at http://localhost:4000${server.graphqlPath}`);
});
Handling File Streams
This feature demonstrates how to handle file streams in a GraphQL mutation. The code sample shows how to extract the file stream from the uploaded file and process it as needed.
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type File {
filename: String!
mimetype: String!
encoding: String!
}
type Query {
_ : Boolean
}
type Mutation {
uploadFile(file: Upload!): File!
}
`;
const resolvers = {
Mutation: {
uploadFile: async (parent, { file }) => {
const { createReadStream, filename, mimetype, encoding } = await file;
const stream = createReadStream();
// Process the file stream here (e.g., save to disk, cloud storage, etc.)
return { filename, mimetype, encoding };
}
}
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
The apollo-upload-server package provides similar functionality for handling file uploads in Apollo Server. It integrates seamlessly with Apollo Server and offers a straightforward way to manage file uploads in GraphQL APIs. Compared to graphql-upload, it is more tightly coupled with Apollo Server and may not be as flexible for use with other GraphQL server implementations.
Middleware and an Upload
scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.
First, check if there are GraphQL multipart request spec server implementations (most for Node.js integrate graphql-upload
) that are more suitable for your environment than a manual setup.
To install graphql-upload
and the graphql
peer dependency with npm, run:
npm install graphql-upload graphql
Use the graphqlUploadKoa
or graphqlUploadExpress
middleware just before GraphQL middleware. Alternatively, use processRequest
to create custom middleware.
A schema built with separate SDL and resolvers (e.g. using makeExecutableSchema
from @graphql-tools/schema
) requires the Upload
scalar to be setup.
Clients implementing the GraphQL multipart request spec upload files as Upload
scalar query or mutation variables. Their resolver values are promises that resolve file upload details for processing and storage. Files are typically streamed into cloud storage but may also be stored in the filesystem.
See the example API and client.
os.tmpdir()
.Promise.all
or a more flexible solution such as Promise.allSettled
where an error in one does not reject them all.createReadStream()
before the resolver returns; late calls (e.g. in an unawaited async function or callback) throw an error. Existing streams can still be used after a response is sent, although there are few valid reasons for not awaiting their completion.stream.destroy()
when an incomplete stream is no longer needed, or temporary files may not get cleaned up.The GraphQL multipart request spec allows a file to be used for multiple query or mutation variables (file deduplication), and for variables to be used in multiple places. GraphQL resolvers need to be able to manage independent file streams. As resolvers are executed asynchronously, it’s possible they will try to process files in a different order than received in the multipart request.
busboy
parses multipart request streams. Once the operations
and map
fields have been parsed, Upload
scalar values in the GraphQL operations are populated with promises, and the operations are passed down the middleware chain to GraphQL resolvers.
fs-capacitor
is used to buffer file uploads to the filesystem and coordinate simultaneous reading and writing. As soon as a file upload’s contents begins streaming, its data begins buffering to the filesystem and its associated promise resolves. GraphQL resolvers can then create new streams from the buffer by calling createReadStream()
. The buffer is destroyed once all streams have ended or closed and the server has responded to the request. Any remaining buffer files will be cleaned when the process exits.
^12.20 || >= 14.13
A GraphQL Upload
scalar that can be used in a GraphQLSchema
. It’s value in resolvers is a promise that resolves file upload details for processing and storage.
Ways to import
.
import { GraphQLUpload } from 'graphql-upload';
import GraphQLUpload from 'graphql-upload/public/GraphQLUpload.js';
Ways to require
.
const { GraphQLUpload } = require('graphql-upload');
const GraphQLUpload = require('graphql-upload/public/GraphQLUpload.js');
A schema built using makeExecutableSchema
from @graphql-tools/schema
.
const { makeExecutableSchema } = require('@graphql-tools/schema');
const { GraphQLUpload } = require('graphql-upload');
const schema = makeExecutableSchema({
typeDefs: /* GraphQL */ `
scalar Upload
`,
resolvers: {
Upload: GraphQLUpload,
},
});
A manually constructed schema with an image upload mutation.
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLBoolean,
} = require('graphql');
const { GraphQLUpload } = require('graphql-upload');
const schema = new GraphQLSchema({
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
uploadImage: {
description: 'Uploads an image.',
type: GraphQLBoolean,
args: {
image: {
description: 'Image file.',
type: GraphQLUpload,
},
},
async resolve(parent, { image }) {
const { filename, mimetype, createReadStream } = await image;
const stream = createReadStream();
// Promisify the stream and store the file, then…
return true;
},
},
},
}),
});
A file expected to be uploaded as it has been declared in the map
field of a GraphQL multipart request. The processRequest
function places references to an instance of this class wherever the file is expected in the GraphQL operation. The Upload
scalar derives it’s value from the promise
property.
Ways to import
.
import { Upload } from 'graphql-upload';
import Upload from 'graphql-upload/public/Upload.js';
Ways to require
.
const { Upload } = require('graphql-upload');
const Upload = require('graphql-upload/public/Upload.js');
Rejects the upload promise with an error. This should only be utilized by processRequest
.
Parameter | Type | Description |
---|---|---|
error | object | Error instance. |
Resolves the upload promise with the file upload details. This should only be utilized by processRequest
.
Parameter | Type | Description |
---|---|---|
file | FileUpload | File upload details. |
The file upload details, available when the upload promise resolves. This should only be utilized by processRequest
.
Type: undefined
| FileUpload
Promise that resolves file upload details. This should only be utilized by GraphQLUpload
.
Type: Promise<FileUpload>
Creates Express middleware that processes GraphQL multipart requests using processRequest
, ignoring non-multipart requests. It sets the request body to be similar to a conventional GraphQL POST request for following GraphQL middleware to consume.
Parameter | Type | Description |
---|---|---|
options | ProcessRequestOptions | Middleware options. Any ProcessRequestOptions can be used. |
options.processRequest | ProcessRequestFunction? = processRequest | Used to process GraphQL multipart requests. |
Returns: Function — Express middleware.
Ways to import
.
import { graphqlUploadExpress } from 'graphql-upload';
import graphqlUploadExpress from 'graphql-upload/public/graphqlUploadExpress.js';
Ways to require
.
const { graphqlUploadExpress } = require('graphql-upload');
const graphqlUploadExpress = require('graphql-upload/public/graphqlUploadExpress.js');
Basic express-graphql
setup.
const express = require('express');
const graphqlHTTP = require('express-graphql');
const { graphqlUploadExpress } = require('graphql-upload');
const schema = require('./schema');
express()
.use(
'/graphql',
graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }),
graphqlHTTP({ schema })
)
.listen(3000);
Creates Koa middleware that processes GraphQL multipart requests using processRequest
, ignoring non-multipart requests. It sets the request body to be similar to a conventional GraphQL POST request for following GraphQL middleware to consume.
Parameter | Type | Description |
---|---|---|
options | ProcessRequestOptions | Middleware options. Any ProcessRequestOptions can be used. |
options.processRequest | ProcessRequestFunction? = processRequest | Used to process GraphQL multipart requests. |
Returns: Function — Koa middleware.
Ways to import
.
import { graphqlUploadKoa } from 'graphql-upload';
import graphqlUploadKoa from 'graphql-upload/public/graphqlUploadKoa.js';
Ways to require
.
const { graphqlUploadKoa } = require('graphql-upload');
const graphqlUploadKoa = require('graphql-upload/public/graphqlUploadKoa.js');
Basic graphql-api-koa
setup.
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const { errorHandler, execute } = require('graphql-api-koa');
const { graphqlUploadKoa } = require('graphql-upload');
const schema = require('./schema');
new Koa()
.use(errorHandler())
.use(bodyParser())
.use(graphqlUploadKoa({ maxFileSize: 10000000, maxFiles: 10 }))
.use(execute({ schema }))
.listen(3000);
Processes a GraphQL multipart request. It parses the operations
and map
fields to create an Upload
instance for each expected file upload, placing references wherever the file is expected in the GraphQL operation for the Upload
scalar to derive it’s value. Errors are created with http-errors
to assist in sending responses with appropriate HTTP status codes. Used in graphqlUploadExpress
and graphqlUploadKoa
and can be used to create custom middleware.
Type: ProcessRequestFunction
Ways to import
.
import { processRequest } from 'graphql-upload';
import processRequest from 'graphql-upload/public/processRequest.js';
Ways to require
.
const { processRequest } = require('graphql-upload');
const processRequest = require('graphql-upload/public/processRequest.js');
File upload details that are only available after the file’s field in the GraphQL multipart request has begun streaming in.
Type: object
Property | Type | Description |
---|---|---|
filename | string | File name. |
mimetype | string | File MIME type. Provided by the client and can’t be trusted. |
encoding | string | File stream transfer encoding. |
createReadStream | FileUploadCreateReadStream | Creates a Node.js readable stream of the file’s contents, for processing and storage. |
Creates a Node.js readable stream of an uploading file’s contents, for processing and storage. Multiple calls create independent streams. Throws if called after all resolvers have resolved, or after an error has interrupted the request.
Type: Function
Parameter | Type | Description |
---|---|---|
options | object? | fs-capacitor ReadStreamOptions . |
options.encoding | string? = null | Specify an encoding for the data chunks to be strings (without splitting multi-byte characters across chunks) instead of Node.js Buffer instances. Supported values depend on the Buffer implementation and include utf8 , ucs2 , utf16le , latin1 , ascii , base64 , or hex . |
options.highWaterMark | number? = 16384 | Maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. |
Returns: Readable — Node.js readable stream of the file’s contents.
A GraphQL operation object in a shape that can be consumed and executed by most GraphQL servers.
Type: object
Property | Type | Description |
---|---|---|
query | string | GraphQL document containing queries and fragments. |
operationName | string | null ? | GraphQL document operation name to execute. |
variables | object | null ? | GraphQL document operation variables and values map. |
Processes a GraphQL multipart request.
Type: Function
Parameter | Type | Description |
---|---|---|
request | IncomingMessage | Node.js HTTP server request instance. |
response | ServerResponse | Node.js HTTP server response instance. |
options | ProcessRequestOptions? | Options for processing the request. |
Returns: Promise<GraphQLOperation | Array<GraphQLOperation>> — GraphQL operation or batch of operations for a GraphQL server to consume (usually as the request body).
Options for processing a GraphQL multipart request; mostly relating to security, performance and limits.
Type: object
Property | Type | Description |
---|---|---|
maxFieldSize | number? = 1000000 | Maximum allowed non-file multipart form field size in bytes; enough for your queries. |
maxFileSize | number? = Infinity | Maximum allowed file size in bytes. |
maxFiles | number? = Infinity | Maximum allowed number of files. |
FAQs
Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.
The npm package graphql-upload receives a total of 316,710 weekly downloads. As such, graphql-upload popularity was classified as popular.
We found that graphql-upload demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
Security News
License exceptions modify the terms of open source licenses, impacting how software can be used, modified, and distributed. Developers should be aware of the legal implications of these exceptions.
Security News
A developer is accusing Tencent of violating the GPL by modifying a Python utility and changing its license to BSD, highlighting the importance of copyleft compliance.