Enhances Apollo for intuitive file uploads via GraphQL mutations or queries. Use with apollo-upload-client.
With npm:
npm install apollo-upload-server
Add the server middleware just before graphql-server.
import { apolloUploadExpress } from 'apollo-upload-server'
// ✂
app.use(
'/graphql',
bodyParser.json(),
apolloUploadExpress({
// Optional, defaults to OS temp directory
uploadDir: '/tmp/uploads'
}),
graphqlExpress(/* ✂ */)
)
// ✂
import { apolloUploadKoa } from 'apollo-upload-server'
// ✂
router.post(
'/graphql',
apolloUploadKoa({
// Optional, defaults to OS temp directory
uploadDir: '/tmp/uploads'
}),
graphqlKoa(/* ✂ */)
)
// ✂
If the middleware you need is not available, import the asynchronous function
processRequest
to make your own:
import { processRequest } from 'apollo-upload-server'
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!
}
Also setup apollo-upload-client.
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.
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.
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
}