rest vs graphql
good things from rest
- stateless API, which make web-scalable and easy-manage
- resource-oriented programming and structured accessto resources, which make many goods, such as cacheable, retriable.
the bad things with rest
`1+N` problem: fetch list api, fetch every detail api to get more message.
- overfetching(fetch too much data which was not requried)
- underfetching(not-enough data from api, which make it need multi request to get the data).
- too flexible, may things this like dynamic(rest) vs static(graphql).
the answer from rest-api design.
- overfetching: add special-api?
- underfetching(1+N): compound-resource
- too flexible: swagger?
graphql core-concepts
the schema-definition-language(SDL)
the spec to define you API and data-model.
# a data-model named Person
type Person {
name: String! # ! mark this field required.
age: Int!
posts: [Post]!
}
type Post {
title: String!
author: Person!
}
Query
graph-like query, which solve the overfetch and underfetch problem.
# query example
{
allPersons {
name
age
# query nested structed
posts {
title
}
}
}
# query with arguments
{
allPersons(last: 2){
name
}
}
write with Mutations
three type mutation: create/update/delete
# Mutation need `mutation` prefix
mutation {
# the argument was data to create
createPersion(name: "Bob", age: 36) {
# this was data to return, allow single-roudtrip to mutationi and query data.
name
age
}
}
realtime update with Subscriptions
like websocket notify in web. not request-response type, represent a stream of data sent over to the client.
- TODO how to implement this in real-server-env.
subscription {
newPersion {
name
age
}
}
# put it all together
type Query {
allPersons(last: Int): [Persion]!
}
type Mutation {
createPerson(name: String!, age: Int!): Person!
}
type Subscription {
newPerson: Person!
}
type Person {
name: String!
age: Int!
# ??
posts: [Post!]!
}
type Post {
title: String!
author: Person!
}
bit picture
graphql was release as a specification, which describe in detail the behaviour of a graphql server.
the usual architecture of graphql-server.
- graphql-server with a connected database.
- thin layer in front of a number of third party api
- a hybrid of above
the graphql problem
TODO the graph-design make data-relationship complex.
how to do cache for the API??
data-relation would cause stateful-api, which has scalable-problem??
TODO no idempotent/unsafe method distinguish.
how to design retry failed idempotent-method?? how to apply multi mutation at-once??
TODO the perfermance problem
graphql reslove was knows as CPU-unfriendly, which may case perfermance-problem.
the data-loader desgin detail??