-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.ts
More file actions
59 lines (50 loc) · 1.71 KB
/
index.ts
File metadata and controls
59 lines (50 loc) · 1.71 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
import { Provider } from '../../../uploads/provider'
import process from 'process'
import path from 'path'
import fs from 'fs'
import { ServerResponse } from 'http'
import crypto from 'crypto'
import { FastifyInstance } from 'fastify'
import fastifyStatic from 'fastify-static'
interface LocalProviderOptions {
uploadDirectory?: string
}
export default class LocalProvider implements Provider {
private readonly uploadDirectory: string
constructor(options: LocalProviderOptions, app: FastifyInstance) {
this.uploadDirectory = path.resolve(
options.uploadDirectory ?? path.join(process.cwd(), 'uploads')
)
void app.register(fastifyStatic, {
root: this.uploadDirectory,
prefix: '/uploads/',
decorateReply: false,
dotfiles: 'allow',
index: false,
setHeaders: (res: ServerResponse) => {
res.setHeader('cache-control', 'public, max-age=31557600, immutable')
res.setHeader('content-disposition', 'attachment')
},
})
}
private getKey(hash: string, name: string): string {
return `${hash}/${name}`
}
async upload(data: Buffer, name: string): Promise<string> {
const hash = crypto.createHash('sha256').update(data).digest('hex')
const key = this.getKey(hash, name)
const filePath = path.join(this.uploadDirectory, key)
await fs.promises.mkdir(path.dirname(filePath), { recursive: true })
await fs.promises.writeFile(filePath, data)
return `/uploads/${key}`
}
async getUrl(sha256: string, name: string): Promise<string | null> {
const key = this.getKey(sha256, name)
try {
await fs.promises.access(path.join(this.uploadDirectory, key))
} catch {
return null
}
return `/uploads/${key}`
}
}