当前位置:网站首页>GraphQL (1) Basic introduction and application examples
GraphQL (1) Basic introduction and application examples
2022-07-30 06:54:00 【If I don't see you tomorrow】
GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义).GraphQL 并没有和任何特定数据库或者存储引擎绑定,而是依靠你现有的代码和数据支撑.
应用场景及优缺点
Quoted from translationGraphQL:它的优点、Disadvantages and alternatives,原文为Why GraphQL: Advantages and Disadvantages
应用场景
GraphQL
是由Facebook
在 2012 An open-source query language founded in 2008.before it was open sourced,Facebook
Already used in internal mobile applications.GraphQL
作为通用的REST
An alternative to the architecture was developed,It allows the client to request only the data it needs——不多也不少,Everything is under the control of the client.
在一个
RESTful
架构下,Because backend developers are defined in each URL The data returned on the resource,Rather than front-end developers coming up with data requirements,Making it very difficult to get data on demand.Often the front end needs to request all the information in a resource,Even if only part of the data is needed.This problem is called overacquisition(overfetching).in the worst case,A client application has to request multiple resources instead of one,This usually initiates multiple network requests.Not only does this create problems of over-acquisition,It can also cause waterfall network requests(waterfall network requests).then it will be like GraphQL 之类的查询语言,Not only used on the server side,Also applies to the client,It is up to the client to decide what data is required,This only needs to send a request to the server.在 Facebook 的 GraphQL in mobile development scenarios,This greatly reduces forgetting requests,因为 GraphQL Only one request needs to be made at a time,And the amount of data in transit is also reduced.
优点
Declarative data fetching
GraphQLUsing query statement style,Get data in a declarative way.The client is in a query request,Select the required data and related field entities.Client according to its UI to determine the required fields.你可以说这是 UI Driven data acquisition.毕竟,GraphQL Provides an excellent separation of concerns:The client knows what data it needs,The server knows the structure of the data,and how to get from some data source(比如数据库、微服务、第三方 API)中拉取数据.
比方说,Airbnb 使用 GraphQL的例子,在 Airbnb A search interface in ,It is often necessary to search for housing experiences and other related information,To be able to retrieve all data in one request,一个 GraphQL 查询会根据 UI Select a portion of the data to achieve a perfect match.
单一数据源(Single Source of Truth)
在 GraphQL There is a single source of truth in the application:GraphQL schema.It provides a single source for all available data retrieval.鉴于 GraphQL 的 schema Usually defined on the server side,客户端可以基于 schema 读取(query)和写入(mutation)数据.因此,The server provides all available information,客户端只需要执行 GraphQL Query to get some data,或者通过 GraphQL Modify and change some data.
拼接 GraphQL Schema
拼接 Schema 使得多个 schemacan be aggregated into one.When do you need to consider this?Consider a backend microservice architecture.Each microservice handles business logic and data for a specific domain.因此,Each microservice can define its ownGraphQL架构.之后,使用 Schema Stitching will be all Schema Aggregate into one that can be accessed by clients Schema 中.最终,Each microservice can have its own GraphQL 端点,而一个 GraphQL APIGateway will all schema merged into one global schema 中,in order to make it available to clients.
GraphQL 自省(Introspection)
GraphQL Introspection allowed to pass GraphQL API 检索 GraphQL schema.因为 schema contains contains GraphQL API All available data,In itself is a perfect auto-generated API 文档.不仅仅是 API 的文档,Clients are also allowed to passmock GraphQL 的 schema 达到测试的目的,或者使用 schema The spliced interface retrieves multiple microservices schema.
缺点
N+1问题,解决方案:
DataLoader
GraphQL 查询的复杂性
When a client needs to query many nested fields at once,Front-end developers usually don't know that he is getting too much data by accessing different databases on the server side.This requires a mechanism(For example, the deepest query depth、Query complexity weight、避免递归、持久化查询)to block from the client(性能)expensive query.
Query frequency limit
Another problem is frequency limitation,在 REST 中,Can be simply declared”一天之中,We are only allowed to request so many resources“,在一个独立的 GraphQL It is difficult to do this in operation,Because the overhead of any operation can be cheap or expensive.These are the ones that have public GraphQL API The specific rate limit calculation proposed by the company,It usually boils down to the aforementioned maximum query depth and query complexity weighting issues.
GraphQL 缓存
A simple cache,相比 REST,在 GraphQL implementation can become extremely complex.在 REST you pass URL 访问资源,So you can implement caching at the resource level,because of resource usage URL 作为其标识符.在 GraphQL is complicated,Because even if it operates on the same entity,Every query is different.比如,一个查询中,You may only request the name of one author,But in another query you might also want to know his email address.This requires you to have a more robust mechanism to ensure field-level caching,实现起来并不简单.不过,多数基于 GraphQL The built-in libraries provide out-of-the-box caching mechanisms.
对象类型和字段
GraphQLDefault scalar type
Int
:有符号 32 位整数.Float
:有符号双精度浮点值.String
:UTF‐8 字符序列.Boolean
:true 或者 false.ID
:ID 标量类型表示一个唯一标识符,通常用以重新获取对象或者作为缓存中的键.ID 类型使用和 String 一样的方式序列化;然而将其定义为 ID 意味着并不需要人类可读型.
type Starship {
id: ID!
nick: [String!]!
length(unit: LengthUnit = METER): Float
}
Starship
为GraphQL 对象类型id
/nick
/length
为Starship
类型上的字段nick
为非空数组,其数组元素为String
且非空
See object types and fields for detailed definitions https://graphql.cn/learn/schema/#type-language
查询和变更类型
schema
内有两个特殊类型,defines eachGraphQL
查询的入口
每一个 GraphQL 服务都有一个
query
类型,可能有一个mutation
类型
schema {
"查询"
query: Query
"变更"
mutation: Mutation
}
示例:
# 定义查询接口
type Query {
# 无参, 返回字符串
hello: String
# Field parameter and cannot be empty, 返回普通对象
bookById(id: ID!): Book
# 对象参数, 返回列表
books(book: BookInput): [Book]
}
# Define the modification interface
type Mutation {
hello: String
}
应用示例
一个 GraphQL 查询在被验证后,GraphQL 服务器会将之执行,并返回与请求的结构相对应的结果,该结果通常会是 JSON 的格式.
schema
type Query {
human(id: ID!): Human
}
type Human {
name: String
appearsIn: [Episode]
starships: [Starship]
}
enum Episode {
NEWHOPE
EMPIRE
JEDI
}
type Starship {
name: String
}
请求参数
{
human(id: 1002) {
name
appearsIn
starships {
name
}
}
}
响应结果
{
"data": {
"human": {
"name": "Han Solo",
"appearsIn": [
"NEWHOPE",
"EMPIRE",
"JEDI"
],
"starships": [
{
"name": "Millenium Falcon"
},
{
"name": "Imperial shuttle"
}
]
}
}
}
参考资料:
边栏推荐
- 《MySQL高级篇》四、索引的存储结构
- 学生管理系统
- TDengineGUI cannot connect to TDengine
- Defense Ideas for a Type of SMS Vulnerability
- oracle row to column, column to row summary
- Dcat Admin 安装
- [Mozhe Academy] Identity Authentication Failure Vulnerability Actual Combat
- misc-file steganography of CTF
- The number of warehouse 】 data quality
- MySQL - 函数及约束命令
猜你喜欢
随机推荐
【数仓】数据质量
Using PyQt5 to add an interface to YoloV5 (1)
Nacos配置中心用法详细介绍
学生管理系统
The most powerful and most commonly used SQL statements in history
Flink PostgreSQL CDC configuration and FAQ
【Spark】Spark 高频面试题英语版(1)
[Mini Program Project Development--Jingdong Mall] Classification Navigation Area of uni-app
Detailed explanation of ClickHouse query statement
Invalid bound statement (not found)出现的原因和解决方法
[MATLAB] Image Processing - Recognition of Traffic Signs
C#中使用OleDb操作access数据库
TypeError The view function did not return a valid response. The function either returned None 的解决
C#中对委托的理解和使用
awd --waf deployment
vulnhub-XXE ctf security question
MySQL 5.7 installation tutorial (all steps, nanny tutorials)
TDengineGUI无法连接TDengine
2022CISCNmisc
Student management system