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. |
by Lucas McGartland 卢卡斯·麦加兰(Lucas McGartland) 如何使用Apollo / Graphene管理GraphQL突变中的文件上传 (How to manage file uploads in GraphQL mutations using Apollo/Graphene) GraphQL is an amazing way to query and mani
一、GraphQL简介 GraphQL是一种API查询语言,与SQL和数据库无关,但是两者有相似性,SQL是数据库查询语言,而GraphQL是API查询语言。它允许客户端定义响应结构(返回的字段及其类型),服务端接收请求后将返回指定的响应参数。例如下面请求示例要求返回id为1000的human的name和height: query { # query默认可以省略不写 human(id: "10
如果你想以声明式的方式工作,GraphQL 非常棒,它使你能够只选择你需要的信息或操作。但是,根据您的用例、性能要求和对不必要复杂性的容忍度,GraphQL 可能不适合您的项目。 在本文中,我们将回顾您应该考虑使用 REST 架构而不是 GraphQL 的一些原因。我们将讨论使用 GraphQL 的缺点,包括性能问题、GraphQL 模式问题和复杂查询。我们还将概述 GraphQL 的一些常见用例
介绍 (Introduction) I have been building GraphQL APIs in a Serverless environment for over 3 years now. I can't even imagine working with RESTful APIs anymore. Combine the power of GraphQL with the scal
I have one or two projects I maintain on Netlify, in addition to hosting my blog there. It’s an easy platform to deploy to, and has features for content management (CMS) and lambda functions (by way o
什么是GraphQL GraphQL一种API查询语言。 这正是GraphQL的强大之处,引用官方文档的一句话: ask exactly what you want. 我们在使用REST接口时,接口返回的数据格式、数据类型都是后端预先定义好的,如果返回的数据格式并不是调用者所期望的,作为前端的我们可以通过以下两种方式来解决问题: 和后端沟通,改接口(更改数据源) 自己做一些适配工作(处理数据源)
GraphQLScalarType ,可以理解为java 语言中的类型、对象。可以通过extends GraphQLScalarType实现自定义。 自定义分为两部分: java 代码 scheme 定义 java 代码如下 @Component public class MyStringScalarType extends GraphQLScalarType { private st
最近参与了一个大型项目,大型项目随着系统业务量的增大,不同的应用和系统共同使用着许多的服务接口API,而随着业务的变化和发展,不同的应用对相同资源的不同使用方法最终会导致需要维护的服务API数量呈现爆炸式的增长。而另一方面,创建一个大而全的通用性接口又非常不利于移动端使用(流量损耗),而且后端数据的无意义聚合也对整个系统带来了很大的资源浪费。 1、 GrapQL背景
快速开始 GraphQL 是一种用于 API 的查询语言。这是 GraphQL 和 REST 之间一个很好的比较 (译者注: GraphQL 替代 REST 是必然趋势)。在这组文章中, 我们不会解释什幺是 GraphQL, 而是演示如何使用 @nestjs/GraphQL 模块。 GraphQLModule 只不过是 Apollo 服务器的包装器。我们没有造轮子, 而是提供一个现成的模块, 这让
GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。 向你的 API 发出一个 GraphQL 请求就能准确获得你想要的数据,不多不少。 GraphQL 查询总是返回可预测
Graphql editor 是一款 Graphql 的可视化编辑器和 IDE,帮助用户更容易理解 GraphQL 模式,通过使用可视化块系统创建模式。GraphQL Editor 将把它们转化为代码。通过 GraphQL Editor,用户可以在不写任何代码的情况下创建可视化的图表,或者以一种很好的方式呈现其模式。 GraphQL View Code Editor View Hierarchy View
GraphQL CLI Help us to improve new GraphQL CLI. Check out the new structure and commands below!Feel free to contact us in Discord channel. We would love to hear your feedback. Features Helpful command
Fullstack GraphQL Simple Demo Application API built with Node + Express + GraphQL + Sequelize (supports MySQL, Postgres, Sqlite and MSSQL). WebApp built with React + Redux. Written in ES6 using Babel
Hasura GraphQL Engine Hasura is an open source product that accelerates API development by 10x by giving you GraphQL or REST APIs with built in authorization on your data, instantly. Read more at hasu