GraphQL
與 RESTful、GRPC類似,均為 http 上層的後端與前端溝通方式
Server 用法
const typeDefs = gql`
"""
使用者
"""
type User {
"識別碼"
id: ID
"名字"
name: String
"年齡"
age: Int
"朋友"
friends(a: Int): [User]
}
type Query {
hello: String
"取得當下使用者"
me: User
"取得所有使用者"
users: [User]
}
type Mutation {
"新增使用者"
addUser(id: ID, name: String!, age: Int): User
}
`;
const resolvers = {
Query: {
hello: () => "world",
me: () => users[0],
users: () => users,
},
Mutation: {
addUser: (root, args, context) => {
const { id, name, age } = args;
// 新增 post
users.push({
id,
name,
age,
});
return users[3];
},
},
User: {
friends: (parent, args, context) => {
const { friendIds } = parent;
return users.filter((user) => friendIds.includes(user.id));
},
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
context: () => {
return {a: ""}
}
});Query
Fragment
Mutation
Subscription
typeDefs
預設 types

自定義 scalar type
resolvers
Subscribe
Authorization
其他工具

Graphql-tag
@apollo/client
React hook
常見問題
Last updated