/
example-koa.js
59 lines (54 loc) · 1.23 KB
/
example-koa.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
/**
* Created by wenshao on 2018/2/10.
*/
'use strict';
const Koa = require('koa');
const Body = require('koa-bodyparser');
const router = require('koa-router')();
const {graphqlKoa} = require('apollo-server-koa');
const {
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLInt
} = require('graphql');
const User = new GraphQLObjectType({
name: 'User',
description: 'User对象',
fields: {
id: {
type: GraphQLInt
},
name: {
type: GraphQLString
},
}
});
const Query = new GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: User,
args: {
id: {
type: GraphQLInt
}
},
resolve: function (root, args) {
return {id: 1, name: '2'};
}
}
}
});
const myGraphQLSchema = new GraphQLSchema({
query: Query
});
const app = new Koa();
const PORT = 3000;
// Body is needed just for POST.
app.use(Body());
router.post('/graphql', graphqlKoa({schema: myGraphQLSchema}));
router.get('/graphql', graphqlKoa({schema: myGraphQLSchema}));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(PORT);