Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
graphql-upload-ts
Advanced tools
Readme
Minimalistic and developer friendly middleware and an Upload
scalar to add support for GraphQL multipart requests (file uploads via queries and
mutations) to various Node.js GraphQL servers.
This module was forked from the amazing graphql-upload-minimal
. The original module is exceptionally well documented and well written. It was very easy to fork and amend.
I needed to support typescript to use it properly in typescript projects.
You can't have same file referenced twice in a GraphQL query/mutation.
The following environments are known to be compatible:
See also GraphQL multipart request spec server implementations.
To install graphql-upload-ts
and the graphql
peer dependency from npm run:
npm install graphql-upload-ts graphql
# or
yarn add graphql-upload-ts graphql
Use the graphqlUploadKoa
or graphqlUploadExpress
middleware just before GraphQL middleware. Alternatively, use processRequest
to create a
custom middleware.
A schema built with separate SDL and resolvers (e.g. using makeExecutableSchema
) requires the Upload
scalar to be setup.
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.
Minimalistic code example showing how to upload a file along with arbitrary GraphQL data and save it to an S3 bucket.
Express.js middleware. You must put it before the main GraphQL sever middleware. Also, make sure there is no other Express.js middleware which parses multipart/form-data
HTTP requests before the graphqlUploadExpress
middleware!
const express = require('express');
const expressGraphql = require('express-graphql');
const { graphqlUploadExpress } = require('graphql-upload-ts');
express()
.use(
'/graphql',
graphqlUploadExpress({
maxFileSize: 10000000,
maxFiles: 10,
// If you are using framework around express like [ NestJS or Apollo Serve ]
// use this options overrideSendResponse to allow nestjs to handle response errors like throwing exceptions
overrideSendResponse: false
}),
expressGraphql({ schema: require('./my-schema') })
)
.listen(3000);
GraphQL schema:
scalar Upload
input DocumentUploadInput {
docType: String!
file: Upload!
}
type SuccessResult {
success: Boolean!
message: String
}
type Mutations {
uploadDocuments(docs: [DocumentUploadInput!]!): SuccessResult
}
GraphQL resolvers:
const { S3 } = require('aws-sdk');
const resolvers = {
Upload: require('graphql-upload-ts').GraphQLUpload,
Mutations: {
async uploadDocuments(root, { docs }, ctx) {
try {
const s3 = new S3({ apiVersion: '2006-03-01', params: { Bucket: 'my-bucket' } });
for (const doc of docs) {
const { createReadStream, filename /*, fieldName, mimetype, encoding */ } = await doc.file;
const Key = `${ctx.user.id}/${doc.docType}-${filename}`;
await s3.upload({ Key, Body: createReadStream() }).promise();
}
return { success: true };
} catch (error) {
console.log('File upload failed', error);
return { success: false, message: error.message };
}
},
},
};
See the example Koa server and client.
When uploading multiple files you can make use of the fieldName
property to keep track of an identifier of the uploaded files. The fieldName is equal to the passed name
property of the file in the multipart/form-data
request. This can
be modified to contain an identifier (like a UUID), for example using the formDataAppendFile
in the commonly used apollo-upload-link
library.
GraphQL schema:
scalar Upload
input DocumentUploadInput {
docType: String!
files: [Upload!]
}
type SuccessResult {
success: Boolean!
message: String
}
type Mutations {
uploadDocuments(docs: [DocumentUploadInput!]!): SuccessResult
}
GraphQL resolvers:
const { S3 } = require('aws-sdk');
const resolvers = {
Upload: require('graphql-upload-ts').GraphQLUpload,
Mutations: {
async uploadDocuments(root, { docs }, ctx) {
try {
const s3 = new S3({ apiVersion: '2006-03-01', params: { Bucket: 'my-bucket' } });
for (const doc of docs) {
// fieldName contains the "name" property from the multipart/form-data request.
// Use it to pass an identifier in order to store the file in a consistent manner.
const { createReadStream, filename, fieldName /*, mimetype, encoding */ } = await doc.file;
const Key = `${ctx.user.id}/${doc.docType}-${fieldName}`;
await s3.upload({ Key, Body: createReadStream() }).promise();
}
return { success: true };
} catch (error) {
console.log('File upload failed', error);
return { success: false, message: error.message };
}
},
},
};
overrideSendResponse
eg: graphqlUploadExpress({ overrideSendResponse: false })
to allow nestjs to handle response errors like throwing exceptions.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's resolvers need to be able to manage independent file streams.
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.
FAQs
Typescript minimalistic and developer friendly middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.
The npm package graphql-upload-ts receives a total of 19,091 weekly downloads. As such, graphql-upload-ts popularity was classified as popular.
We found that graphql-upload-ts demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.