jamplay-apollo-upload-server

2.0.5 • Public • Published

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

Inspiration

Package Sidebar

Install

npm i jamplay-apollo-upload-server

Weekly Downloads

1

Version

2.0.5

License

MIT

Unpacked Size

25 kB

Total Files

8

Last publish

Collaborators

  • devdigithun