-
-
Notifications
You must be signed in to change notification settings - Fork 107
/
upload.ts
192 lines (161 loc) · 4.54 KB
/
upload.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { S3 } from '@aws-sdk/client-s3'
import { mkdirpSync } from 'mkdirp'
import { Request } from 'express'
import { unlink, writeFile } from 'fs/promises'
import { extname, resolve } from 'path'
import { createReadStream, readdirSync } from 'fs'
import { assertValid, Validator, UnwrapBody } from '/common/valid'
import { config } from '../config'
const s3 = new S3({
region: 'us-east-1',
forcePathStyle: false,
endpoint: `https://${config.storage.endpoint}`,
credentials: {
accessKeyId: config.storage.id,
secretAccessKey: config.storage.key,
},
})
export type Attachment = {
field: string
original: string
type: string
content: Buffer | string
ext: string
}
export function handleForm<T extends Validator>(
req: Request,
type: T
): UnwrapBody<T> & { attachments: Attachment[] } {
const attachments: Attachment[] = []
if (Array.isArray(req.files)) {
for (const file of req.files) {
if (!isAllowedType(file.mimetype)) continue
const ext = file.mimetype.split('/').slice(-1)[0]
attachments.push({
field: file.fieldname,
content: file.buffer,
ext,
original: file.originalname,
type: file.mimetype,
})
}
}
const result: any = { ...req.body, attachments }
assertValid(type, result)
return result as any
}
export async function entityUpload(kind: string, id: string, attachment?: Attachment) {
if (!attachment) return
const filename = `${kind}-${id}`
return upload(attachment, filename)
}
export async function entityUploadBase64(kind: string, id: string, content?: string) {
if (!content) return
if (!content.includes(',')) return
const filename = `${kind}-${id}`
const attachment = toAttachment(content)
return upload(attachment, filename)
}
function toAttachment(content: string): Attachment {
const [prefix, base64] = content.split(',')
const type = prefix.slice(5, -7)
const [, ext] = type.split('/')
return {
ext,
field: '',
original: '',
type: getType(ext),
content: Buffer.from(base64, 'base64'),
}
}
export async function upload(attachment: Attachment, name: string, ttl?: number) {
const filename = `${name}.${attachment.ext}`
if (config.storage.enabled) {
await s3.putObject({
Expires: ttl ? new Date(Date.now() + ttl * 1000) : undefined,
Bucket: config.storage.bucket,
Key: `assets/${name}.${attachment.ext}`,
Body: attachment.content,
ContentType: attachment.type,
ACL: 'public-read',
})
return `/assets/` + filename
}
await saveFile(filename, attachment.content, ttl)
return `/assets/` + filename
}
export async function saveFile(filename: string, content: any, ttl?: number) {
if (config.storage.enabled) {
const res = await s3.putObject({
Expires: ttl ? new Date(Date.now() + ttl * 1000) : undefined,
Bucket: config.storage.bucket,
Key: `assets/${filename}`,
Body: content,
ContentType: getType(filename),
ACL: 'public-read',
})
res
return `/assets/` + filename
}
if (ttl) {
setTimeout(() => unlink(resolve(config.assetFolder, filename)).catch((err) => err), ttl * 1000)
}
await writeFile(resolve(config.assetFolder, filename), content, { encoding: 'utf8' })
return `/assets/${filename}`
}
export async function saveBase64File(filename: string, content: any) {
await writeFile(resolve(config.assetFolder, filename), content, 'base64')
return `/assets/${filename}`
}
export function getFile(filename: string) {
const stream = createReadStream(resolve(config.assetFolder, filename))
const type = getType(filename)
return { stream, type }
}
function createAssetFolder() {
try {
readdirSync(config.assetFolder)
} catch (ex) {
mkdirpSync(config.assetFolder)
}
}
function getType(filename: string) {
const ext = extname(filename)
switch (ext) {
case '.json':
return 'application/json'
case '.jpg':
case '.jpeg':
return 'image/jpeg'
case '.png':
return 'image/png'
case '.apng':
return 'image/apng'
case '.webp':
return 'image/webp'
case '.webm':
return 'video/webm'
case '.gif':
return 'image/gif'
case '.mp3':
return 'audio/mp3'
case '.wav':
return 'audio/wav'
case '.gif':
return 'image/gif'
}
return 'octet-stream'
}
createAssetFolder()
function isAllowedType(contentType: string) {
switch (contentType) {
case 'image/jpeg':
case 'image/jpg':
case 'image/png':
case 'image/apng':
case 'image/gif':
case 'image/webp':
return true
}
return false
}