@cortexql/core
Version:
A RESTful API framework for your apps based on GraphQL type system.
180 lines (175 loc) • 7.65 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const Express = require("express");
const http = require("http");
const bodyParser = require("body-parser");
const apollo_server_express_1 = require("apollo-server-express");
const subscriptions_transport_ws_1 = require("subscriptions-transport-ws");
const getSchema_1 = require("../api/getSchema");
const death_1 = require("../hooks/death");
const bootstrap_1 = require("../hooks/bootstrap");
const middlewares_1 = require("../hooks/middlewares");
const listening_1 = require("../hooks/listening");
const gatewayRequest_1 = require("../hooks/gatewayRequest");
const gatewayConnect_1 = require("../hooks/gatewayConnect");
const config_1 = require("../config");
const __1 = require("..");
const context_1 = require("../api/context");
// Create our express based server.
exports.api = Object.assign(Express(), {});
exports.httpServer = http.createServer(exports.api);
middlewares_1.default.addAction('graphql', ({ api }) => __awaiter(this, void 0, void 0, function* () {
api.post('/', bodyParser.json(), (req, res, next) => __awaiter(this, void 0, void 0, function* () {
try {
yield gatewayRequest_1.default.do({ req });
const context = yield context_1.createContextFromExpressRequest(req);
apollo_server_express_1.graphqlExpress({
schema: context.schema,
context,
debug: false,
formatResponse(response, options) {
return __1.formatResponse(context, response);
},
formatError: (error) => {
return __1.formatError(context, error);
},
})(req, res, next);
}
catch (error) {
next(error);
}
}));
}), { priority: 50 });
middlewares_1.default.addAction('graphiql', ({ api }) => __awaiter(this, void 0, void 0, function* () {
if (process.env.NODE_ENV === 'development') {
require('reload')(api);
}
api.get('/', (req, res, next) => {
if (process.env.NODE_ENV === 'development') {
const reloadInjection = '<script src="/reload/reload.js"></script>';
const write = res.write.bind(res);
Object.assign(res, {
write(body) {
return write(body.replace(/(<\/body>)/, ` ${reloadInjection}\n$1`));
}
});
}
apollo_server_express_1.graphiqlExpress(Object.assign({ endpointURL: '/' }, (config_1.default.disableSubscription ? null : {
subscriptionsEndpoint: `ws://${config_1.default.host}`,
})))(req, res, next);
});
}), { priority: 60 });
bootstrap_1.default.addAction('middlewares', () => __awaiter(this, void 0, void 0, function* () {
yield middlewares_1.default.do({ api: exports.api });
}));
function destroy() {
return __awaiter(this, void 0, void 0, function* () {
yield death_1.default.do({ httpServer: exports.httpServer, api: exports.api });
yield new Promise((resolve, reject) => {
exports.httpServer.close((error) => {
if (error !== undefined) {
reject(error);
}
else {
resolve();
}
});
});
});
}
process.on('SIGINT', destroy);
process.on('SIGTERM', destroy);
process.on('exit', destroy);
process.on('uncaughtException', (err) => {
console.log('UNCAUGHT EXCEPTION');
console.log(`${err.stack || err.message}`);
process.exit(2);
});
bootstrap_1.default.addAction('serverStartingLog', () => __awaiter(this, void 0, void 0, function* () {
if (process.env.SERVER_RESTART !== 'true') {
console.log('Launching server...');
}
}), { before: 'server' });
listening_1.default.addAction('log', () => __awaiter(this, void 0, void 0, function* () {
if (process.env.SERVER_RESTART === 'true') {
console.log(`\nServer is up to date!`);
}
else {
console.log(`
Server is ready!
Server is now listening on Port ${config_1.default.listenPort} and Address ${config_1.default.listenAddress}
You can access it in the browser at http://${config_1.default.host}
Press Ctrl-C to stop.
`);
}
if (process.env.NODE_ENV === 'development' && process.env.SERVER_RESTART === 'true') {
const { notify } = yield Promise.resolve().then(() => require('../internal/utils/notify'));
notify('✔️ Server is running with latest changes');
}
}));
bootstrap_1.default.addAction('subscription', () => {
const subscribeServer = new subscriptions_transport_ws_1.SubscriptionServer({
execute: __1.executeWithContext,
subscribe: __1.subscribeWithContext,
schema: getSchema_1.getSchema(),
onConnect(connectionParams, webSocket, context) {
return __awaiter(this, void 0, void 0, function* () {
const operationContext = {};
Object.assign(webSocket, { operationContext });
yield gatewayConnect_1.default.do({ connectionParams, webSocket, context });
return true;
});
},
onOperation(message, params, webSocket) {
return __awaiter(this, void 0, void 0, function* () {
let result;
const { id: opId } = message;
if (opId == null) {
throw new Error('No operation id set');
}
const context = yield context_1.createContextFromWebSocketTransport(webSocket, message, params);
webSocket.operationContext[opId] = context;
return Object.assign({}, params, { context });
});
},
onOperationComplete(webSocket, opId) {
return __awaiter(this, void 0, void 0, function* () {
const { operationContext } = webSocket;
if (typeof operationContext === 'undefined') {
return;
}
const context = operationContext[opId];
if (!context.completed) {
context.end(null, 'unsubscribed');
}
});
},
}, {
server: exports.httpServer,
path: '/',
});
});
bootstrap_1.default.addAction('server', () => __awaiter(this, void 0, void 0, function* () {
yield new Promise((resolve, reject) => {
// Create an http listener for our express app.
exports.httpServer.listen(config_1.default.listenPort, config_1.default.listenAddress, () => {
resolve();
// Execute listening hook
listening_1.default.do({ httpServer: exports.httpServer, api: exports.api })
.catch(err => {
console.log(err.stack !== undefined ? err.stack : err.message);
});
});
exports.httpServer.on('error', reject);
});
}));
exports.default = exports.api;
//# sourceMappingURL=index.js.map