# GraphQL

# 1.什么是 GraphQL

  • GraphQL既是一种用于 api 的查询语言也是一个满足你数据查询的运行时
  • GraphQL对你的 api 中的数据提供了一套用于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余
  • 请求你所要的数据不多不少
  • 只用一个请求获取多个资源

# 2.创建后端项目

mkdir server
cd server
cnpm init -y
cnpm i express graphql express-graphql mongoose cors --save
1
2
3
4

# 3.实现商品分类接口

# 3.1 server.js

server.js

const express = require("express")
const graphqlHTTP = require("express-graphql")
const schema = require("./schema")
const cors = require("cors")
const app = express()
app.use(
  cors({
    origin: "http://localhost:3000",
    methods: "GET,PUT.POST,OPTIONS",
  })
)
app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    graphiql: true,
  })
)
app.listen(4000, () => {
  consle.log("server started on 4000")
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 3.2 schema.js

定义用户自定义类型,类型的每个字段都必须是已定义的且最终都是 GraphQL 中定义的类型。 定义根类型,每种根类型中包含了准备暴露给服务调用方的用户自定义类型 定义 Schema,每一个 Schema 中允许出现三种根类型:query,mutation,subscription,其中至少要有 query schema.js

const graphql = require('graphql');
const { GraphQLObjectType,
    GraphQLString,
    GraphQLInt,
    GraphQLSchema,
    GraphQLList,
    GraphQLNonNull
} = graphql;
const categories = [
    { id: '1', name: '图书' },
    { id: '2', name: '数码' },
    { id: '3', name: '食品' }
]

const Category = new GraphQLObjectType({
    name: 'Category',
    fields: () => (
        {
            id: { type: GraphQLString },
            name: { type: GraphQLString },
        }
    )
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQuery',
    fields: {
        getCategory: {
            type: Category,
            args: {
                id: {
                    type: GraphQLString
                }
            },
            resolve(parent, args) {
                return categories.find(item => item.id === args.id);
            }
        }
    }
});
module.exports = new GraphQLSchema({
    query: RootQuery
})
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

# 3.3 GraphiQL

GraphiQLis an in-browser tool for writing, validating, and testing GraphQL queries. 浏览器访问

每次调用 GraphQL 服务,需要明确指定调用 Schema 中的哪个根类型(默认是 query)

然后指定这个根类型下的哪几个字段(每个字段对应一个用户自定义类型),然后指定这些字段中的那些子字段的哪几个。一直到所有的字段都没有子字段为止 Schema 明确了服务端有哪些字段(用户自定义类型)可以用,每个字段的类型和子字段 每次查询时,服务器就会根据 Schema 验证并执行查询

     {
       field(arg: "value") {
         subField
       }
     }
1
2
3
4
5
query{
  getCategory(id: "1") {
    id
    name
  }
}
1
2
3
4
5
6

getCategory

getCategories

# 4. 实现商品接口

# 4.1 schema.js

schema.js

const graphql = require('graphql');
const { GraphQLObjectType,
    GraphQLString,
    GraphQLSchema,
    GraphQLList,
} = graphql;
const categories = [
    { id: '1', name: '图书' },
    { id: '2', name: '数码' },
    { id: '3', name: '食品' }
]
+const products = [
+    { id: '1', name: '红楼梦', category: '1' },
+    { id: '2', name: '西游记', category: '1' },
+    { id: '3', name: '水浒传', category: '1' },
+    { id: '4', name: '三国演义', category: '1' },
+    { id: '2', name: 'iPhone', category: '2' },
+    { id: '3', name: '', category: '3' }
+]
//定义用户自定义类型
//类型的每个字段都必须是已定义的且最终都是 GraphQL 中定义的类型。
const Category = new GraphQLObjectType({
    name: 'Category',
    fields: () => (
        {
            id: { type: GraphQLString },
            name: { type: GraphQLString },
+            products: {
+                type: new GraphQLList(Product),
+                resolve(parent) {
+                    return products.filter(item => item.category === parent.id);
+                }
+            }
        }
    )
});
+const Product = new GraphQLObjectType({
+    name: 'Product',
+    fields: () => (
+        {
+            id: { type: GraphQLString },
+            name: { type: GraphQLString },
+            category: {
+                type: Category,
+                resolve(parent) {
+                    return categories.find(item => item.id === parent.category);
+                }
+            }
+        }
+    )
+});

const RootQuery = new GraphQLObjectType({
    name: 'RootQuery',
    fields: {
        getCategory: {
            type: Category,
            args: {
                id: {
                    type: GraphQLString
                }
            },
            resolve(parent, args) {
                return categories.find(item => item.id === args.id);
            }
        },
        getCategories: {
            type: new GraphQLList(Category),
            args: {

            },
            resolve(parent, args) {
                return categories;
            }
        },
+        getProduct: {
+            type: Product,
+            args: {
+                id: {
+                    type: GraphQLString
+                }
+            },
+            resolve(parent, args) {
+                return products.find(item => item.id === args.id);
+            }
+        },
+        getProducts: {
+            type: new GraphQLList(Product),
+            args: {},
+            resolve(parent, args) {
+                return categories;
+            }
+        }
    }
});
//定义 Schema,每一个 Schema 中允许出现三种根类型:query,mutation,subscription,其中至少要有 query
module.exports = new GraphQLSchema({
    query: RootQuery
})
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
91
92
93
94
95
96
97
98
99

# 5. 添加商品

# 5.1 schema.js

schema.js

const graphql = require('graphql');
const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLSchema,
    GraphQLList,
    GraphQLNonNull
} = graphql;
const categories = [
    { id: '1', name: '图书' },
    { id: '2', name: '数码' },
    { id: '3', name: '食品' }
]
+const products = [
+    { id: '1', name: '红楼梦', category: '1' },
+    { id: '2', name: '西游记', category: '1' },
+    { id: '3', name: '水浒传', category: '1' },
+    { id: '4', name: '三国演义', category: '1' },
+    { id: '2', name: 'iPhone', category: '2' },
+    { id: '3', name: '', category: '3' }
+]
//定义用户自定义类型
//类型的每个字段都必须是已定义的且最终都是 GraphQL 中定义的类型。
const Category = new GraphQLObjectType({
    name: 'Category',
    fields: () => (+
        {
            id: { type: GraphQLString },
            name: { type: GraphQLString },
            products: {
                type: new GraphQLList(Product),
                resolve(parent) {
                    return products.filter(item => item.category === parent.id);
                }
            }
        }
    )
});
+const Product = new GraphQLObjectType({
+    name: 'Product',
+    fields: () => (
+        {
+            id: { type: GraphQLString },
+            name: { type: GraphQLString },
+            category: {
+                type: Category,
+                resolve(parent) {
+                    return categories.find(item => item.id === parent.category);
+                }
+            }
+        }
+    )
+});

const RootQuery = new GraphQLObjectType({
    name: 'RootQuery',
    fields: {
        getCategory: {
            type: Category,
            args: {
                id: {
                    type: GraphQLString
                }
            },
            resolve(parent, args) {
                return categories.find(item => item.id === args.id);
            }
        },
        getCategories: {
            type: new GraphQLList(Category),
            args: {

            },
            resolve(parent, args) {
                return categories;
            }
        },
        getProduct: {
            type: Product,
            args: {
                id: {
                    type: GraphQLString
                }
            },
            resolve(parent, args) {
                return products.find(item => item.id === args.id);
            }
        },
        getProducts: {
            type: new GraphQLList(Product),
            args: {

            },
            resolve(parent, args) {
                return categories;
            }
        }
    }
});
+const RootMutation = new GraphQLObjectType({
+    name: 'RootMutation',
+    fields: {
+        addCategory: {
+            type: Category,
+            args: {
+                name: { type: new GraphQLNonNull(GraphQLString) }
+            },
+            resolve(parent, args) {
+                args.id = categories.length + 1 + '';
+                categories.push(args);
+                return args;
+            }
+        },
+        addProduct: {
+            type: Product,
+            args: {
+                name: { type: new GraphQLNonNull(GraphQLString) },
+                category: { type: new GraphQLNonNull(GraphQLString) }
+            },
+            resolve(parent, args) {
+                args.id = products.length + 1 + '';
+                products.push(args);
+                return args;
+            }
+        }
    }
});
//定义 Schema,每一个 Schema 中允许出现三种根类型:query,mutation,subscription,其中至少要有 query
module.exports = new GraphQLSchema({
    query: RootQuery,
+    mutation: RootMutation
})
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

addProduct

# 6. 使用mongodb数据库

# 6.1 model.js

const mongoose = require('mongoose');
const ObjectId = mongoose.Schema.Types.ObjectId;
const Schema = mongoose.Schema;
const conn = mongoose.createConnection(`mongodb://localhost/graphql`, {
    useNewUrlParser: true, useUnifiedTopology: true
});
conn.on('open', () => console.log('数据库连接成功'));
conn.on('error', (error) => console.log('数据库连接失败', error));

const CategorySchema = new Schema({
    name: String
});
const CategoryModel = conn.model('Category', CategorySchema);
const ProductSchema = new Schema({
    name: String,
    category: {
        type: ObjectId,
        ref: 'Category'
    }
});
const ProductModel = conn.model('Product', ProductSchema);
module.exports = {
    CategoryModel,
    ProductModel
}
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

# 6.2 schema.js

schema.js

const graphql = require('graphql');
+const { CategoryModel, ProductModel } = require('./model');
const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLSchema,
    GraphQLList,
    GraphQLNonNull
} = graphql;
const categories = [
    { id: '1', name: '图书' },
    { id: '2', name: '数码' },
    { id: '3', name: '食品' }
]
const products = [
    { id: '1', name: '红楼梦', category: '1' },
    { id: '2', name: '西游记', category: '1' },
    { id: '3', name: '水浒传', category: '1' },
    { id: '4', name: '三国演义', category: '1' },
    { id: '2', name: 'iPhone', category: '2' },
    { id: '3', name: '', category: '3' }
]
//定义用户自定义类型
//类型的每个字段都必须是已定义的且最终都是 GraphQL 中定义的类型。
const Category = new GraphQLObjectType({
    name: 'Category',
    fields: () => (
        {
            id: { type: GraphQLString },
            name: { type: GraphQLString },
            products: {
                type: new GraphQLList(Product),
                resolve(parent) {
                    //return products.filter(item => item.category === parent.id);
+                    return ProductModel.find({ category: parent.id });
                }
            }
        }
    )
});
const Product = new GraphQLObjectType({
    name: 'Product',
    fields: () => (
        {
            id: { type: GraphQLString },
            name: { type: GraphQLString },
            category: {
                type: Category,
                resolve(parent) {
                    //return categories.find(item => item.id === parent.category);
+                    return CategoryModel.findById(parent.category);
                }
            }
        }
    )
});

