graphql-upload 正在参加 2021 年度 OSC 中国开源项目评选,请投票支持!
graphql-upload 在 2021 年度 OSC 中国开源项目评选 中已获得 {{ projectVoteCount }} 票,请投票支持!
2021 年度 OSC 中国开源项目评选 正在火热进行中,快来投票支持你喜欢的开源项目!
2021 年度 OSC 中国开源项目评选 >>> 中场回顾
graphql-upload 获得 2021 年度 OSC 中国开源项目评选「最佳人气项目」 !
授权协议 Readme
开发语言 Java
操作系统 跨平台
软件类型 开源软件
所属分类 大数据数据查询
开源组织
地区 不详
投 递 者 首席测试
适用人群 未知
收录时间 2021-11-23

软件简介

graphql-upload logo

graphql-upload

npm version CI status

Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.

Setup

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.

Usage

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.

Tips

  • The process must have both read and write access to the directory identified by os.tmpdir().
  • The device requires sufficient disk space to buffer the expected number of concurrent upload requests.
  • Promisify and await file upload streams in resolvers or the server will send a response to the client before uploads are complete, causing a disconnect.
  • Handle file upload promise rejection and stream errors; uploads sometimes fail due to network connectivity issues or impatient users disconnecting.
  • Process multiple uploads asynchronously with Promise.all or a more flexible solution such as Promise.allSettled where an error in one does not reject them all.
  • Only use 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.
  • Use stream.destroy() when an incomplete stream is no longer needed, or temporary files may not get cleaned up.

Architecture

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.

Support

API

Table of contents

class GraphQLUpload

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.

Examples

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;
        },
      },
    },
  }),
});

class Upload

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.

Examples

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');

Upload instance method reject

Rejects the upload promise with an error. This should only be utilized by processRequest.

Parameter Type Description
error object Error instance.

Upload instance method resolve

Resolves the upload promise with the file upload details. This should only be utilized by processRequest.

Parameter Type Description
file FileUpload File upload details.

Upload instance property file

The file upload details, available when the upload promise resolves. This should only be utilized by processRequest.

Type: undefined | FileUpload

Upload instance property promise

Promise that resolves file upload details. This should only be utilized by GraphQLUpload.

Type: Promise<FileUpload>


function graphqlUploadExpress

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.

Examples

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);

function graphqlUploadKoa

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.

Examples

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);

function processRequest

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

Examples

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');

type FileUpload

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.

type FileUploadCreateReadStream

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.

See


type GraphQLOperation

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.

See


type ProcessRequestFunction

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).

See


type ProcessRequestOptions

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.
展开阅读全文

代码

评论 (0)

加载中
更多评论
暂无内容
发表了博客
2019/01/07 18:35

[GraphQL] Query a GraphQL API with graphql-request

To query a GraphQL API, all you need to do is send an HTTP request that includes the query operation in the body of the request. In this lesson, we will use the browser’s fetch method to request the total days skied from our GraphQL API. const query = ` query { totalDays } `; console.log("querying the count"); fetch("https://8lq1n313m2.sse.codesandbox.io", { method: "POST", ...

0
0
发表了博客
2019/03/05 23:03

GraphQL(一):GraphQL介绍

GraphQL(一):GraphQL介绍 GraphQL是什么 GraphQL是facebook开源的一套数据交互方案,它并非某种具体的语言或者框架,它只是提供了一套解决方案,这套解决方案通过GraphQL规范进行定义,不同语言可以有自己的GraphQL实现,目前已经有很多语言完成了GraphQL的实现,可以在这里查看。 怎么使用GraphQL GraphQL致力于提供一种直观的弹性语法系统,用以描述客户端程序设计时的数据需求以及数据交互行为。通俗地讲就是允许客户端在...

0
1
发表了博客
2019/01/21 18:50

GraphQL

GraphQL 官方描述: GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。 优点 GraphQL可以让我们通过请求控制返回的字段,以此来减少restful api的设计理念带来的请求多次的问题。 比如我们要获取指定id的文章相关...

0
0
发表了博客
2017/06/11 00:16

GraphQL

感谢支持ayqy个人订阅号,每周义务推送1篇(only unique one)原创精品博文,话题包括但不限于前端、Node、Android、数学(WebGL)、语文(课外书读后感)、英语(文档翻译) 如果觉得弱水三千,一瓢太少,可以去 http://blog.ayqy.net 看个痛快 写在前面 本文第一部分翻译自REST 2.0 Is Here and Its Name Is GraphQL,标题很有视觉冲击力,不小心上钩了 剩余部分是对GraphQL的思考。现在,我们边看译文边汇聚疑问 一.译文 Gr...

0
0
发表于软件架构专区
2020/08/03 19:48

GraphQL

网文、分享汇总 干货分享 | GraphQL 数据聚合层 http://www.sohu.com/a/235978606_205771 awesome-graphql https://github.com/chentsulin/awesome-graphql 一些graphql相关的java项目 周边项目 java GraphQL client https://github.com/americanexpress/nodes 同类后台 BaaS https://app.graphcms.com/ 可以创建schema、数据记录、查询api Baas https://www.graph.cool/docs/quickstart/ QuickStart https://www.graphql-java-...

0
0
发表于程序人生专区
2020/02/25 08:45

GraphQL[0x01] -- GraphQL基础实践

基础篇 理论知识 graphQL介绍 GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。它由Facebook开发和开源,强烈地表达了代码即文档的期望。能够精确有效地得到数据,没有冗余。 如果你想了解API设计的相关文章,那么我建议你去了解下SOAP协议,然后是Restful API协议,在业务不是很复杂的情况下,正常的Restful API的设计已经够用了,我们的graphQL的出现就是克Restful API的一些局限性的,遗憾的是,在企业...

0
0
发表于服务端专区
2019/08/02 12:04

go-graphql

关于golang的graphql入门学习教程,非常简单的数据结构,代码解释在注释里面. package main import ( "encoding/json" "errors" "fmt" "github.com/graphql-go/graphql" "github.com/graphql-go/graphql-go-handler" uuid "github.com/satori/go.uuid" "net/http" ) // Good 商品 type Good struct { ID string `json:"id"` // id Name string `json:"name"` // 名称 Price float64 `js...

0
0
发表了博客
2019/05/07 13:39

GraphQL简介

原文地址 https://flaviocopes.com/graphql/ 中译文地址 什么是GraphQL GraphQL的原则 GraphQL vs REST Rest是一个概念 单个端点 根据你的需求量身定制 GraphQL可以轻松监控字段的使用情况 访问嵌套数据资源 类型 哪一个更好? GraphQL查询 字段和参数 别名 片段 GraphQL变量 必选变量 指定变量的默认值 GraphQL指令 @include(if:Boolean) @skip(if:Boolean) 什么是GraphQL GraphQL是API技术的新前沿。 它是一种API查询语...

0
0
没有更多内容
加载失败,请刷新页面
点击加载更多
加载中
下一页
暂无内容
0 评论
0 收藏
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部