-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
102 lines (96 loc) · 2.75 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const { makeExecutableSchema } = require('@graphql-tools/schema');
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const {
defaultSetState,
millisecondsToSeconds,
rateLimitDirective
} = require('graphql-rate-limit-directive');
const { RateLimiterMemory } = require('rate-limiter-flexible');
// This is not necessary, it exists to demonstrate when we check the rate limit usage
class DebugRateLimiterMemory extends RateLimiterMemory {
consume(key, pointsToConsume, options) {
console.log(`[CONSUME] ${key} for ${pointsToConsume}`);
return super.consume(key, pointsToConsume, options);
}
}
const directiveName = 'rateLimit';
const {
rateLimitDirectiveTypeDefs,
rateLimitDirectiveTransformer,
} = rateLimitDirective({
name: directiveName,
setState: defaultSetState(directiveName), // IMPORTANT: Where to store the request's rate limit state in context
limiterClass: DebugRateLimiterMemory
});
const resolvers = {
Query: {
books: () => [
{
title: 'A Game of Thrones',
author: 'George R. R. Martin',
},
{
title: 'The Hobbit',
author: 'J. R. R. Tolkien',
},
],
quote: () =>
'The future is something which everyone reaches at the rate of sixty minutes an hour, whatever he does, whoever he is. ― C.S. Lewis',
},
};
let schema = makeExecutableSchema({
typeDefs: [
rateLimitDirectiveTypeDefs,
`# Allow each field to be queried three times every 15 seconds
type Query @rateLimit(limit: 3, duration: 15) {
books: [Book!]
quote: String
}
type Book {
title: String
author: String
}`,
],
resolvers,
});
schema = rateLimitDirectiveTransformer(schema);
const app = express();
app.use(
'/graphql',
graphqlHTTP((request) => {
return {
schema,
extensions: (info) => {
// IMPORTANT: Fetch the request's rate limit state from context
const state = info.context[directiveName];
return { // Format state to desired output structure
[directiveName]: Object.entries(state).reduce((accumulator, [coordinate, response]) => {
accumulator[coordinate] = {
remaining: response.remainingPoints,
consumed: response.consumedPoints,
resets: millisecondsToSeconds(response.msBeforeNext),
};
return accumulator;
}, {}),
};
},
graphiql: {
defaultQuery: `# Welcome to GraphiQL
#
# Allow each field to be queried three times every 15 seconds.
# Repeated requests within this time window will fail.
query {
quote
books {
title
author
}
}`
},
};
}),
);
app.listen(4000, () => {
console.log(`🚀 Server ready at http://localhost:4000/graphql`);
});