-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.js
96 lines (79 loc) · 2.01 KB
/
upload.js
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
const {URLSearchParams} = require('url')
, {buffer} = require('micro')
, {lookup} = require('mime-types')
, {use, upload} = require('./storage')
, getProperties = (...parameters) =>
parameters.reduce((result, [name, value]) => {
if (value)
result[name] = value
return result
}, {})
module.exports = async (request, response) => {
if (request.method == 'PATCH') {
const fileFolder = request.headers['upload-name'] + '/'
, firstPart = request.headers['upload-offset'] == 0
if (firstPart) {
var fileExists = true
try {
await use('headObject', fileFolder)
} catch (error) {
if (error.code == 'NotFound')
fileExists = false
else
throw error
}
}
if (firstPart && fileExists)
response.statusCode = 403
else {
var uploads = []
if (firstPart) {
const {maximumDownloadCount, expiryDateAndTime} = Array.from(
new URLSearchParams(request.url.replace('/?', '')).entries()
).reduce((result, [name, value]) => ({
...result, [name]: value
}), {})
uploads.push(
upload(fileFolder, undefined, {
...getProperties([
'ContentType', lookup(request.headers['upload-name'])
])
, Metadata: {
contentLength: request.headers['upload-length']
, ...getProperties(
['maximumDownloadCount', maximumDownloadCount]
, ['expiryDateAndTime', expiryDateAndTime]
)
}
})
, upload(fileFolder + 'downloadCount' + '/')
)
}
uploads.push(
upload(
fileFolder + 'part' + '/' + request.headers['upload-offset']
, await buffer(request)
)
)
}
}
[
['Access-Control-Allow-Origin', '*']
, ...(request.method == 'OPTIONS' ? [
, ['Access-Control-Allow-Methods', 'PATCH']
, ['Access-Control-Allow-Headers', [
'Content-Type'
, 'Upload-Length'
, 'Upload-Name'
, 'Upload-Offset'
]]
, ['Access-Control-Max-Age', 7200]
] : [])
].forEach(header =>
header &&
response.setHeader(...header)
)
if (uploads)
await Promise.all(uploads)
response.end()
}