const RootQuery = new GraphQLObjectType({
    name: 'RootQuery',
    fields: {
        getCategory: {
            type: Category,
            args: {
                id: {
                    type: GraphQLString
                }
            },
            resolve(parent, args) {
                //return categories.find(item => item.id === args.id);
+                return CategoryModel.findById(args.id);
            }
        },
        getCategories: {
            type: new GraphQLList(Category),
            args: {},
            resolve(parent, args) {
                //return categories;
+                return CategoryModel.find();
            }
        },
        getProduct: {
            type: Product,
            args: {
                id: { type: GraphQLString }
            },
            resolve(parent, args) {
                //return products.find(item => item.id === args.id);
+                return ProductModel.findById(args.id);
            }
        },
        getProducts: {
            type: new GraphQLList(Product),
            args: {

            },
            resolve(parent, args) {
                //return categories;
+                return ProductModel.find();
            }
        }
    }
});
const RootMutation = new GraphQLObjectType({
    name: 'RootMutation',
    fields: {
        addCategory: {
            type: Category,
            args: {
                name: { type: new GraphQLNonNull(GraphQLString) }
            },
            resolve(parent, args) {
                /*
                  args.id = categories.length + 1 + '';
                  categories.push(args);
                  return args;
                */
+                return CategoryModel.create(args);
            }
        },
        addProduct: {
            type: Product,
            args: {
                name: { type: new GraphQLNonNull(GraphQLString) },
                category: { type: new GraphQLNonNull(GraphQLString) }
            },
            resolve(parent, args) {
                /* args.id = products.length + 1 + '';
                products.push(args);
                return args; */
+                return ProductModel.create(args);
            }
        }
    }
});
//定义 Schema,每一个 Schema 中允许出现三种根类型:query,mutation,subscription,其中至少要有 query
module.exports = new GraphQLSchema({
    query: RootQuery,
    mutation: RootMutation
})
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

