apollo-upload-server

Enhances Apollo GraphQL Server for intuitive file uploads via GraphQL mutations.

Please migrate to https://npm.im/graphql-upload (see https://git.io/fADhl).
Last updated 7 years ago by jaydenseric .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ npm install apollo-upload-server 
SYNC missed versions from official npm registry.

Apollo upload logo

apollo-upload-server

npm version Build 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.

Support

The following environments are known to be compatible, or feature this package built in:

See also GraphQL multipart request spec server implementations.

Setup

Setup is necessary if your environment doesn’t feature this package built in (see Support).

To install apollo-upload-server and the graphql peer dependency from npm run:

npm install apollo-upload-server graphql

Use the apolloUploadKoa or apolloUploadExpress middleware just before GraphQL middleware. Alternatively, use processRequest to create custom middleware.

A schema built with separate SDL and resolvers (e.g. using makeExecutableSchema) 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 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.

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

Setup for a schema built with makeExecutableSchema.

import { makeExecutableSchema } from 'graphql-tools'
import { GraphQLUpload } from 'apollo-upload-server'

const typeDefs = `
  scalar Upload
`

const resolvers = {
  Upload: GraphQLUpload
}

export const schema = makeExecutableSchema({ typeDefs, resolvers })

A manually constructed schema with an image upload mutation.

import { GraphQLSchema, GraphQLObjectType, GraphQLBoolean } from 'graphql'
import { GraphQLUpload } from 'apollo-upload-server'

export 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
        }
      }
    }
  })
})

function apolloUploadExpress

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 UploadOptions GraphQL upload options.

Returns: function — Express middleware.

Examples

Basic express-graphql setup.

import express from 'express'
import graphqlHTTP from 'express-graphql'
import { apolloUploadExpress } from 'apollo-upload-server'
import schema from './schema'

express()
  .use(
    '/graphql',
    apolloUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }),
    graphqlHTTP({ schema })
  )
  .listen(3000)

function apolloUploadKoa

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 UploadOptions GraphQL upload options.

Returns: function — Koa middleware.

Examples

Basic graphql-api-koa setup.

import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import { errorHandler, execute } from 'graphql-api-koa'
import { apolloUploadKoa } from 'apollo-upload-server'
import schema from './schema'

new Koa()
  .use(errorHandler())
  .use(bodyParser())
  .use(apolloUploadKoa({ maxFileSize: 10000000, maxFiles: 10 }))
  .use(execute({ schema }))
  .listen(3000)

function processRequest

Processes a GraphQL multipart request. Used in apolloUploadKoa and apolloUploadExpress and can be used to create custom middleware.

Parameter Type Description
request IncomingMessage Node.js HTTP server request instance.
response ServerResponse Node.js HTTP server response instance.
options UploadOptions? GraphQL upload options.

Returns: Promise<GraphQLOperation | Array<GraphQLOperation>> — GraphQL operation or batch of operations for a GraphQL server to consume (usually as the request body).

Examples

How to import.

import { processRequest } from 'apollo-upload-server'

type FileUpload

File upload details, resolved from an Upload scalar promise.

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 function Returns a Node.js readable stream of the file contents, for processing and storing the file. Multiple calls create independent streams. Throws if called after all resolvers have resolved, or after an error has interrupted the request.

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 UploadOptions

GraphQL upload server options, 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.

Current Tags

  • 7.1.0                                ...           latest (6 years ago)

21 Versions

  • 7.1.0 [deprecated]           ...           6 years ago
  • 7.0.0 [deprecated]           ...           6 years ago
  • 6.0.0-alpha.1                                ...           6 years ago
  • 5.0.0 [deprecated]           ...           7 years ago
  • 4.0.2 [deprecated]           ...           7 years ago
  • 4.0.1 [deprecated]           ...           7 years ago
  • 4.0.0 [deprecated]           ...           7 years ago
  • 4.0.0-alpha.3                                ...           7 years ago
  • 4.0.0-alpha.2                                ...           7 years ago
  • 4.0.0-alpha.1                                ...           7 years ago
  • 3.0.0 [deprecated]           ...           7 years ago
  • 2.0.4 [deprecated]           ...           7 years ago
  • 2.0.3 [deprecated]           ...           8 years ago
  • 2.0.2 [deprecated]           ...           8 years ago
  • 2.0.1 [deprecated]           ...           8 years ago
  • 2.0.0 [deprecated]           ...           8 years ago
  • 1.1.1 [deprecated]           ...           8 years ago
  • 1.1.0 [deprecated]           ...           8 years ago
  • 1.0.2 [deprecated]           ...           8 years ago
  • 1.0.1 [deprecated]           ...           8 years ago
  • 1.0.0 [deprecated]           ...           8 years ago
Maintainers (1)
Downloads
Total 3
Today 0
This Week 0
This Month 1
Last Day 0
Last Week 1
Last Month 0
Dependencies (3)
Dev Dependencies (15)

© 2010 - cnpmjs.org x YWFE | Home | YWFE