1 创建项目
使用以下命令创建项目
cd graphql-with-nodejs
npm init -y
npm install express
npm install express-graphql graphql
在项目里新建server.js
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// 定义 GraphQL schema
const schema = buildSchema(`
type Account {
name : String
age: Int
sex : String
department : String
}
type Query {
hello: String
age: Int
account: Account
}
`);
// 定义 resolver
const root = {
hello: () => 'hello world',
age: () => 21,
account: () => ({
name: '张三',
age: 18,
sex: 'male',
department: '销售'
})
};
// 创建 Express 服务器
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true // 启用 GraphiQL 方便测试
}));
// 监听端口
app.listen(5000, () => {
console.log('🚀 Server running at http://localhost:5000/graphql');
});
启动项目
node .\server.js
访问 http://localhost:5000/graphql
在页面中输入查询参数
{
hello
age
account {
name
age
sex
department
}
}
2 参数类型和传递
新建文件 baseType.js
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// 定义 GraphQL schema
const schema = buildSchema(`
type Query {
getClassMates(classNo: Int!): [String]
}
`);
// 定义 resolver
const obj = {
"31": ["张三", "李四", "王五"], // 数字改为字符串
"61": ["张三2", "李四2", "王五2"]
};
const root = {
getClassMates: (args) => {
return obj[args.classNo.toString()] || []; // 确保 classNo 转成字符串匹配键名
}
};
// 创建 Express 服务器
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true // 启用 GraphiQL 方便测试
}));
// 监听端口
app.listen(5000, () => {
console.log('Server running at http://localhost:5000/graphql');
});
启动项目
node .\baseType.js
在页面中输入查询参数
{
getClassMates(classNo: 31)
}
参考页面
https://www.infoq.cn/article/i5jmm54_awrrzcem1vgh