# 6.3 操作步骤

mutation{
  addCategory(name:"书籍"){
    id,
    name
  }
}
{
  "data": {
    "addCategory": {
      "id": "5dcfb188fe2d74a3543392ab",
      "name": "书籍"
    }
  }
}
mutation{
  addCategory(name:"数码产品"){
    id,
    name
  }
}
{
  "data": {
    "addCategory": {
      "id": "5dcfb1bdfe2d74a3543392ad",
      "name": "数码产品"
    }
  }
}
mutation{
  addCategory(name:"食品"){
    id,
    name
  }
}
{
  "data": {
    "addCategory": {
      "id": "5dcfb1c5fe2d74a3543392ae",
      "name": "食品"
    }
  }
}


{
  getCategories {
    id
    name
  }
}

{
  "data": {
    "getCategories": [
      {
        "id": "5dcfb188fe2d74a3543392ab",
        "name": "书籍"
      },
      {
        "id": "5dcfb1bdfe2d74a3543392ad",
        "name": "数码产品"
      },
      {
        "id": "5dcfb1c5fe2d74a3543392ae",
        "name": "食品"
      }
    ]
  }
}


mutation {
  addProduct(name: "西游记", category: "5dcfb188fe2d74a3543392ab") {
    id
    name
  }
}

{
  "data": {
    "addProduct": {
      "id": "5dcfb341b2f03ea4906dd913",
      "name": "西游记"
    }
  }
}

