forked from email2vimalraj/graphql-heroku
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
88 lines (73 loc) · 1.79 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
84
85
86
87
88
import express from 'express';
import bodyParser from 'body-parser';
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import { connectToDB } from './database';
// Start the http server
const startServer = async () => {
const { Block } = require('./database/models');
// GraphQL Types
const typeDefs = `
type Block {
_id: ID!
height: Int
}
type Mutation {
addBlock(height: BlockInput): Block
}
input BlockInput {
height: Int!
}
type Query {
blocks: [Block]
}
`;
// GraphQL resolvers
const resolvers = {
Query: {
blocks: async () => {
const res = await Block.find();
return res;
}
},
Mutation: {
addBlock: async(root, args) => {
const res = await Block.create(args.input);
return res;
},
},
};
// Define a schema
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
// Initiate express and define routes
const app = express();
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
app.use('/', graphiqlExpress({ endpointURL: '/graphql' }));
// Initiate the server
app.listen(process.env.PORT || 3000, () => {
console.log(`Server started on port: ${process.env.PORT || 3000}`);
});
};
// Connecting to DB and then start the server
const dbConnectAndStartServer = async () => {
try {
await connectToDB();
console.log('Connected to Mongo successfully');
startServer();
} catch (err) {
console.error(`Error connecting to mongo - ${err.message}`);
process.exit(1);
}
};
// Entry point
dbConnectAndStartServer();
// mutation addBlock {
// addBlock(input: {
// height: 1,
// }) {
// height
// }
// }