@jstwrt/apollo-upload-server

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

Stats

stars 🌟issues ⚠️updated 🛠created 🐣size 🏋️‍♀️
1,1414May 12, 2021Feb 24, 2017Minified + gzip package size for @jstwrt/apollo-upload-server in KB

Readme

Apollo upload logo

apollo-upload-server

npm version Licence Github issues Github stars

Enhances Apollo for intuitive file uploads via GraphQL mutations or queries. Use with apollo-upload-client.

Setup

Install

With npm:

npm install apollo-upload-server

Server middleware

Add the server middleware just before graphql-server.

Express

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

// ✂

app.use(
  '/graphql',
  bodyParser.json(),
  apolloUploadExpress({
    // Optional, defaults to OS temp directory
    uploadDir: '/tmp/uploads'
  }),
  graphqlExpress(/* ✂ */)
)

// ✂

Koa

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

// ✂

router.post(
  '/graphql',
  apolloUploadKoa({
    // Optional, defaults to OS temp directory
    uploadDir: '/tmp/uploads'
  }),
  graphqlKoa(/* ✂ */)
)

// ✂

Custom middleware

If the middleware you need is not available, import the asynchronous function processRequest to make your own:

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

GraphQL schema

Add an input type for uploads to your schema. You can name it anything but it must have this shape:

input Upload {
  name: String!
  type: String!
  size: Int!
  path: String!
}

Client

Also setup apollo-upload-client.

Usage

Once setup, you will be able to use FileList, File and ReactNativeFile instances anywhere within mutation or query input variables. See the client usage.

The files upload to a configurable temp directory. Upload input type metadata replaces file instances in the arguments received by the resolver.

Single file

In types:

type Mutation {
  updateUserAvatar(userId: String!, avatar: Upload!): User!
}

In resolvers:

updateUserAvatar(root, { userId, avatar }) {
  // ✂ Auth
  // ✂ Update avatar
  console.log(`New avatar for user ${userId} is ${avatar.size} bytes`)
  // ✂ Return fresh user data
}

See client usage for this example.

Multiple files

In types:

type Mutation {
  updateGallery(galleryId: String!, images: [Upload!]!): Gallery!
}

In resolvers:

updateGallery(root, { galleryId, images }) {
  // ✂ Auth
  // ✂ Update gallery
  console.log(`New images for gallery ${galleryId}:`)
  images.forEach((image, index) =>
    console.log(`Image ${index} is ${image.size} bytes`)
  )
  // ✂ Return fresh gallery data
}

See client usage for this example.

Support

  • Node.js: See package.json engines.
  • Koa.
  • Express.

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.