mutation {
  addProduct(name: "红楼梦", category: "5dcfb188fe2d74a3543392ab") {
    id
    name
  }
}

{
  "data": {
    "addProduct": {
      "id": "5dcfb354b2f03ea4906dd914",
      "name": "红楼梦"
    }
  }
}

mutation {
  addProduct(name: "水浒传", category: "5dcfb188fe2d74a3543392ab") {
    id
    name
  }
}

{
  "data": {
    "addProduct": {
      "id": "5dcfb36cb2f03ea4906dd915",
      "name": "水浒传"
    }
  }
}

mutation {
  addProduct(name: "三国演义", category: "5dcfb188fe2d74a3543392ab") {
    id
    name
  }
}


{
  "data": {
    "addProduct": {
      "id": "5dcfb37bb2f03ea4906dd916",
      "name": "三国演义"
    }
  }
}

mutation {
  addProduct(name: "iPhone", category: "5dcfb1bdfe2d74a3543392ad") {
    id
    name
  }
}

{
  "data": {
    "addProduct": {
      "id": "5dcfb393b2f03ea4906dd917",
      "name": "iPhone"
    }
  }
}


mutation {
  addProduct(name: "面包", category: "5dcfb1c5fe2d74a3543392ae") {
    id
    name
  }
}

{
  "data": {
    "addProduct": {
      "id": "5dcfb3a7b2f03ea4906dd918",
      "name": "面包"
    }
  }
}


{
  getProducts {
    id
    name
  }
}

{
  "data": {
    "getProducts": [
      {
        "id": "5dcfb341b2f03ea4906dd913",
        "name": "西游记"
      },
      {
        "id": "5dcfb354b2f03ea4906dd914",
        "name": "红楼梦"
      },
      {
        "id": "5dcfb36cb2f03ea4906dd915",
        "name": "水浒传"
      },
      {
        "id": "5dcfb37bb2f03ea4906dd916",
        "name": "三国演义"
      },
      {
        "id": "5dcfb393b2f03ea4906dd917",
        "name": "iPhone"
      },
      {
        "id": "5dcfb3a7b2f03ea4906dd918",
        "name": "面包"
      }
    ]
  }
}
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207