-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
file.ts
220 lines (190 loc) · 4.9 KB
/
file.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*
* @adonisjs/bodyparser
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { join } from 'node:path'
import { Exception } from '@poppinss/utils'
import Macroable from '@poppinss/macroable'
import { moveFile } from '../helpers.js'
import { SizeValidator } from './validators/size.js'
import { ExtensionValidator } from './validators/extensions.js'
import type { FileJSON, FileUploadError, FileValidationOptions } from '../types.js'
/**
* The file holds the meta/data for an uploaded file, along with
* an errors occurred during the upload process.
*/
export class MultipartFile extends Macroable {
/**
* File validators
*/
#sizeValidator = new SizeValidator(this)
#extensionValidator = new ExtensionValidator(this)
/**
* A boolean to know if file is an instance of this class
* or not
*/
isMultipartFile: true = true
/**
* Field name is the name of the field
*/
fieldName: string
/**
* Client name is the file name on the user client
*/
clientName: string
/**
* The headers sent as part of the multipart request
*/
headers: Record<string, any>
/**
* File size in bytes
*/
size: number = 0
/**
* The extname for the file.
*/
extname?: string
/**
* Upload errors
*/
errors: FileUploadError[] = []
/**
* Type and subtype are extracted from the `content-type`
* header or from the file magic number
*/
type?: string
subtype?: string
/**
* File path is only set after the move operation
*/
filePath?: string
/**
* File name is only set after the move operation. It is the relative
* path of the moved file
*/
fileName?: string
/**
* Tmp path, only exists when file is uploaded using the
* classic mode.
*/
tmpPath?: string
/**
* The file meta data
*/
meta: any = {}
/**
* The state of the file
*/
state: 'idle' | 'streaming' | 'consumed' | 'moved' = 'idle'
/**
* Whether or not the validations have been executed
*/
get validated(): boolean {
return this.#sizeValidator.validated && this.#extensionValidator.validated
}
/**
* A boolean to know if file has one or more errors
*/
get isValid() {
return this.errors.length === 0
}
/**
* Opposite of [[this.isValid]]
*/
get hasErrors() {
return !this.isValid
}
/**
* The maximum file size limit
*/
get sizeLimit() {
return this.#sizeValidator.maxLimit
}
set sizeLimit(limit: number | string | undefined) {
this.#sizeValidator.maxLimit = limit
}
/**
* Extensions allowed
*/
get allowedExtensions() {
return this.#extensionValidator.extensions
}
set allowedExtensions(extensions: string[] | undefined) {
this.#extensionValidator.extensions = extensions
}
constructor(
data: { fieldName: string; clientName: string; headers: any },
validationOptions: Partial<FileValidationOptions>
) {
super()
this.sizeLimit = validationOptions.size
this.allowedExtensions = validationOptions.extnames
this.fieldName = data.fieldName
this.clientName = data.clientName
this.headers = data.headers
}
/**
* Validate the file
*/
validate() {
this.#extensionValidator.validate()
this.#sizeValidator.validate()
}
/**
* Mark file as moved
*/
markAsMoved(fileName: string, filePath: string) {
this.filePath = filePath
this.fileName = fileName
this.state = 'moved'
}
/**
* Moves the file to a given location. Multiple calls to the `move` method are allowed,
* incase you want to move a file to multiple locations.
*/
async move(location: string, options?: { name?: string; overwrite?: boolean }): Promise<void> {
if (!this.tmpPath) {
throw new Exception('property "tmpPath" must be set on the file before moving it', {
status: 500,
code: 'E_MISSING_FILE_TMP_PATH',
})
}
options = Object.assign({ name: this.clientName, overwrite: true }, options)
const filePath = join(location, options.name!)
try {
await moveFile(this.tmpPath, filePath, { overwrite: options.overwrite! })
this.markAsMoved(options.name!, filePath)
} catch (error) {
if (error.message.includes('destination file already')) {
throw new Exception(
`"${options.name!}" already exists at "${location}". Set "overwrite = true" to overwrite it`
)
}
throw error
}
}
/**
* Returns file JSON representation
*/
toJSON(): FileJSON {
return {
fieldName: this.fieldName,
clientName: this.clientName,
size: this.size,
filePath: this.filePath,
fileName: this.fileName,
type: this.type,
extname: this.extname,
subtype: this.subtype,
state: this.state,
isValid: this.isValid,
validated: this.validated,
errors: this.errors,
meta: this.meta,
}
}
}