GraphQLUpload.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // @ts-check
  2. "use strict";
  3. const { GraphQLScalarType, GraphQLError } = require("graphql");
  4. const Upload = require("./Upload.js");
  5. /** @typedef {import("./processRequest").FileUpload} FileUpload */
  6. /**
  7. * A GraphQL `Upload` scalar that can be used in a
  8. * [`GraphQLSchema`](https://graphql.org/graphql-js/type/#graphqlschema). It’s
  9. * value in resolvers is a promise that resolves
  10. * {@link FileUpload file upload details} for processing and storage.
  11. * @example
  12. * A schema built using
  13. * [`makeExecutableSchema`](https://www.graphql-tools.com/docs/api/modules/schema_src#makeexecutableschema)
  14. * from [`@graphql-tools/schema`](https://npm.im/@graphql-tools/schema):
  15. *
  16. * ```js
  17. * const { makeExecutableSchema } = require("@graphql-tools/schema");
  18. * const GraphQLUpload = require("graphql-upload/GraphQLUpload.js");
  19. *
  20. * const schema = makeExecutableSchema({
  21. * typeDefs: `
  22. * scalar Upload
  23. * `,
  24. * resolvers: {
  25. * Upload: GraphQLUpload,
  26. * },
  27. * });
  28. * ```
  29. * @example
  30. * A manually constructed schema with an image upload mutation:
  31. *
  32. * ```js
  33. * const { GraphQLSchema, GraphQLObjectType, GraphQLBoolean } = require("graphql");
  34. * const GraphQLUpload = require("graphql-upload/GraphQLUpload.js");
  35. *
  36. * const schema = new GraphQLSchema({
  37. * mutation: new GraphQLObjectType({
  38. * name: "Mutation",
  39. * fields: {
  40. * uploadImage: {
  41. * description: "Uploads an image.",
  42. * type: GraphQLBoolean,
  43. * args: {
  44. * image: {
  45. * description: "Image file.",
  46. * type: GraphQLUpload,
  47. * },
  48. * },
  49. * async resolve(parent, { image }) {
  50. * const { filename, mimetype, createReadStream } = await image;
  51. * const stream = createReadStream();
  52. * // Promisify the stream and store the file, then…
  53. * return true;
  54. * },
  55. * },
  56. * },
  57. * }),
  58. * });
  59. * ```
  60. */
  61. const GraphQLUpload = new GraphQLScalarType({
  62. name: "Upload",
  63. description: "The `Upload` scalar type represents a file upload.",
  64. parseValue(value) {
  65. if (value instanceof Upload) return value.promise;
  66. throw new GraphQLError("Upload value invalid.");
  67. },
  68. parseLiteral(node) {
  69. throw new GraphQLError("Upload literal unsupported.", { nodes: node });
  70. },
  71. serialize() {
  72. throw new GraphQLError("Upload serialization unsupported.");
  73. },
  74. });
  75. module.exports = GraphQLUpload;