UNPKG

@cran/gql.koa

Version:

Cran/GraphQL Koa Server

56 lines (55 loc) 2.13 kB
/* eslint-disable require-atomic-updates */ /* eslint-disable @typescript-eslint/naming-convention */ import accepts from "accepts"; import { ApolloServerBase, HttpQueryError, convertNodeHttpToRequest, runHttpQuery, } from "apollo-server-core"; export class ApolloServer extends ApolloServerBase { storedLandingPage; async createGraphQLServerOptions(ctx) { return super.graphQLServerOptions({ ctx, }); } getMiddleware() { return this.makeMiddleware.bind(this); } async makeMiddleware(ctx) { if (undefined === this.storedLandingPage) { this.storedLandingPage = this.getLandingPage(); } if (this.storedLandingPage && "GET" === ctx.request.method) { if (accepts(ctx.req).type(["html",])) { ctx.set("Content-Type", "text/html"); return Object.assign(ctx, { status: 200, body: this.storedLandingPage.html, }); } } return this.makeGraphqlRequest(ctx); } async makeGraphqlRequest(ctx) { try { const { graphqlResponse, responseInit, } = await runHttpQuery([ctx,], { method: ctx.request.method, request: convertNodeHttpToRequest(ctx.req), query: "POST" === ctx.request.method ? ctx.request.body : ctx.request.query, options: async () => { return this.createGraphQLServerOptions(ctx); }, }); return assignContext(ctx, responseInit.status || 200, graphqlResponse, responseInit.headers); } catch (error) { if (!(error instanceof HttpQueryError)) { throw error; } return assignContext(ctx, error.statusCode, error.message, error.headers); } } } function assignContext(ctx, status, body, headers) { if (headers) { for (const [headerName, headerValue,] of Object.entries(headers)) { ctx.set(headerName, headerValue); } } return Object.assign(ctx, { body, status, }); }