系统需要安装nodejs环境,版本最好是12.22.0或者14.16.0或者大于等于16.0.0,我用的是14.16.0版本的(这里用nvm管理node版本会比较方便)
- 首先初始化项目
npm init -y
,会生成package.json文件
(这个.gitignore是我自己在项目初始化之前就配置的git配置文件,一般自己练习的项目有没有都无所谓)
- 安装express和graphql以及express-graphql
npm install express graphql express-graphql -S
- 为了方便热更新代码,可以安装nodemon
npm i nodemon -g
,这个必须全局安装
- 新建启动文件
index.js
,并且写一个基础的demo,启动nodemon index.js
启动项目,看到打印出来了http://localhost:3000/graphql
就成功了
附上代码
// 引入 express 核心库
const express = require('express');
// 引入 结合 express 和 graphql 的中间件
const { graphqlHTTP } = require('express-graphql');
// 引入 graphql 核心库
const { buildSchema } = require('graphql');
// buildSchema 定义查询语句和类型, Query:语句,hello:查询方法名称,String:返回值类型
const schema = buildSchema(`
type Query {
hello: String,
}
`);
// root 查询处理器,hello:查询方法 及 返回值
const root = {
hello: () => {
return 'hello graphql test';
},
};
const app = express();
// /graphql:接口,graphqlHTTP:graphql处理中间件
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
// 是否启用调试界面,false不能调试
graphiql: true,
}));
// 监听3000端口
app.listen(3000, () => { console.log('http://localhost:3000/graphql')} );
- 浏览器打开
http://localhost:3000/graphql
- 点击右上角Docs,可以查看root types,删掉左边所有,输入
query {
hello
}
点击运行,可以得到结果hello graphql test
- 基础的项目搭建就完成了,接下来再继续学习graphql的其他语法和用法吧
PS:我测试了下其他类型和自定义类型的数据,需要什么数据取什么数据,不会所有数据都返回,附上代码,看图说话:
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const schema = buildSchema(`
type User {
username: String
age: Int
sex: String
address: String
}
type Query {
hello: String
height: Int
accountInfo: User
}
`);
const root = {
hello: () => {
return 'hello graphql test';
},
height: () => {
return 288
},
accountInfo: () => {
return {
username: 'hsieh chia',
age: 22,
sex: 'girl',
address: 'sichuan, chengdu'
}
}
};
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(3000, () => { console.log('http://localhost:3000/graphql')} );