mkdir myapp
cd myapp
npm init (一路回车)
npm install @apollo/server graphql
创建 schema.graphql 文件,内容如下:
type Book {
title: String!
author: Author!
}
type Author {
name: String!
books: [Book!]!
}
type Query {
books: [Book]
authors: [Author]
}
schema 文件主要包括:
创建 resolvers.js 文件,内容如下:
const book1 = {title: 'book1'};
const book2 = {title: 'book2'};
const book3 = {title: 'book3'};
const author1 = {name: 'author1', books: [book1]};
const author2 = {name: 'author2', books: [book2, book3]};
book1.author = author1;
book2.author = author2;
book3.author = author2;
const books = [book1, book2, book3];
const authors = [author1, author2];
const resolvers = {
Query: {
books: () => books,
authors: () => authors,
},
};
module.exports = resolvers;
处理器文件主要包括:
创建 server.js 文件,内容如下:
const { ApolloServer } = require('@apollo/server');
const { startStandaloneServer } = require('@apollo/server/standalone');
const fs = require("fs");
const typeDefs = fs.readFileSync('./schema.graphql').toString();
const resolvers = require('./resolvers');
const server = new ApolloServer({
typeDefs,
resolvers,
});
startStandaloneServer(server).then(function(data) {
console.log(`🚀 Server ready at ${data.url}`);
});
node server.js
服务启动后,访问 http://localhost:4000 进行测试。
查询操作
query GetBooksAndAuthors {
books {
title,
author {
name
}
}
authors {
name
books {
title
}
}
}
查询结果
{
"data": {
"books": [
{
"title": "book1",
"author": {
"name": "author1"
}
},
{
"title": "book2",
"author": {
"name": "author2"
}
},
{
"title": "book3",
"author": {
"name": "author2"
}
}
],
"authors": [
{
"name": "author1",
"books": [
{
"title": "book1"
}
]
},
{
"name": "author2",
"books": [
{
"title": "book2"
},
{
"title": "book3"
}
]
}
]
}
}