• Stars
    star
    1,427
  • Rank 32,971 (Top 0.7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.

graphql-upload logo

graphql-upload

Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.

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.

Installation

Note

First, check if there are GraphQL multipart request spec server implementations (most for Node.js integrate graphql-upload) that are more suitable for your environment than a manual setup.

To install graphql-upload and its graphql peer dependency with npm, run:

npm install graphql-upload graphql

Use the middleware graphqlUploadKoa or graphqlUploadExpress just before GraphQL middleware. Alternatively, use the function processRequest to create custom middleware.

A schema built with separate SDL and resolvers (e.g. using the function makeExecutableSchema from @graphql-tools/schema) requires the Upload scalar to be setup.

Then, the Upload scalar can be used for query or mutation arguments. For how to use the scalar value in resolvers, see the documentation in the module GraphQLUpload.mjs.

Examples

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 such as Promise.allSettled where an error in one does not reject them all.
  • Only use the function 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 the function 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.

Requirements

Supported runtime environments:

  • Node.js versions ^14.17.0 || ^16.0.0 || >= 18.0.0.

Projects must configure TypeScript to use types from the ECMAScript modules that have a // @ts-check comment:

Exports

The npm package graphql-upload features optimal JavaScript module design. It doesnโ€™t have a main index module, so use deep imports from the ECMAScript modules that are exported via the package.json field exports:

More Repositories

1

apollo-upload-client

A terminating Apollo Link for Apollo Client that fetches a GraphQL multipart request if the GraphQL variables contain files (by default FileList, File, or Blob instances), or else fetches a regular GraphQL POST or GET request (depending on the config and GraphQL operation).
JavaScript
1,527
star
2

graphql-multipart-request-spec

A spec for GraphQL multipart form requests (file uploads).
994
star
3

graphql-react

A GraphQL client for React using modern context and hooks APIs that is lightweight (< 4 kB) but powerful; the first Relay and Apollo alternative with server side rendering.
JavaScript
718
star
4

apollo-upload-examples

A full stack demo of file uploads via GraphQL mutations using Apollo Server and apollo-upload-client.
JavaScript
427
star
5

ruck

Ruck is an open source buildless React web application framework for Deno.
JavaScript
149
star
6

Barebones

A barebones boilerplate for getting started on a bespoke front end.
JavaScript
125
star
7

Fix

A CSS normalization/reset reference.
CSS
123
star
8

next-graphql-react

A graphql-react integration for Next.js.
JavaScript
77
star
9

find-unused-exports

A Node.js CLI and equivalent JS API to find unused ECMAScript module exports in a project.
JavaScript
56
star
10

extract-files

A function to recursively extract files and their object paths within a value, replacing them with null in a deep clone without mutating the original value. FileList instances are treated as File instance arrays. Files are typically File and Blob instances.
JavaScript
54
star
11

coverage-node

A simple CLI to run Node.js and report code coverage.
JavaScript
53
star
12

graphql-api-koa

GraphQL execution and error handling middleware written from scratch for Koa.
JavaScript
52
star
13

svg-symbol-viewer

An online, no-upload drag-and-drop SVG file symbol extractor and viewer.
JavaScript
36
star
14

graphql-react-examples

Deno Ruck web app demonstrating graphql-react functionality using various GraphQL APIs.
JavaScript
36
star
15

Purty-Picker

A super lightweight visual HSL, RGB and hex color picker with a responsive, touch-friendly and customizable UI. Compatible with jQuery or Zepto.
JavaScript
36
star
16

fake-tag

A fake template literal tag to trick syntax highlighters, linters and formatters into action.
JavaScript
33
star
17

next-server-context

A Next.js App or page decorator, React context object, and React hook to access Node.js HTTP server context when rendering components.
JavaScript
31
star
18

jsdoc-md

A Node.js CLI and equivalent JS API to analyze source JSDoc and generate documentation under a given heading in a markdown file (such as readme.md).
JavaScript
26
star
19

next-router-events

A more powerful Next.js router events API.
JavaScript
26
star
20

test-director

An ultra lightweight unit test director for Node.js.
JavaScript
25
star
21

device-agnostic-ui

Device agnostic styles, components & hooks for React apps.
JavaScript
18
star
22

snapshot-assertion

Asserts a string matches a snapshot saved in a file. An environment variable can be used to save rather than assert snapshots.
JavaScript
16
star
23

Focal

Simulates a camera focus within a CSS 3D transform powered scene using CSS blur filters.
JavaScript
12
star
24

scroll-animator

Smart, lightweight functions to animate browser scroll.
JavaScript
12
star
25

graphql-http-test

A JavaScript API and CLI to test a GraphQL server for GraphQL over HTTP spec compliance.
JavaScript
12
star
26

eslint-config-env

ESLint config optimized for authoring packages that adapts to the project environment.
JavaScript
11
star
27

nova-deno

A Nova editor extension that integrates the Deno JavaScript/TypeScript runtime and tools.
JavaScript
9
star
28

webpack-watch-server

A single npm script command to start Webpack and your server in watch mode, with a unified console.
JavaScript
9
star
29

Skid

An ultra-lightweight slider utilizing Hurdler for URL hash based control.
JavaScript
8
star
30

Hurdler

Enables hash links to web page content hidden beneath layers of interaction.
JavaScript
7
star
31

audit-age

A Node.js CLI and equivalent JS API to audit the age of installed production npm packages.
JavaScript
7
star
32

ruck-website

The ruck.tech website for Ruck, an open source buildless React web application framework for Deno.
JavaScript
6
star
33

react-waterfall-render

Renders nested React components with asynchronous cached loading; useful for GraphQL clients and server side rendering.
JavaScript
6
star
34

babel-plugin-syntax-highlight

A Babel plugin that transforms the code contents of template literals lead by comments specifying a Prism.js language into syntax highlighted HTML.
JavaScript
6
star
35

google-static-maps-styler-query

Converts a Google Maps styler array to a Google Static Maps styler URL query string.
JavaScript
5
star
36

constraint-validation-buggyfill

Prevents invalid form submission in browsers that improperly support the HTML forms spec (i.e. Safari).
JavaScript
5
star
37

babel-plugin-transform-runtime-file-extensions

A Babel plugin that adds file extensions to Babel runtime import specifiers and require paths for Node.js ESM compatibility.
JavaScript
4
star
38

eslint-plugin-optimal-modules

An ESLint plugin to enforce optimal JavaScript module design.
JavaScript
4
star
39

install-from

Reliably installs a local package into another, for testing.
JavaScript
4
star
40

babel-plugin-transform-require-extensions

A Babel plugin that transforms specified require path file extensions.
JavaScript
3
star
41

device-agnostic-ui-website

The Device Agnostic UI website.
JavaScript
3
star
42

disposable-directory

Asynchronously creates a disposable directory in the OS temporary directory that gets deleted after the callback is done or errors.
JavaScript
3
star
43

class-name-prop

A lightweight utility function to create a React className prop value for multiple class names.
JavaScript
2
star
44

replace-stack-traces

A JavaScript function to replace error stack traces and following Node.js versions at any indent in a multiline string.
JavaScript
2
star
45

revertable-globals

Sets globals in a JavaScript environment that can be easily reverted to restore the original environment; useful for testing code that relies on the presence of certain globals.
JavaScript
2
star
46

eslint-config-barebones

Barebones ESLint config, extending JavaScript Standard Style.
JavaScript
1
star