大家好,GraphQL 是一个可以让 Client 弹性要求资料的技术,本文章将介绍Apollo Server,他是一个以 GraphQL 规范设计的 Server,并且可以套用 Node.js 现今大家常用的 Express、Fastify 等 Server 的 Middleware。
本文章以 Appollo 官网的getting-started撰写。
请先 clone 程序范例,以下会以程序范例讲解。
先将 Server 运行起来会比较有感觉,
$ cd ./week36
$ docker-compose up --build
打开localhost:4000
,会看到 GraphQL 的测试页面,
输入以下,并点选中间的运行按钮,
{
books {
title
author
}
}
将会获得以下资料,
{
"data": {
"books": [
{
"title": "The Awakening",
"author": "Kate Chopin"
},
{
"title": "City of Glass",
"author": "Paul Auster"
}
]
}
}
如果不使用测试页面来测试,也可以使用一般的 Curl、Postman 来测试,要特别注意的是,request 端的 query 实际上是一个字串,并不是一个 object
创建 node 专案并且安装 Apollo 相关套件
$ npm init --yes
$ npm install apollo-server graphql
让我们来看看index.js发生了什麽事,
定义了 GraphQL 的 schema,
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
type Book
: 定义有一个Book
物件,拥有 title 与 author 的栏位,并且都是 Stringtype Query
: 定义有哪些查询
的方法,此范例拥有books
方法,并且会返回复数或零个Book
物件设定假资料,
const books = [
{
title: "The Awakening",
author: "Kate Chopin",
},
{
title: "City of Glass",
author: "Paul Auster",
},
];
实作查询中的books
方法,此处的方法非常简单,就是直接把假资料回传而已,而实战中,此处可以设计去 DB 或者其他 Microservice 捞取资料,
const resolvers = {
Query: {
books: () => books,
},
};
以 schema 的typeDefs
、实作的resolvers
来创建ApolloServer
,并启动,
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`? Server ready at ${url}`);
});
>>: 鼠年全马铁人挑战 WEEK 38:封包测试工具 - Charles (三)
前言 在ES6之前,要使用非同步并且正确输出资料必须透过callback,然而callback不好学...
笔者想要在网路上实在很难找到好用又齐全的PySide2教学大全,那乾脆自己做一份自己想要的大补帖出来...
今天我们要让之前的程序能跟 Chat Bot 连动。 需要 Worker 吗? 直接从程序中 POS...
实作待办事项的第三天,今天把切换日期的功能做好就完成啦!!今天会透过路由传递日期像是这样 https...
1. Two Sum 我们挑选 LeetCode 中的 1. Two Sum 作为我们实作练习的第...