├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .npmrc ├── .prettierrc ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── index.ts ├── package.json ├── test ├── basic.test.ts └── build-server.ts └── tsconfig.json /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Node.js CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | node-version: [20.x, 22.x] 11 | os: [ubuntu-latest, windows-latest, macOS-latest] 12 | steps: 13 | - uses: actions/checkout@v3 14 | - name: Use Node.js ${{ matrix.node-version }} 15 | uses: actions/setup-node@v3 16 | with: 17 | node-version: ${{ matrix.node-version }} 18 | - name: Install Dependencies 19 | run: npm install --ignore-scripts 20 | - name: Test 21 | run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .nyc_output 3 | dist 4 | package-lock.json 5 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=true 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "printWidth": 80, 4 | "semi": false, 5 | "endOfLine": "lf" 6 | } 7 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib" 3 | } 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Pablo Sáez 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mercurius-upload 2 | 3 | [graphql-upload-minimal](https://github.com/flash-oss/graphql-upload-minimal) implementation plugin for [Fastify](https://www.fastify.io/) & [mercurius](https://github.com/mercurius-js/mercurius). 4 | 5 | Plugin made for **Fastify v5**: 6 | 7 | ## Install 8 | 9 | ```sh 10 | yarn add mercurius-upload 11 | # or 12 | npm i mercurius-upload 13 | # or 14 | pnpm add mercurius-upload 15 | ``` 16 | 17 | ## Usage 18 | 19 | Plugin options should conform to https://github.com/flash-oss/graphql-upload-minimal#type-processrequestoptions 20 | 21 | ```js 22 | fastify.register(require('mercurius-upload'), { 23 | // options passed to processRequest from graphql-upload-minimal 24 | // maxFileSize: 1024 * 1024 * 5, 25 | // maxFiles: 1, 26 | }) 27 | ``` 28 | 29 | > or 30 | 31 | ```ts 32 | import MercuriusGQLUpload from 'mercurius-upload' 33 | 34 | // ... 35 | 36 | fastify.register(MercuriusGQLUpload, { 37 | // options passed to processRequest from graphql-upload-minimal 38 | }) 39 | ``` 40 | 41 | ## Example 42 | 43 | ```js 44 | const GQL = require('mercurius') 45 | const { GraphQLUpload } = require('graphql-upload-minimal') 46 | const fs = require('fs') 47 | const util = require('util') 48 | const stream = require('stream') 49 | const path = require('path') 50 | 51 | const pipeline = util.promisify(stream.pipeline) 52 | const uploadsDir = path.resolve(__dirname, '../uploads') 53 | 54 | const schema = /* GraphQL */ ` 55 | scalar Upload 56 | 57 | type Query { 58 | add(x: Int, y: Int): Int 59 | } 60 | 61 | type Mutation { 62 | uploadImage(image: Upload): Boolean 63 | } 64 | ` 65 | 66 | const resolvers = { 67 | Upload: GraphQLUpload, 68 | Query: { 69 | add: async (_, { x, y }) => { 70 | return x + y 71 | }, 72 | }, 73 | Mutation: { 74 | uploadImage: async (_, { image }) => { 75 | const { filename, createReadStream } = await image 76 | const rs = createReadStream() 77 | const ws = fs.createWriteStream(path.join(uploadsDir, filename)) 78 | await pipeline(rs, ws) 79 | return true 80 | }, 81 | }, 82 | } 83 | 84 | module.exports = function (fastify, options, done) { 85 | fastify.register(require('mercurius-upload')) 86 | 87 | fastify.register(GQL, { 88 | schema, 89 | resolvers, 90 | graphiql: true, 91 | }) 92 | 93 | done() 94 | } 95 | ``` 96 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import * as util from 'util' 2 | import stream from 'stream' 3 | import fp from 'fastify-plugin' 4 | import { processRequest, UploadOptions } from 'graphql-upload-minimal' 5 | 6 | const finishedStream = util.promisify(stream.finished) 7 | 8 | import type { FastifyPluginCallback } from 'fastify' 9 | 10 | declare module 'fastify' { 11 | interface FastifyRequest { 12 | mercuriusUploadMultipart?: true 13 | } 14 | } 15 | 16 | const mercuriusGQLUpload: FastifyPluginCallback = ( 17 | fastify, 18 | options, 19 | done, 20 | ) => { 21 | fastify.addContentTypeParser('multipart/form-data', (req, _payload, done) => { 22 | req.mercuriusUploadMultipart = true 23 | done(null) 24 | }) 25 | 26 | fastify.addHook('preValidation', async function (request, reply) { 27 | if (!request.mercuriusUploadMultipart) { 28 | return 29 | } 30 | 31 | request.body = await processRequest(request.raw, reply.raw, options) 32 | }) 33 | 34 | fastify.addHook('onSend', async function (request) { 35 | if (!request.mercuriusUploadMultipart) { 36 | return 37 | } 38 | 39 | await finishedStream(request.raw) 40 | }) 41 | 42 | done() 43 | } 44 | 45 | export const mercuriusUpload = fp(mercuriusGQLUpload, { 46 | fastify: '5.x', 47 | name: 'mercurius-upload', 48 | }) 49 | 50 | export default mercuriusUpload 51 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mercurius-upload", 3 | "version": "8.0.0", 4 | "description": "Fastify plugin to support GraphQL uploads using graphql-upload", 5 | "keywords": [ 6 | "fastify", 7 | "mercurius", 8 | "gql", 9 | "graphql", 10 | "upload", 11 | "file", 12 | "files", 13 | "typescript" 14 | ], 15 | "homepage": "https://github.com/mercurius-js/mercurius-upload#readme", 16 | "bugs": { 17 | "url": "https://github.com/mercurius-js/mercurius-upload/issues" 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/mercurius-js/mercurius-upload.git" 22 | }, 23 | "license": "ISC", 24 | "author": "PabloSzx", 25 | "main": "dist/index.js", 26 | "types": "dist/index.d.ts", 27 | "files": [ 28 | "dist" 29 | ], 30 | "scripts": { 31 | "prepack": "tsc && prettier --write dist index.ts test", 32 | "test": "tap --ts --100 test/*.test.ts" 33 | }, 34 | "dependencies": { 35 | "fastify-plugin": "^5.0.1", 36 | "graphql-upload-minimal": "^1.6.1" 37 | }, 38 | "devDependencies": { 39 | "@types/node": "^20.5.0", 40 | "@types/tap": "^15.0.7", 41 | "cross-env": "^7.0.3", 42 | "fastify": "^5.0.0", 43 | "form-data": "^4.0.1", 44 | "graphql": "^16.5.0", 45 | "mercurius": "^15.0.0", 46 | "prettier": "^3.3.3", 47 | "tap": "^16.2.0", 48 | "ts-node": "^10.9.2", 49 | "typescript": "^5.6.3" 50 | }, 51 | "peerDependencies": { 52 | "graphql": "^16.3.0" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /test/basic.test.ts: -------------------------------------------------------------------------------- 1 | import tap from 'tap' 2 | import FormData from 'form-data' 3 | import { build } from './build-server' 4 | 5 | tap.test('mercurius-upload - should work', async (t) => { 6 | const server = build() 7 | await server.ready() 8 | 9 | const body = new FormData() 10 | 11 | const query = /* GraphQL */ ` 12 | mutation UploadImage($image: Upload!) { 13 | uploadImage(image: $image) 14 | } 15 | ` 16 | const operations = { 17 | query, 18 | variables: { image: null }, 19 | } 20 | 21 | const fileData = 'abcd' 22 | const uploadFilename = 'a.png' 23 | 24 | body.append('operations', JSON.stringify(operations)) 25 | body.append('map', JSON.stringify({ '1': ['variables.image'] })) 26 | body.append('1', fileData, { filename: uploadFilename }) 27 | 28 | const res = await server.inject({ 29 | method: 'POST', 30 | url: '/graphql', 31 | headers: body.getHeaders(), 32 | payload: body, 33 | }) 34 | 35 | t.equal(res.statusCode, 200) 36 | t.same(JSON.parse(res.body), { data: { uploadImage: fileData } }) 37 | 38 | await server.close() 39 | }) 40 | 41 | tap.test('Normal gql query should work', async (t) => { 42 | const server = build() 43 | await server.ready() 44 | 45 | const query = '{ add(x: 2, y: 2) }' 46 | 47 | const res = await server.inject({ 48 | method: 'POST', 49 | url: '/graphql', 50 | headers: { 51 | 'content-type': 'application/json', 52 | }, 53 | payload: JSON.stringify({ 54 | query, 55 | }), 56 | }) 57 | 58 | t.equal(res.statusCode, 200) 59 | t.same(JSON.parse(res.body), { 60 | data: { 61 | add: 4, 62 | }, 63 | }) 64 | 65 | await server.close() 66 | }) 67 | 68 | tap.test('A normal http request to another route should work', async (t) => { 69 | const server = build() 70 | await server.ready() 71 | const res = await server.inject({ method: 'GET', url: '/' }) 72 | 73 | t.same(res.statusCode, 200) 74 | t.same(res.headers['content-type'], 'application/json; charset=utf-8') 75 | t.same(JSON.parse(res.payload), { hello: 'world' }) 76 | await server.close() 77 | }) 78 | -------------------------------------------------------------------------------- /test/build-server.ts: -------------------------------------------------------------------------------- 1 | import fastify from 'fastify' 2 | import GQL from 'mercurius' 3 | import { GraphQLUpload } from 'graphql-upload-minimal' 4 | import mercuriusGQLUpload from '../index' 5 | 6 | const schema = /* GraphQL */ ` 7 | scalar Upload 8 | type Query { 9 | add(x: Int, y: Int): Int 10 | } 11 | type Mutation { 12 | uploadImage(image: Upload): String 13 | } 14 | ` 15 | 16 | export function build() { 17 | const app = fastify() 18 | 19 | app.register(mercuriusGQLUpload) 20 | 21 | app.register(GQL, { 22 | schema, 23 | resolvers: { 24 | Upload: GraphQLUpload, 25 | Query: { 26 | add: async (_, { x, y }) => { 27 | return x + y 28 | }, 29 | }, 30 | Mutation: { 31 | uploadImage: async (_: unknown, { image }) => { 32 | const { createReadStream } = await image 33 | const rs = createReadStream() 34 | 35 | let data = '' 36 | 37 | for await (const chunk of rs) { 38 | data += chunk 39 | } 40 | 41 | return data 42 | }, 43 | }, 44 | }, 45 | }) 46 | 47 | app.get('/', async (_request, _reply) => { 48 | return { hello: 'world' } 49 | }) 50 | 51 | return app 52 | } 53 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es2018" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, 8 | "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | "declaration": true /* Generates corresponding '.d.ts' file. */, 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | "outDir": "./dist" /* Redirect output structure to the directory. */, 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true /* Enable all strict type-checking options. */, 29 | "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, 30 | "strictNullChecks": true /* Enable strict null checks. */, 31 | "strictFunctionTypes": true /* Enable strict checking of function types. */, 32 | "strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */, 33 | "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */, 34 | "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */, 35 | "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, 36 | 37 | /* Additional Checks */ 38 | "noUnusedLocals": true /* Report errors on unused locals. */, 39 | "noUnusedParameters": true /* Report errors on unused parameters. */, 40 | "noImplicitReturns": true /* Report error when not all code paths in function return a value. */, 41 | "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */, 42 | 43 | /* Module Resolution Options */ 44 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [], /* Type declaration files to be included in compilation. */ 50 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 51 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | 55 | /* Source Map Options */ 56 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 59 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | 61 | /* Experimental Options */ 62 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 63 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 64 | 65 | /* Advanced Options */ 66 | "skipLibCheck": true /* Skip type checking of declaration files. */, 67 | "forceConsistentCasingInFileNames": true, /* Disallow inconsistently-cased references to the same file. */ 68 | 69 | "allowJs": true, 70 | "maxNodeModuleJsDepth": 10 71 | }, 72 | "include": ["index.ts"] 73 | } 74 | --------------------------------------------------------------------------------