-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
graphql.js
309 lines (286 loc) · 8.73 KB
/
graphql.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import debug from 'debug';
import gql from 'graphql-tag';
import ApolloClient from 'apollo-boost';
import { flatten, uniqBy, pick } from 'lodash';
// Alternative setup with GraphQLClient from graphql-request
// import { GraphQLClient } from 'graphql-request';
import cache from './cache';
import fetch from './fetch';
import { queryString, md5, sleep, randomInteger } from './utils';
const oneDayInSeconds = 24 * 60 * 60;
const thirtyMinutesInSeconds = 30 * 60;
const oneMinuteInSeconds = 60;
const debugGraphql = debug('graphql');
const getGraphqlUrl = ({ version = 'v1' } = {}) => {
const apiKey = process.env.API_KEY;
const baseApiUrl = process.env.API_URL;
return `${baseApiUrl}/graphql/${version}${apiKey ? `?api_key=${apiKey}` : ''}`;
};
let client;
function getClient() {
if (!client) {
// client = new GraphQLClient(getGraphqlUrl(), { headers });
client = new ApolloClient({ fetch, uri: getGraphqlUrl({ version: 'v1' }) });
}
return client;
}
function graphqlRequest(query, variables) {
// With GraphQLClient from graphql-request
// return getClient().request(query, variables);
// With ApolloClient as client
return getClient()
.query({ query, variables, fetchPolicy: 'network-only' })
.then((result) => result.data);
}
/*
Used by:
- logo.js: requires `type`, `name` and `image`
- background.js: requires `backgroundImage`
*/
export async function fetchCollective(collectiveSlug) {
const query = gql`
query fetchCollective($collectiveSlug: String) {
Collective(slug: $collectiveSlug) {
name
type
image
backgroundImage
isGuest
parentCollective {
image
backgroundImage
}
}
}
`;
const result = await graphqlRequest(query, { collectiveSlug });
return result.Collective;
}
export async function fetchCollectiveWithCache(collectiveSlug, options = {}) {
let cacheKey;
if (options.hash) {
cacheKey = `collective_v2_${collectiveSlug}_${options.hash}`;
} else {
cacheKey = `collective_v2_${collectiveSlug}`;
}
let collective = await cache.get(cacheKey);
if (!collective) {
collective = await fetchCollective(collectiveSlug);
cache.set(cacheKey, collective, oneDayInSeconds + randomInteger(3600));
}
return collective;
}
export async function fetchMembersStats(variables) {
const { backerType, tierSlug } = variables;
let query, processResult;
if (backerType) {
query = gql`
query fetchMembersStats($collectiveSlug: String) {
Collective(slug: $collectiveSlug) {
stats {
backers {
all
users
organizations
}
}
}
}
`;
processResult = (res) => {
let name, count;
if (backerType.match(/sponsor/i) || backerType.match(/organization/i)) {
count = res.Collective.stats.backers.organizations;
name = backerType;
} else if (backerType.match(/backer/i) || backerType.match(/individual/i)) {
count = res.Collective.stats.backers.users;
name = backerType;
} else {
count = res.Collective.stats.backers.all;
name = 'financial contributors';
}
return { name, count };
};
} else if (tierSlug) {
query = gql`
query fetchMembersStatsForTier($collectiveSlug: String, $tierSlug: String) {
Collective(slug: $collectiveSlug) {
tiers(slug: $tierSlug) {
slug
name
stats {
totalDistinctOrders
}
}
}
}
`;
processResult = (result) => {
if (result.Collective.tiers.length === 0) {
throw new Error('Tier not found');
}
return {
count: result.Collective.tiers[0].stats.totalDistinctOrders,
slug: result.Collective.tiers[0].slug,
name: result.Collective.tiers[0].name,
};
};
}
const result = await graphqlRequest(query, variables);
const count = processResult(result);
return count;
}
export async function fetchMembersStatsWithCache(params) {
const cacheKey = `members_stats_${md5(queryString.stringify(params))}`;
let stats = await cache.get(cacheKey);
if (!stats) {
stats = await fetchMembersStats(params);
cache.set(cacheKey, stats, thirtyMinutesInSeconds + randomInteger(300));
}
return stats;
}
/*
Used by:
- avatar.js: requires `type`, `name`, `image` and `slug`
- website.js: requires `website`, `twitterHandle` and `slug`
- banner.js: requires `type`, `name`, `image`, `website` and `slug` (generateSvgBanner)
*/
export async function fetchMembers({ collectiveSlug, tierSlug, backerType, isActive }) {
// Optimize some 404s that are heavily sent
if (
[
'algorithmvisualizer',
'angular-universal-pwa',
'jquery-adaptive-backgrounds',
'lottie-web',
'postwoman',
'react-native-camera-mlkit',
'vsc-material-theme',
].includes(collectiveSlug)
) {
throw new Error('Collective not found.');
}
let query, processResult, type, role;
if (backerType === 'contributors') {
query = gql`
query fetchContributors($collectiveSlug: String) {
Collective(slug: $collectiveSlug) {
githubContributors
}
}
`;
processResult = (result) => {
const users = result.Collective.githubContributors;
return Object.keys(users).map((username) => {
return {
slug: username,
type: 'GITHUB_USER',
image: `https://avatars.githubusercontent.com/${username}?s=96`,
website: `https://github.com/${username}`,
};
});
};
} else if (backerType) {
if (backerType.match(/sponsor/i) || backerType.match(/organization/i)) {
type = 'ORGANIZATION,COLLECTIVE';
} else {
type = 'USER';
}
role = 'BACKER';
query = gql`
query fetchMembersWithRole($collectiveSlug: String!, $type: String!, $role: String!, $isActive: Boolean) {
allMembers(
collectiveSlug: $collectiveSlug
type: $type
role: $role
isActive: $isActive
orderBy: "totalDonations"
) {
member {
type
slug
name
image
website
twitterHandle
}
}
}
`;
processResult = (result) =>
uniqBy(
result.allMembers.map((m) => m.member),
(m) => m.slug,
);
} else if (tierSlug) {
tierSlug = tierSlug.split(',');
query = gql`
query fetchMembersWithTier($collectiveSlug: String, $tierSlug: [String], $isActive: Boolean) {
Collective(slug: $collectiveSlug) {
tiers(slugs: $tierSlug) {
orders(isActive: $isActive) {
fromCollective {
type
slug
name
isGuest
image
website
twitterHandle
}
}
}
}
}
`;
processResult = (result) => {
const allOrders = flatten(result.Collective.tiers.map((t) => t.orders));
const allCollectives = allOrders.map((o) => o.fromCollective);
return uniqBy(allCollectives, (c) => c.slug);
};
}
const result = await graphqlRequest(query, {
collectiveSlug,
tierSlug,
type,
role,
isActive,
});
const members = processResult(result);
return members;
}
export async function fetchMembersWithCache(params) {
params = pick(params, ['collectiveSlug', 'tierSlug', 'backerType', 'isActive']);
const cacheKey = `users_${md5(queryString.stringify(params))}`;
const cacheKeyFetching = `${cacheKey}_fetching`;
let users = await cache.get(cacheKey);
if (!users) {
debugGraphql(`fetchMembersWithCache ${params.collectiveSlug} ${cacheKey} miss`);
let fetching = await cache.has(cacheKeyFetching);
if (fetching) {
while (fetching) {
debugGraphql(`fetchMembersWithCache ${params.collectiveSlug} ${cacheKey} waiting`);
await sleep(100);
fetching = await cache.has(cacheKeyFetching);
}
debugGraphql(`fetchMembersWithCache ${params.collectiveSlug} ${cacheKey} available`);
users = await cache.get(cacheKey);
}
if (!users) {
debugGraphql(`fetchMembersWithCache ${params.collectiveSlug} ${cacheKey} fetching`);
cache.set(cacheKeyFetching, true, oneMinuteInSeconds);
try {
users = await fetchMembers(params);
cache.set(cacheKey, users, thirtyMinutesInSeconds + randomInteger(300));
debugGraphql(`fetchMembersWithCache ${params.collectiveSlug} ${cacheKey} set`);
cache.del(cacheKeyFetching);
} catch (e) {
cache.del(cacheKeyFetching);
throw e;
}
}
} else {
debugGraphql(`fetchMembersWithCache ${params.collectiveSlug} ${cacheKey} hit`);
}
return users;
}