This repository has been archived by the owner on Mar 4, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
users.ts
56 lines (48 loc) · 1.39 KB
/
users.ts
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
import { requestData } from './utils/graphql.js';
import { TTLCache } from './utils/cache.js';
interface User {
name: string;
login: string;
}
const CACHE_TTL = 7 * 24 * 60 * 60 * 1000;
export const cache = new TTLCache<string, User>(CACHE_TTL);
/**
* Gets user details (name in particular) for each given logins
* @param logins user login names
*/
export async function getUsersDetails(logins: string[]) {
const results: { [login: string]: User } = Object.create(null);
for (const login of logins) {
const cached = cache.get(login);
if (cached !== undefined) {
results[login] = cached;
}
}
const loginsToFetch = logins.filter(login => !cache.get(login));
if (!loginsToFetch.length) {
return results;
}
const query = createQuery(loginsToFetch);
const data: { [login: string]: User } = await requestData(query);
for (const user of Object.values(data)) {
if (!user) continue;
results[user.login] = user;
cache.set(user.login, user);
}
return results;
}
function createQuery(logins: string[]) {
// sending special characters in GraphQL query alias isn't allowed
const alias = (str: string) => str.replace(/[^\w]/g, '_');
const subQueries = logins.map(
login => `${alias(login)}: user(login: "${login}") { ...user }`,
);
return `
query {
${subQueries.join('\n')}
}
fragment user on User {
name
login
}`;
}