Gaurab Paul

Polyglot software developer & consultant passionate about web development, distributed systems and open source technologies

Support my blog and open-source work

Tags

Uploading files to MongoDB GridFS via Apollo powered GraphQL API
Posted  5 years ago

GraphQL multi-part request spec outlines a specification for multipart form requests in GraphQL. Jayden Seric, the author of the spec, has also authored two libraries apollo-upload-client and apollo-upload-server which makes it effortless to integrate file uploads in Apollo Server.

GridFS is a simple file system abstraction on top of MongoDB. This facilitates storage of large files (beyond BSON document size limit) in mongo database.

This post outlines the minimal integration required to save the files uploaded through the GraphQL API to GridFS.

We will use Koa as the HTTP server but the approach is applicable to any Apollo supported backend.

The Apollo-koa integration library comes built in with apollo-upload-server, so if we initialize our Apollo server and configure it use koa server, it will automatically configure body parser and enable file uploads.

Apollo server exports an Upload scalar type which we can use in our typedefs:

Now our add file resolver is ready to accept the incoming file stream and can pass it on to GridFS:

In order to facilitate uploading of files from the client, we need to configure Apollo client to use an upload link:

Note that using http link is no longer required, and any configuration options that could be passed to http link can be passed to createUploadLink. In fact, if http link is used before createUploadLink file uploads won’t work at all because http link is a terminal link and the upload link added after would not be used.

Now we can upload files to our GraphQL endpoint using Mutation component.

This concludes our server side as well as client side setup involved in connecting a file input field to mongodb gridfs.