-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
51 lines (44 loc) · 1.41 KB
/
index.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
const apiEndpoint = "/api/v1/blurhash";
type Options = { fetch: typeof global.fetch };
export const getBlurhash = async (url: string, { fetch }: Options): Promise<string | undefined> => {
const response = await fetch(`${apiEndpoint}/${encodeURIComponent(url)}`);
if (!response.ok) return;
return response.text();
};
type Nullable<T> = T | null | undefined;
type Asset = Nullable<{
sys?: Nullable<{
id?: Nullable<string>;
}>;
url?: Nullable<string>;
contentType?: Nullable<string>;
}>;
export const getBlurhashMapFromAssetList = async (
assets: (Asset | null | undefined)[],
options: Options,
): Promise<Record<string, string>> =>
Object.fromEntries(
(
await Promise.all(
assets
.filter((item): item is Asset => !!item)
.map(async (item) => {
if (!item?.sys?.id || !item?.url || !item?.contentType?.startsWith("image/")) return [];
const blurhash = await getBlurhash(item.url, options);
if (!blurhash) return [];
return [[item.sys.id, blurhash]];
}),
)
).flat(),
);
type RichTextForBlurhashes = Nullable<{
links?: Nullable<{
assets?: Nullable<{
block?: Nullable<(Asset | null | undefined)[]>;
}>;
}>;
}>;
export const getBlurhashMapFromRichText = async (
richText: RichTextForBlurhashes,
options: Options,
) => getBlurhashMapFromAssetList(richText?.links?.assets?.block ?? [], options);