-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
72 lines (60 loc) · 1.54 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
type StrapiImage = {
height: number;
url: string;
width: number;
};
type StrapiImageFormats = {
thumbnail?: StrapiImage;
small?: StrapiImage;
medium?: StrapiImage;
large?: StrapiImage;
};
export enum PreferredSize {
Thumbnail = "thumbnail",
Small = "small",
Medium = "medium",
Large = "large",
}
type GetOptimizedImageParameters = {
image: { formats: StrapiImageFormats } & StrapiImage;
fallback?: "original" | "smaller";
preferredSize?: PreferredSize;
};
type OptimizedImage = {
src: string;
} & Omit<StrapiImage, "url">;
export function strapiOptimizedImage({
image: { formats, height, url: src, width },
fallback = "original",
preferredSize = PreferredSize.Large,
}: GetOptimizedImageParameters): OptimizedImage {
if (!formats?.[preferredSize]) {
if (fallback === "original") {
return { height, src, width };
}
const image = smallerImage(formats, preferredSize);
if (!image) {
return { height, src, width };
}
return image;
}
return {
height: formats[preferredSize].height,
src: formats[preferredSize].url,
width: formats[preferredSize].width,
};
}
function smallerImage(
formats: StrapiImageFormats,
preferredSize: PreferredSize,
): OptimizedImage | undefined {
const preferredSizes = Object.values(PreferredSize);
const end = preferredSizes.indexOf(preferredSize);
for (const ps of preferredSizes.slice(0, end)) {
if (formats[ps]) {
const { height, url: src, width } = formats[ps];
return { height, src, width };
}
}
return undefined;
}