apollo-server-micro-pluto
Version:
Production-ready Node.js GraphQL server for Micro(for xsky pluto project)
94 lines • 3.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApolloServer = void 0;
const apollo_server_core_1 = require("apollo-server-core");
const micro_1 = require("micro");
const accept_1 = require("@hapi/accept");
const microApollo_1 = require("./microApollo");
class ApolloServer extends apollo_server_core_1.ApolloServerBase {
async createGraphQLServerOptions(req, res) {
return super.graphQLServerOptions({ req, res });
}
createHandler({ path, disableHealthCheck, onHealthCheck, __testing__microSuppressErrorLog, } = {}) {
this.assertStarted('createHandler');
this.graphqlPath = path || '/graphql';
const landingPage = this.getLandingPage();
return async (req, res) => {
try {
if (await this.handleHealthCheck({
req,
res,
disableHealthCheck,
onHealthCheck,
})) {
return;
}
if (landingPage &&
this.handleGraphqlRequestsWithLandingPage({ req, res, landingPage })) {
return;
}
if (await this.handleGraphqlRequestsWithServer({ req, res })) {
return;
}
micro_1.send(res, 404, null);
}
catch (errorObj) {
if (!__testing__microSuppressErrorLog) {
throw errorObj;
}
const statusCode = errorObj.statusCode || errorObj.status;
micro_1.send(res, statusCode || 500, errorObj.stack);
}
};
}
async handleHealthCheck({ req, res, disableHealthCheck, onHealthCheck, }) {
let handled = false;
if (!disableHealthCheck &&
req.url === '/.well-known/apollo/server-health') {
res.setHeader('Content-Type', 'application/health+json');
if (onHealthCheck) {
try {
await onHealthCheck(req);
}
catch (error) {
micro_1.send(res, 503, { status: 'fail' });
handled = true;
}
}
if (!handled) {
micro_1.send(res, 200, { status: 'pass' });
handled = true;
}
}
return handled;
}
handleGraphqlRequestsWithLandingPage({ req, res, landingPage, }) {
let handled = false;
if (req.method === 'GET') {
const accept = accept_1.parseAll(req.headers);
const types = accept.mediaTypes;
const prefersHtml = types.find((x) => x === 'text/html' || x === 'application/json') === 'text/html';
if (prefersHtml) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
micro_1.send(res, 200, landingPage.html);
handled = true;
}
}
return handled;
}
async handleGraphqlRequestsWithServer({ req, res, }) {
let handled = false;
const url = req.url.split('?')[0];
if (url === this.graphqlPath) {
const graphqlHandler = microApollo_1.graphqlMicro(() => {
return this.createGraphQLServerOptions(req, res);
});
const responseData = await graphqlHandler(req, res);
micro_1.send(res, 200, responseData);
handled = true;
}
return handled;
}
}
exports.ApolloServer = ApolloServer;
//# sourceMappingURL=ApolloServer.js.map