generated from ubiquity/ts-template
/
fetch-avatar.ts
59 lines (56 loc) · 2.07 KB
/
fetch-avatar.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
57
58
59
import { Octokit } from "@octokit/rest";
import { getGitHubAccessToken } from "../getters/get-github-access-token";
import { getImageFromCache, saveImageToCache } from "../getters/get-indexed-db";
import { organizationImageCache } from "./fetch-issues-full";
export async function fetchAvatar(orgName: string) {
// Check local cache first
const cachedAvatar = organizationImageCache.get(orgName);
if (cachedAvatar) {
return Promise.resolve();
}
// If not in local cache, check IndexedDB
const avatarBlob = await getImageFromCache({ dbName: "GitHubAvatars", storeName: "ImageStore", orgName: `avatarUrl-${orgName}` });
if (avatarBlob) {
// If the avatar Blob is found in IndexedDB, add it to the cache
organizationImageCache.set(orgName, avatarBlob);
return Promise.resolve();
}
// If not in IndexedDB, fetch from network
const octokit = new Octokit({ auth: await getGitHubAccessToken() });
try {
const {
data: { avatar_url: avatarUrl },
} = await octokit.rest.orgs.get({ org: orgName });
if (avatarUrl) {
// Fetch the image as a Blob and save it to IndexedDB
const response = await fetch(avatarUrl);
const blob = await response.blob();
await saveImageToCache({
dbName: "GitHubAvatars",
storeName: "ImageStore",
keyName: "name",
orgName: `avatarUrl-${orgName}`,
avatarBlob: blob,
});
organizationImageCache.set(orgName, blob);
}
} catch (error) {
console.error(`Failed to fetch avatar for organization ${orgName}: ${error}`);
const {
data: { avatar_url: avatarUrl },
} = await octokit.rest.users.getByUsername({ username: orgName });
if (avatarUrl) {
// Fetch the image as a Blob and save it to IndexedDB
const response = await fetch(avatarUrl);
const blob = await response.blob();
await saveImageToCache({
dbName: "GitHubAvatars",
storeName: "ImageStore",
keyName: "name",
orgName: `avatarUrl-${orgName}`,
avatarBlob: blob,
});
organizationImageCache.set(orgName, blob);
}
}
}