forked from graphql-compose/graphql-compose-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (74 loc) · 2.39 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* eslint-disable no-new */
/* @flow */
import express from 'express';
import cors from 'cors';
import { ApolloServer } from 'apollo-server-express';
import { altairExpress } from 'altair-express-middleware';
import { express as voyagerMiddleware } from 'graphql-voyager/middleware';
import http from 'http';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { mainPage, addToMainPage } from './mainPage';
import { PORT, getExampleNames, resolveExamplePath } from './config';
import './mongooseConnection';
const app = express();
app.use(cors({ origin: true, credentials: true }));
const httpServer = http.createServer(app);
// scan `examples` directory and add
// - graphql endpoint by uri /exampleDirName
// - links and example queries to index page
const exampleNames = getExampleNames();
for (const name of exampleNames) {
addExample(
// $FlowFixMe
require(resolveExamplePath(name)).default,
name
);
}
// $FlowFixMe
app.get('/', (req, res) => {
res.send(mainPage());
});
httpServer.listen(PORT, () => {
console.log(`🚀🚀🚀 The server is running at http://localhost:${PORT}/`);
// https://www.apollographql.com/docs/graphql-subscriptions/setup/
SubscriptionServer.create(
{
schema: require('./examples/northwind/schema').default,
execute,
subscribe,
onConnect: (connectionParams, ws, context) => {
console.log(`WS[connect][${context.request.connection.remoteAddress}]`, connectionParams);
},
onDisconnect: (ws, context) => {
console.log(`WS[disconn][${context.request.connection.remoteAddress}]`);
},
},
{
server: httpServer,
path: '/northwind',
}
);
});
function addExample(example, uri) {
example.uri = `/${uri}`;
const server = new ApolloServer({
schema: example.schema,
introspection: true,
playground: {
subscriptionEndpoint: process.env.SUBSCRIPTION_ENDPOINT || `ws://localhost:${PORT}/northwind`,
},
plugins: example.plugins,
});
server.applyMiddleware({ app, path: example.uri });
app.use(
`${example.uri}-altair`,
altairExpress({
endpointURL: example.uri,
subscriptionsEndpoint:
process.env.SUBSCRIPTION_ENDPOINT || `ws://localhost:${PORT}/northwind`,
})
);
app.use(`${example.uri}-voyager`, voyagerMiddleware({ endpointUrl: example.uri }));
addToMainPage(example);
}