UNPKG

@cran/gql.koa

Version:

Cran/GraphQL Koa Server

61 lines (60 loc) 2.4 kB
"use strict"; /* eslint-disable require-atomic-updates */ /* eslint-disable @typescript-eslint/naming-convention */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ApolloServer = void 0; const tslib_1 = require("tslib"); const accepts_1 = (0, tslib_1.__importDefault)(require("accepts")); const apollo_server_core_1 = require("apollo-server-core"); class ApolloServer extends apollo_server_core_1.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 ((0, accepts_1.default)(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 (0, apollo_server_core_1.runHttpQuery)([ctx,], { method: ctx.request.method, request: (0, apollo_server_core_1.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 apollo_server_core_1.HttpQueryError)) { throw error; } return assignContext(ctx, error.statusCode, error.message, error.headers); } } } exports.ApolloServer = ApolloServer; 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, }); }