Repository navigation
Expand file tree
/
Copy pathimage-cache.ts
More file actions
67 lines (55 loc) · 1.69 KB
/
Copy pathimage-cache.ts
File metadata and controls
67 lines (55 loc) · 1.69 KB
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
import fetch from 'node-fetch'
import sharp from 'sharp'
/**
* This module was inspired by Zach Leatherman's `avatar-local-cache` library.
* Check out https://github.com/zachleat/avatar-local-cache for a similar,
* pre-packaged solution.
*/
export interface AvatarCacheOptions {
/** The path to write the images to. */
outputDirectory: string
/** The max width of the avatars. */
width?: number
}
export class AvatarCache {
outputDirectory: string
width: number
constructor({ outputDirectory, width = 120 }: AvatarCacheOptions) {
this.outputDirectory = outputDirectory
this.width = width
}
async urlToFile(url: string, outputFileSlug: string) {
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error(
`Bad status code for ${url}. ${response.status}: ${response.statusText}`,
)
}
const body = await response.arrayBuffer()
return this.processImage(body, outputFileSlug)
} catch (error) {
console.error(`Error processing ${url}\nError: ${error}`)
}
}
private async processImage(body: ArrayBuffer, outputFileSlug: string) {
const { width, outputDirectory } = this
const output = `${outputDirectory}/${outputFileSlug}`
const img = sharp(Buffer.from(body)).resize({
width: width,
withoutEnlargement: true,
})
const metadata = await img.metadata()
await this.toJpeg(img, metadata, `${output}.jpg`)
return `${outputFileSlug}.jpg`
}
private async toJpeg(
img: sharp.Sharp,
metadata: sharp.Metadata,
slug: string,
) {
const jpeg = metadata.format !== 'jpeg' ? img.jpeg() : img
await jpeg.toFile(slug)
}
}
export default AvatarCache