UNPKG

graphql-upload-ts

Version:

TypeScript-first middleware and Upload scalar for GraphQL multipart requests (file uploads) with support for Apollo Server, Express, Koa, and more.

87 lines (82 loc) 2.46 kB
'use strict'; var graphql = require('graphql'); class Upload { constructor() { this.promise = new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; }); // Prevent unhandled promise rejection errors this.promise.catch(() => { }); } resolve(file) { this.file = file; this._resolve(file); } reject(error) { this._reject(error); } } /** * A GraphQL `Upload` scalar that can be used in a GraphQL schema. * Its value in resolvers is a promise that resolves to file upload details * for processing and storage. * * @example Import usage * ```typescript * import { GraphQLUpload } from 'graphql-upload-ts'; * ``` * * @example Schema usage with GraphQL Tools * ```typescript * import { makeExecutableSchema } from '@graphql-tools/schema'; * import { GraphQLUpload } from 'graphql-upload-ts'; * * const schema = makeExecutableSchema({ * typeDefs: ` * scalar Upload * * type Mutation { * uploadFile(file: Upload!): Boolean * } * `, * resolvers: { * Upload: GraphQLUpload, * Mutation: { * uploadFile: async (_, { file }) => { * const { filename, mimetype, createReadStream } = await file; * const stream = createReadStream(); * // Process the file stream... * return true; * } * } * }, * }); * ``` */ const uploadScalarConfig = { name: 'Upload', description: 'The `Upload` scalar type represents a file upload.', parseValue(value) { if (value instanceof Upload) { return value.promise; } throw new graphql.GraphQLError('Upload value invalid. Expected Upload instance.', { extensions: { code: 'INVALID_UPLOAD_VALUE' }, }); }, parseLiteral(node) { throw new graphql.GraphQLError('Upload literal unsupported. Uploads can only be passed as variables.', { nodes: node, extensions: { code: 'UPLOAD_LITERAL_UNSUPPORTED' }, }); }, serialize() { throw new graphql.GraphQLError('Upload serialization unsupported. Uploads cannot be serialized.', { extensions: { code: 'UPLOAD_SERIALIZATION_UNSUPPORTED' }, }); }, }; const GraphQLUpload = new graphql.GraphQLScalarType(uploadScalarConfig); exports.GraphQLUpload = GraphQLUpload; //# sourceMappingURL=graphql-upload.js.map