import { mergeResolvers, mergeTypeDefs } from '@graphql-tools/merge'; import { makeExecutableSchema } from '@graphql-tools/schema'; import { GraphQLSchema } from 'graphql'; import { GraphQLUpload, graphqlUploadExpress } from 'graphql-upload-minimal'; import { IResolvers } from '@graphql-tools/utils'; import express from 'express'; import { getGraphQLParameters, processRequest, renderGraphiQL, shouldRenderGraphiQL, sendResult } from "graphql-helix"; const books = [ { id: 1, title: 'The Awakening', author: 'Kate Chopin', cover: '', }, { id: 2, title: 'City of Glass', author: 'Paul Auster', cover: '', }, { id: 3, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', cover: '', } ]; export const movieTypes = /* GraphQL */ ` type Book { id: Int title: String author: Int cover: String } type Books { books: [Book] count: Int } type Query { getBook(id: Int): Book getBooks: Books } type Mutation { uploadCover(id: Int!, file: Upload! ): Book } scalar Upload `; export function getMovieResolvers(): IResolvers { const resolvers = { Upload: GraphQLUpload, Query: { getBook: async (_: any, args: { id: number }) => { return books[args.id]; }, getBooks: (_: any) => { return { books, count: books.length, }; }, }, Mutation: { uploadCover: async (_: any, args: any) => { const book = books.find(book => book.id = args.id); if (book) { const file = await args.file; const content: string = await new Promise((resolve, reject) => { const stream = file.createReadStream(); let content = ''; stream.on('data', (chunk: any) => { content += chunk.toString(); }); stream.on('end', () => { resolve(content); }); stream.on('error', (error: any) => { reject(error); }); }); book.cover = content; } return book; }, }, }; return resolvers; } export function getSchema(): GraphQLSchema { const movieResolvers = getMovieResolvers(); const resolvers = mergeResolvers([movieResolvers]) const typeDefs = mergeTypeDefs([movieTypes]); return makeExecutableSchema({ resolvers, typeDefs, }); } export const remoteApplication2 = async () => { const schema = getSchema(); const app = express(); app.use(express.json()); app.use("/graphql", graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }), async (req, res) => { const request = { body: req.body, headers: req.headers, method: req.method, query: req.query, }; if (shouldRenderGraphiQL(request)) { res.send(renderGraphiQL()); } else { const { operationName, query, variables } = getGraphQLParameters(request); const result = await processRequest({ operationName, query, variables, request, schema, }); sendResult(result, res); } }); const server = app.listen(8009); return { server, }; }; if (process.env.RUN === 'true') { remoteApplication2(); }