-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (69 loc) · 1.57 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const { ApolloServer, gql, PubSub, makeExecutableSchema } = require('apollo-server');
const { applyMiddleware } = require('graphql-middleware');
const { shield, deny, allow, rule } = require('graphql-shield');
const pubsub = new PubSub();
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
type Subscription {
book: Book
}
`;
const resolvers = {
Query: {
books: () => books,
},
Subscription: {
book: {
subscribe: () => pubsub.asyncIterator(['book']),
resolve: payload => payload,
},
},
};
// Rule runs on resolve function above but not on subscribe function where it would be useful
const check = rule({
cache: 'no_cache',
})(async () => {
console.log('----------- Rule check -----------');
return true;
});
const permissions = {
Query: {
books: allow,
},
Subscription: {
book: check,
},
Book: allow,
};
const shieldMiddleware = shield(permissions, {
fallbackRule: deny,
});
const schema = applyMiddleware(
makeExecutableSchema({
typeDefs,
resolvers,
}),
shieldMiddleware,
);
const server = new ApolloServer({ schema });
server.listen({ port: 4100 }).then(({ url, subscriptionsUrl }) => {
console.log(`🚀 Server ready at ${url}`);
console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`);
});
setInterval(()=>pubsub.publish('book', books[0]), 1000);