基本使用方法(查詢交掏、更改)
- 服務(wù)端(類型定義沈条,resolvers定義):
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
type Mutation {
addBook(title: String, author: String): Book
}
`;
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
const resolvers = {
Query: {
books: () => books,
},
Mutation: {
addBook: (parent, args, context, info) => books.push({title: args.title, author: args.author})
}
};
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`?? Server ready at ${url}`);
});
- 客戶端
# 查詢
query {
books {
title
author
}
}
# 更改
mutation {
addBook(title: book-title, author: book-author) {
title
author
}
}
發(fā)布訂閱
與普通的訂閱發(fā)布模式類似酣难。首先創(chuàng)建一個發(fā)布訂閱示例让虐,然后為一些類型添加一些訂閱者侯养,每次調(diào)用發(fā)布,都會通知每一個訂閱者澄干。
例子如下:
const { PubSub } = require('apollo-server');
const pubsub = new PubSub();
const typeDefs = gql`
type Subscription {
postAdded: Post
}
type Query {
posts: [Post]
}
type Mutation {
addPost(author: String, comment: String): Post
}
type Post {
author: String
comment: String
}
`
const POST_ADDED = 'POST_ADDED';
const resolvers = {
Subscription: {
postAdded: {
subscribe: () => pubsub.asyncIterator([POST_ADDED]),
},
},
Query: {
posts(root, args, context) {
return postController.posts();
},
},
Mutation: {
addPost(root, args, context) {
pubsub.publish(POST_ADDED, { postAdded: args });
return postController.addPost(args);
},
},
};