This repository has been archived by the owner on Jun 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
server.js
75 lines (63 loc) · 2.48 KB
/
server.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
'use strict';
const path = require('path');
const cfGraphql = require('cf-graphql');
const express = require('express');
const cors = require('cors');
const graphqlHTTP = require('express-graphql');
const port = process.env.PORT || 4000;
const spaceId = process.env.SPACE_ID;
const cdaToken = process.env.CDA_TOKEN;
const cmaToken = process.env.CMA_TOKEN;
if (spaceId && cdaToken && cmaToken) {
console.log('Space ID, CDA token and CMA token provided');
console.log(`Fetching space (${spaceId}) content types to create a space graph`);
useProvidedSpace();
} else {
console.log('Using a demo space');
console.log('You can provide env vars (see README.md) to use your own space');
useDemoSpace();
}
// this function implements a flow you could use in your application:
// 1. fetch content types
// 2. prepare a space graph
// 3. create a schema out of the space graph
// 4. run a server
function useProvidedSpace () {
const client = cfGraphql.createClient({spaceId, cdaToken, cmaToken});
client.getContentTypes()
.then(cfGraphql.prepareSpaceGraph)
.then(spaceGraph => {
const names = spaceGraph.map(ct => ct.names.type).join(', ');
console.log(`Contentful content types prepared: ${names}`);
return spaceGraph;
})
.then(cfGraphql.createSchema)
.then(schema => startServer(client, schema))
.catch(fail);
}
// this function is being run if you don't provide credentials to your own space
function useDemoSpace () {
const {spaceId, cdaToken, spaceGraph} = require('./demo-data.json');
const client = cfGraphql.createClient({spaceId, cdaToken});
const schema = cfGraphql.createSchema(spaceGraph);
startServer(client, schema);
}
function startServer (client, schema) {
const app = express();
app.use(cors());
app.use('/client', express.static(path.join(__dirname, 'dist')));
const ui = cfGraphql.helpers.graphiql({title: 'cf-graphql demo'});
app.get('/', (_, res) => res.set(ui.headers).status(ui.statusCode).end(ui.body));
const opts = {version: true, timeline: true, detailedErrors: false};
const ext = cfGraphql.helpers.expressGraphqlExtension(client, schema, opts);
app.use('/graphql', graphqlHTTP(ext));
app.listen(port);
console.log('Running a GraphQL server!');
console.log(`You can access GraphiQL at localhost:${port}`);
console.log(`You can use the GraphQL endpoint at localhost:${port}/graphql/`);
console.log(`You can have a look at a React Frontend at localhost:${port}/client/`);
}
function fail (err) {
console.log(err);
process.exit(1);
}