1. 安装
这里没使用apollo来搭建graphql,所以配置比较麻烦些。现在使用apollo来搭建graphql很主流,apollo帮助我们减少编写这些配置graphql的代码
- 不同框架安装不同的包,比如koa的话,安装koa-graphql,express安装express-graphql
2. 初识demo
import Koa from 'koa';import Router from 'koa-router';import graphqlHTTP from 'koa-graphql';import { buildSchema } from 'graphql';const app = new Koa();const router = new Router();// 定义类型 type Query表示查询, type Mutation表示修改const schema = buildSchema(`type Query {hello: String // 定义了一个查询的变量,和返回的类型}`);==========================================================// 当用户在localhost:5000/graphql页面里输入下面这样query {hello}// 返回值如下{"data": {"hello": "Hello World"}}==========================================================// rootValue类似控制器,比如这里上面schema里定义查询hello// 那么当用户在/graphql这个页面里查询hello字段时,服务器做的相应操作// 就在这里写const rootValue = {hello: () => `Hello World`,};router.all('/graphql',graphqlHTTP({schema,rootValue,graphiql: true,}));app.use(router.routes(), router.allowedMethods());const PORT = process.env.PORT || 5000;app.listen(PORT, () => console.log(`server started at ${PORT}`));
3. 自定义类型
// 定义类型 type Query表示查询, type Mutation表示修改const schema = buildSchema(`type User {id: ID! // ! ID一定存在name: Stringage: Int}type Query {user: User}`);// rootValue类似控制器,比如这里上面schema里定义查询hello// 那么当用户在/graphql这个页面里查询hello字段时,服务器做的相应操作// 就在这里写const rootValue = {user: () => ({id: nanoid(),name: 'Yoooo',age: 18,}),};
4. 简单拆分文件
把schema拆分到单独的文件里
在根目录新建schema.js
index.js 需要修改下
import Koa from 'koa';import Router from 'koa-router';import graphqlHTTP from 'koa-graphql';import schema from './schema';const app = new Koa();const router = new Router();router.all('/graphql',graphqlHTTP({schema,graphiql: true,}));app.use(router.routes(), router.allowedMethods());const PORT = process.env.PORT || 5000;app.listen(PORT, () => console.log(`server started at ${PORT}`));
schema.js
- makeExecutableSchema作用是把类型和控制器糅合在一起,形成一个schema ```javascript import { makeExecutableSchema } from ‘graphql-tools’; import { nanoid } from ‘nanoid’;
const typeDefs = ` type User { id: ID! name: String age: Int }
type Query { user: User } `;
const resolvers = { Query: { user: () => ({ id: nanoid(), name: ‘Yoooo’, age: 12, }), }, };
// makeExecutableSchema作用是把类型和控制器糅合在一起,形成一个schema export default makeExecutableSchema({ typeDefs, resolvers, });
---<a name="9BG6s"></a>## 5. 完全拆分> 把type, resolver也分开目录:<br />index.js<br />db.js<br />schema.js<br />typeDefs- userType.graphqlresolvers- userResolver.js**index.js**```javascriptimport Koa from 'koa';import Router from 'koa-router';import graphqlHTTP from 'koa-graphql';import schema from './schema';const app = new Koa();const router = new Router();router.all('/graphql',graphqlHTTP({schema,graphiql: true,}));app.use(router.routes(), router.allowedMethods());const PORT = process.env.PORT || 5000;app.listen(PORT, () => console.log(`server started at ${PORT}`));
db.js
const db = {users: [],};export default {getData: () => db,setData: (key, value) => {db[key] = value;return db;},};
schema.js
import {makeExecutableSchema,mergeTypeDefs,loadFilesSync,mergeResolvers,} from 'graphql-tools';import { nanoid } from 'nanoid';const typeDefs = mergeTypeDefs(loadFilesSync('./typeDefs'), { all: true });const resolvers = mergeResolvers(loadFilesSync('./resolvers'));// makeExecutableSchema作用是把类型和控制器糅合在一起,形成一个schemaexport default makeExecutableSchema({typeDefs,resolvers,});
typeDefs/userType.graphql
type User {id: ID!name: Stringage: Int}type Query {userList: [User]}type Mutation {createUser(name: String, age: Int): User}
resolvers/userResolver.js
import { nanoid } from 'nanoid';import UserModel from '../models/userModel';export default {Query: {userList: () => UserModel.getUserList(),},Mutation: {createUser: (parent, args) => {const user = new UserModel({name: args.name,age: args.age,}).create();return user;},},};
6. GraphQL VS Restful

- 相对于restful 很多个接口,GraphQL只有一个end point,就是/graphql
- express-graphql, apollo 这些包用来帮我们parse incoming graphql requery
- How are Schemas and Resolvers connected?
- The express-graphql package does that
