定义
使用
第一步:初始化一个项目,不用做太多配置,我们只是为了测试graphql,所以创建项目的话一路回车就行
npm init
第二步:下载graphql相关,因为我们想要在node中潜入graphql,使用框架是express,所以需要express和express-graphql
yarn add graphql express express-graphql
第三步:下载babel相关,因为我写graphql可能需要用到一些es6写法(暂时不用)
yarn add @babel/cli @babel/core @babel/node
第四步配置package.json
"scripts": {// nodemon如果没有,需要下载"dev": "nodemon index.js --exec babel-node --presets @babel/preset-env","test": "echo \"Error: no test specified\" && exit 1"}
第五步,创建一个index.js,用express启动一个服务:http://localhost:5000
import express from 'express';const app = express();app.use((req, res) => {res.send('welcome');})app.listen(5000);
下面,我们就可以进行graphql配置了
// index.jsimport {graphqlHTTP} from 'express-graphql';import GraphqlSchema from './GraphqlSchema';const app = express();// 启动一个graphql服务,可以进行可视化查询操作app.use('/graphql',graphqlHTTP({schema: GraphqlSchema,graphiql: true,}),);app.listen(5000);
新建一个GraphqlSchema.js文件,进行graphql的schema配置
import {graphql,GraphQLSchema,GraphQLObjectType,GraphQLString,GraphQLList,GraphQLInt} from 'graphql';var schema = new GraphQLSchema({query: new GraphQLObjectType({name: 'RootQueryType',fields: {hello: {type: GraphQLString,resolve() {return 'world';},}}})});export default schema;
启动命令:
npm run dev
在浏览器中输入:http://localhost:5000/graphql即可启动graphql服务器,同时输入查询语句,则可以进行可视化查询,如图
我们还可以配置一些更复杂的数据
// GraphqlSchema.jslet HelloType = new GraphQLObjectType({name: 'HelloType',fields: {name: {type: GraphQLString},age: {type: GraphQLInt},phone: {type: GraphQLString}}})var schema = new GraphQLSchema({query: new GraphQLObjectType({name: 'RootQueryType',fields: {hello: {type: new GraphQLList(HelloType),resolve() {return [{name: 'tom',age: 18,phone: '323243434'},{name: 'jerry',age: 10,phone: '1123333'},{name: 'hahah',age: 48,phone: '222233444'}];}}}})});
