UNPKG

7.65 kBJavaScriptView Raw
1"use strict";
2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3 return new (P || (P = Promise))(function (resolve, reject) {
4 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7 step((generator = generator.apply(thisArg, _arguments || [])).next());
8 });
9};
10Object.defineProperty(exports, "__esModule", { value: true });
11const Express = require("express");
12const http = require("http");
13const bodyParser = require("body-parser");
14const apollo_server_express_1 = require("apollo-server-express");
15const subscriptions_transport_ws_1 = require("subscriptions-transport-ws");
16const getSchema_1 = require("../api/getSchema");
17const death_1 = require("../hooks/death");
18const bootstrap_1 = require("../hooks/bootstrap");
19const middlewares_1 = require("../hooks/middlewares");
20const listening_1 = require("../hooks/listening");
21const gatewayRequest_1 = require("../hooks/gatewayRequest");
22const gatewayConnect_1 = require("../hooks/gatewayConnect");
23const config_1 = require("../config");
24const __1 = require("..");
25const context_1 = require("../api/context");
26// Create our express based server.
27exports.api = Object.assign(Express(), {});
28exports.httpServer = http.createServer(exports.api);
29middlewares_1.default.addAction('graphql', ({ api }) => __awaiter(this, void 0, void 0, function* () {
30 api.post('/', bodyParser.json(), (req, res, next) => __awaiter(this, void 0, void 0, function* () {
31 try {
32 yield gatewayRequest_1.default.do({ req });
33 const context = yield context_1.createContextFromExpressRequest(req);
34 apollo_server_express_1.graphqlExpress({
35 schema: context.schema,
36 context,
37 debug: false,
38 formatResponse(response, options) {
39 return __1.formatResponse(context, response);
40 },
41 formatError: (error) => {
42 return __1.formatError(context, error);
43 },
44 })(req, res, next);
45 }
46 catch (error) {
47 next(error);
48 }
49 }));
50}), { priority: 50 });
51middlewares_1.default.addAction('graphiql', ({ api }) => __awaiter(this, void 0, void 0, function* () {
52 if (process.env.NODE_ENV === 'development') {
53 require('reload')(api);
54 }
55 api.get('/', (req, res, next) => {
56 if (process.env.NODE_ENV === 'development') {
57 const reloadInjection = '<script src="/reload/reload.js"></script>';
58 const write = res.write.bind(res);
59 Object.assign(res, {
60 write(body) {
61 return write(body.replace(/(<\/body>)/, ` ${reloadInjection}\n$1`));
62 }
63 });
64 }
65 apollo_server_express_1.graphiqlExpress(Object.assign({ endpointURL: '/' }, (config_1.default.disableSubscription ? null : {
66 subscriptionsEndpoint: `ws://${config_1.default.host}`,
67 })))(req, res, next);
68 });
69}), { priority: 60 });
70bootstrap_1.default.addAction('middlewares', () => __awaiter(this, void 0, void 0, function* () {
71 yield middlewares_1.default.do({ api: exports.api });
72}));
73function destroy() {
74 return __awaiter(this, void 0, void 0, function* () {
75 yield death_1.default.do({ httpServer: exports.httpServer, api: exports.api });
76 yield new Promise((resolve, reject) => {
77 exports.httpServer.close((error) => {
78 if (error !== undefined) {
79 reject(error);
80 }
81 else {
82 resolve();
83 }
84 });
85 });
86 });
87}
88process.on('SIGINT', destroy);
89process.on('SIGTERM', destroy);
90process.on('exit', destroy);
91process.on('uncaughtException', (err) => {
92 console.log('UNCAUGHT EXCEPTION');
93 console.log(`${err.stack || err.message}`);
94 process.exit(2);
95});
96bootstrap_1.default.addAction('serverStartingLog', () => __awaiter(this, void 0, void 0, function* () {
97 if (process.env.SERVER_RESTART !== 'true') {
98 console.log('Launching server...');
99 }
100}), { before: 'server' });
101listening_1.default.addAction('log', () => __awaiter(this, void 0, void 0, function* () {
102 if (process.env.SERVER_RESTART === 'true') {
103 console.log(`\nServer is up to date!`);
104 }
105 else {
106 console.log(`
107
108 Server is ready!
109
110 Server is now listening on Port ${config_1.default.listenPort} and Address ${config_1.default.listenAddress}
111 You can access it in the browser at http://${config_1.default.host}
112 Press Ctrl-C to stop.
113
114
115
116 `);
117 }
118 if (process.env.NODE_ENV === 'development' && process.env.SERVER_RESTART === 'true') {
119 const { notify } = yield Promise.resolve().then(() => require('../internal/utils/notify'));
120 notify('✔️ Server is running with latest changes');
121 }
122}));
123bootstrap_1.default.addAction('subscription', () => {
124 const subscribeServer = new subscriptions_transport_ws_1.SubscriptionServer({
125 execute: __1.executeWithContext,
126 subscribe: __1.subscribeWithContext,
127 schema: getSchema_1.getSchema(),
128 onConnect(connectionParams, webSocket, context) {
129 return __awaiter(this, void 0, void 0, function* () {
130 const operationContext = {};
131 Object.assign(webSocket, { operationContext });
132 yield gatewayConnect_1.default.do({ connectionParams, webSocket, context });
133 return true;
134 });
135 },
136 onOperation(message, params, webSocket) {
137 return __awaiter(this, void 0, void 0, function* () {
138 let result;
139 const { id: opId } = message;
140 if (opId == null) {
141 throw new Error('No operation id set');
142 }
143 const context = yield context_1.createContextFromWebSocketTransport(webSocket, message, params);
144 webSocket.operationContext[opId] = context;
145 return Object.assign({}, params, { context });
146 });
147 },
148 onOperationComplete(webSocket, opId) {
149 return __awaiter(this, void 0, void 0, function* () {
150 const { operationContext } = webSocket;
151 if (typeof operationContext === 'undefined') {
152 return;
153 }
154 const context = operationContext[opId];
155 if (!context.completed) {
156 context.end(null, 'unsubscribed');
157 }
158 });
159 },
160 }, {
161 server: exports.httpServer,
162 path: '/',
163 });
164});
165bootstrap_1.default.addAction('server', () => __awaiter(this, void 0, void 0, function* () {
166 yield new Promise((resolve, reject) => {
167 // Create an http listener for our express app.
168 exports.httpServer.listen(config_1.default.listenPort, config_1.default.listenAddress, () => {
169 resolve();
170 // Execute listening hook
171 listening_1.default.do({ httpServer: exports.httpServer, api: exports.api })
172 .catch(err => {
173 console.log(err.stack !== undefined ? err.stack : err.message);
174 });
175 });
176 exports.httpServer.on('error', reject);
177 });
178}));
179exports.default = exports.api;
180//# sourceMappingURL=index.js.map
\No newline at end of file