-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.apollo.js
More file actions
80 lines (69 loc) · 2.4 KB
/
index.apollo.js
File metadata and controls
80 lines (69 loc) · 2.4 KB
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
// server-apollo.js
import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@as-integrations/express5';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
import * as simfinity from '@simtlix/simfinity-js';
// ---------- Mongo ----------
let mongooseConfig = [
'mongodb://localhost:27017/series-sample',
{ replicaSet: 'rs0' }
];
if (process.env.MONGO) {
mongooseConfig = [process.env.MONGO, {}];
}
await mongoose.connect(...mongooseConfig).then(() => console.log('Connected to the database')).catch(console.error);
// ---------- Simfinity schema ----------
import './types/index.js';
const schema = simfinity.createSchema();
const formatError = simfinity.buildErrorFormatter((err) => { console.error(err); });
// ------------------------
// Apollo plugins
// ------------------------
function timingPlugin() {
return {
async requestDidStart() {
const start = Date.now();
return {
async willSendResponse({ response }) {
const durationMs = Date.now() - start;
if (response.body.kind === 'single') {
response.body.singleResult.extensions = {
...(response.body.singleResult.extensions || {}),
runTime: durationMs,
timestamp: new Date().toISOString(),
};
}
}
};
}
};
};
// Using simfinity's Apollo count plugin
const countPlugin = simfinity.plugins.apolloCountPlugin;
// ---------- Apollo ----------
const server = new ApolloServer({
schema,
formatError,
plugins: [ApolloServerPluginLandingPageLocalDefault({ includeCookies: false }), timingPlugin(), countPlugin()],
});
await server.start();
// ---------- Express ----------
const app = express();
app.use(cors());
// GET /graphql -> serve Apollo landing page / Playground
app.get('/graphql', express.json(), expressMiddleware(server, { context: async () => ({}) }));
// POST /graphql -> JSON body required
app.post(
'/graphql',
express.json({ limit: '1mb', type: ['application/json', 'application/*+json'] }),
expressMiddleware(server, { context: async () => ({}) })
);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
console.log(`Playground: http://localhost:${PORT}/graphql`);
});