-
Notifications
You must be signed in to change notification settings - Fork 6
/
example-option.js
90 lines (84 loc) · 2.04 KB
/
example-option.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
89
90
/**
* 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,
resolve(root, args, context) {
console.log(root, context); // console: { id: 1, name: '2' } { test: true }
return root.name;
}
},
}
});
const Query = new GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: User,
args: {
id: {
type: GraphQLInt
}
},
resolve: function (root, args, context) {
console.log(root,context); // { test: false } { test: true }
return {id: 1, name: 'wenshao'};
}
}
}
});
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,
context: {
test: true
},
rootValue: {
test: false
},
formatError(error) {
return error;
},
validationRules(validationContext) {
return validationContext;
},
formatParams(params) {
return params;
},
formatResponse(data, all) {
// console.log(data);
delete data.extensions;// 当加上 tracing: true 返回到前端的会有extensions对象的值 对前端来说这数据没有用 所有可以删除
return data;
},
tracing: true
}));
router.get('/graphql', graphqlKoa({
schema: myGraphQLSchema
}));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(PORT);