@appweaver/skill 0.0.0-stage → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +29 -2
- package/index.d.ts +39 -0
- package/index.js +105 -0
- package/package.json +41 -3
- package/skill/GUIDELINES.md +383 -0
- package/skill/SKILL.md +120 -0
- package/skill/references/ai.md +231 -0
- package/skill/references/audit.md +218 -0
- package/skill/references/cache.md +233 -0
- package/skill/references/cli.md +729 -0
- package/skill/references/client.md +884 -0
- package/skill/references/configuration.md +1159 -0
- package/skill/references/database.md +345 -0
- package/skill/references/dependency-injection.md +301 -0
- package/skill/references/errors.md +466 -0
- package/skill/references/events.md +203 -0
- package/skill/references/logging.md +156 -0
- package/skill/references/mailer.md +393 -0
- package/skill/references/mcp.md +245 -0
- package/skill/references/modules.md +500 -0
- package/skill/references/patterns.md +1216 -0
- package/skill/references/queue.md +281 -0
- package/skill/references/realtime.md +572 -0
- package/skill/references/resources.md +2228 -0
- package/skill/references/scheduler.md +228 -0
- package/skill/references/security.md +1185 -0
- package/skill/references/sms.md +143 -0
- package/skill/references/spatial.md +197 -0
- package/skill/references/storage.md +500 -0
- package/skill/references/telemetry.md +202 -0
- package/skill/references/templates.md +488 -0
- package/skill/references/timeseries.md +312 -0
- package/skill/references/workflow.md +223 -0
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
# Storage
|
|
2
|
+
|
|
3
|
+
The storage module handles file persistence: storing, streaming, and deleting binary content. The default implementation
|
|
4
|
+
(`FilesystemStorage`, provider `local`) writes files to a local directory using a configurable name pattern; a module
|
|
5
|
+
of another driver (i.e. a cloud storage, see [modules](./modules.md)) replaces it once enabled. The module supports
|
|
6
|
+
range-based streaming for efficient large-file delivery (e.g., video, audio).
|
|
7
|
+
|
|
8
|
+
## Injecting Storage
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { inject } from '@appweaver/core';
|
|
12
|
+
import { Storage } from '@appweaver/common';
|
|
13
|
+
|
|
14
|
+
const storage = inject(Storage);
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
#### `storage.store(fileName, data, options?)`
|
|
20
|
+
|
|
21
|
+
Persists a readable stream under the given file name. Returns the stored file's path/ID (derived from
|
|
22
|
+
`STORAGE_NAME_PATTERN`), or `null` on failure.
|
|
23
|
+
|
|
24
|
+
| Parameter | Type | Description |
|
|
25
|
+
| ---------- | -------------- | ----------------------------------------------------------------------------------------------- |
|
|
26
|
+
| `fileName` | `string` | Original file name (used for name pattern) |
|
|
27
|
+
| `data` | `Readable` | Node.js readable stream with the content |
|
|
28
|
+
| `options` | `StoreOptions` | `{ contentType?, size? }`, the MIME type and the byte size, kept as metadata by a cloud storage |
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { createReadStream } from 'node:fs';
|
|
32
|
+
|
|
33
|
+
const fileId = await storage.store(
|
|
34
|
+
'avatar.png',
|
|
35
|
+
createReadStream('/tmp/upload.png')
|
|
36
|
+
);
|
|
37
|
+
// fileId e.g. "avatar-a3f8bc12.png"
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
**From a multipart upload (Fastify example):**
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
const upload = await req.file();
|
|
44
|
+
const fileId = await storage.store(upload.filename, upload.file, {
|
|
45
|
+
contentType: upload.mimetype
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
#### `storage.url(fileName, options?)`
|
|
50
|
+
|
|
51
|
+
Returns a URL the clients download the file from directly, i.e. a signed URL of a cloud storage valid for
|
|
52
|
+
`options.expiresIn` milliseconds, or `null` (the default, and the `local` storage) to stream the file through the
|
|
53
|
+
server. The files route redirects (`302`) to the URL when there is one.
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
#### `storage.stream(fileName, start, end?)`
|
|
58
|
+
|
|
59
|
+
Returns a `ContentStream` for the stored file, or `null` if the file does not exist. Supports range requests.
|
|
60
|
+
|
|
61
|
+
| Parameter | Type | Description |
|
|
62
|
+
| ---------- | -------- | ------------------------------------------ |
|
|
63
|
+
| `fileName` | `string` | File ID returned by `store` |
|
|
64
|
+
| `start` | `number` | Byte offset to start reading from |
|
|
65
|
+
| `end` | `number` | Byte offset to stop reading at (inclusive) |
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
type ContentStream = {
|
|
69
|
+
stream: Readable;
|
|
70
|
+
size: number; // total file size in bytes
|
|
71
|
+
};
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
**Full file download:**
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
const result = await storage.stream('avatar-a3f8bc12.png', 0);
|
|
78
|
+
if (!result) throw new Error('File not found');
|
|
79
|
+
|
|
80
|
+
reply.header('Content-Length', result.size);
|
|
81
|
+
reply.send(result.stream);
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
**Range request (e.g., video seeking):**
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
const { start, end } = parseRangeHeader(req.headers.range, fileSize);
|
|
88
|
+
const result = await storage.stream(fileId, start, end);
|
|
89
|
+
|
|
90
|
+
reply
|
|
91
|
+
.status(206)
|
|
92
|
+
.header('Content-Range', `bytes ${start}-${end}/${fileSize}`)
|
|
93
|
+
.send(result.stream);
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
#### `storage.exists(fileName)`
|
|
99
|
+
|
|
100
|
+
Returns `true` if the file exists in storage.
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
if (await storage.exists('avatar-a3f8bc12.png')) {
|
|
104
|
+
// safe to stream
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
#### `storage.delete(fileName)`
|
|
111
|
+
|
|
112
|
+
Deletes the stored file. Returns `true` if the file existed and was removed.
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
await storage.delete('avatar-a3f8bc12.png');
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
#### `storage.checkHealth()`
|
|
121
|
+
|
|
122
|
+
Verifies that the storage directory is readable and writable. Returns a `HealthCheckResult`.
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## File name pattern
|
|
127
|
+
|
|
128
|
+
Stored files are renamed according to `STORAGE_NAME_PATTERN`. The default pattern is `{name}-{hash}.{extension}`, which
|
|
129
|
+
produces collision-resistant names while preserving the original extension.
|
|
130
|
+
|
|
131
|
+
Available placeholders:
|
|
132
|
+
|
|
133
|
+
| Placeholder | Resolved to |
|
|
134
|
+
| ------------- | --------------------------- |
|
|
135
|
+
| `{name}` | Base name without extension |
|
|
136
|
+
| `{hash}` | Short content hash |
|
|
137
|
+
| `{extension}` | Original file extension |
|
|
138
|
+
|
|
139
|
+
Example: storing `photo.jpg` produces `photo-c7d3a1f2.jpg`.
|
|
140
|
+
|
|
141
|
+
Only the pattern itself may contain directory separators (e.g. `photos/{resourceId}/{name}.{extension}`). Every value
|
|
142
|
+
substituted into it — including the uploaded file name — is reduced to a single path segment, so an upload can never
|
|
143
|
+
introduce a subdirectory, a `..` traversal or a hidden file.
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## Serving the files
|
|
148
|
+
|
|
149
|
+
The file routes (`GET /files/public/*` and `/files/protected/*`) answer the stored type, which is the one the upload
|
|
150
|
+
declared, inline, so every file but a PDF is served with a sandboxing content security policy (`default-src 'none'`,
|
|
151
|
+
`sandbox`): an HTML page or an SVG image opened directly runs no script on the origin of the API. The file name is
|
|
152
|
+
sent as RFC 6266 `filename` and, outside ASCII, `filename*`.
|
|
153
|
+
|
|
154
|
+
## Reserved paths
|
|
155
|
+
|
|
156
|
+
`STORAGE_RESERVED_PATHS` (default `['__keys__']`, protecting the default JWT key location) lists paths inside
|
|
157
|
+
`STORAGE_PATH` that files can never use. An entry is a directory (blocking everything inside it) or a full file name,
|
|
158
|
+
relative to the storage root, and whole segments are matched case-insensitively.
|
|
159
|
+
|
|
160
|
+
Configured `namePattern`s are validated on startup and abort the start; file paths resolved at upload, stream, or delete
|
|
161
|
+
time are rejected with a `400` error.
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
## Configuration
|
|
166
|
+
|
|
167
|
+
| Key | Type | Default | Description |
|
|
168
|
+
| ---------------------------- | ---------- | ----------------------------- | -------------------------------------------------------------------------------------------- |
|
|
169
|
+
| `STORAGE_PATH` | `string` | `'./storage'` | Root directory where files are stored |
|
|
170
|
+
| `STORAGE_RESERVED_PATHS` | `string[]` | `['__keys__']` | Paths inside the storage root that files cannot use |
|
|
171
|
+
| `STORAGE_NAME_PATTERN` | `string` | `'{name}-{hash}.{extension}'` | Template for deriving the stored file name |
|
|
172
|
+
| `STORAGE_CACHE_TTL` | duration | `86400000` | Cache TTL for storage responses, milliseconds or a duration string (24h) |
|
|
173
|
+
| `STORAGE_FILES_ROUTE_PREFIX` | `string` | `/files` | URL prefix for file access routes. |
|
|
174
|
+
| `STORAGE_PROVIDER` | `string` | `'auto'` | `auto` (`local` unless another storage driver is enabled), `local`, `none`, or a module path |
|
|
175
|
+
| `IMAGE_PROVIDER` | `string` | `'auto'` | `auto` (`sharp` with `@appweaver/sharp`, otherwise none), `sharp`, `none`, or a module path |
|
|
176
|
+
|
|
177
|
+
**`appweaver.json` example:**
|
|
178
|
+
|
|
179
|
+
```json
|
|
180
|
+
{
|
|
181
|
+
"config": {
|
|
182
|
+
"storage": {
|
|
183
|
+
"path": "./uploads",
|
|
184
|
+
"reservedPaths": ["__keys__"],
|
|
185
|
+
"namePattern": "{name}-{hash}.{extension}"
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## Real-world example
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
import { inject } from '@appweaver/core';
|
|
197
|
+
import { Storage } from '@appweaver/common';
|
|
198
|
+
|
|
199
|
+
export class AvatarService {
|
|
200
|
+
private readonly _storage = inject(Storage);
|
|
201
|
+
|
|
202
|
+
async upload(
|
|
203
|
+
userId: number,
|
|
204
|
+
stream: Readable,
|
|
205
|
+
originalName: string
|
|
206
|
+
): Promise<string> {
|
|
207
|
+
const fileId = await this._storage.store(originalName, stream);
|
|
208
|
+
if (!fileId) throw new Error('Upload failed');
|
|
209
|
+
|
|
210
|
+
await saveAvatarRecord(userId, fileId);
|
|
211
|
+
return fileId;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async download(fileId: string): Promise<{ stream: Readable; size: number }> {
|
|
215
|
+
const result = await this._storage.stream(fileId, 0);
|
|
216
|
+
if (!result) throw new Error('File not found');
|
|
217
|
+
return result;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async remove(fileId: string): Promise<void> {
|
|
221
|
+
await this._storage.delete(fileId);
|
|
222
|
+
await deleteAvatarRecord(fileId);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
---
|
|
228
|
+
|
|
229
|
+
## FileService usage
|
|
230
|
+
|
|
231
|
+
The `FileService` provides higher-level file management specifically for **Resource Models**. Unlike the raw `Storage`
|
|
232
|
+
module, it automatically manages the database records (`File` entries) and enforces security policies defined on your
|
|
233
|
+
models. It is defined with a database and a storage. The `File` model, and the files routes, exist only when a model
|
|
234
|
+
declares `files`.
|
|
235
|
+
|
|
236
|
+
### Image processing
|
|
237
|
+
|
|
238
|
+
The `image` options of a file field (dimensions, fit, quality) are applied by the `ImageProcessor` contract of
|
|
239
|
+
`@appweaver/common`, `supports(mimeType)` and `process(stream, mimeType, config?)`. Its `sharp` driver
|
|
240
|
+
(`SharpImageProcessor` of `@appweaver/sharp`, installed by the `data` module of a scaffolded project) is selected when
|
|
241
|
+
the package is installed. Without a processor (`IMAGE_PROVIDER=none`, or no `@appweaver/sharp`), the images are stored
|
|
242
|
+
as they are uploaded, and the application warns at startup naming the file fields whose `image` options are not applied.
|
|
243
|
+
|
|
244
|
+
### Injecting FileService
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
import { inject } from '@appweaver/core';
|
|
248
|
+
import { FileService } from '@appweaver/data';
|
|
249
|
+
|
|
250
|
+
const fileService = inject(FileService);
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
### Saving a file
|
|
254
|
+
|
|
255
|
+
When saving a file via `FileService`, you must provide the multipart data, the resource instance it belongs to, and its
|
|
256
|
+
`ResourceClient`.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
import { inject, injectService } from '@appweaver/core';
|
|
260
|
+
import { FileService } from '@appweaver/data';
|
|
261
|
+
|
|
262
|
+
export class PostService {
|
|
263
|
+
private readonly _fileService = inject(FileService);
|
|
264
|
+
private readonly _postService = injectService('Post');
|
|
265
|
+
|
|
266
|
+
async uploadImage(postId: number, data: MultipartFile) {
|
|
267
|
+
const post = await this._postService.find(postId);
|
|
268
|
+
|
|
269
|
+
// saveFile stores the file in Storage AND creates a File record in the DB
|
|
270
|
+
// linked to the file field named by the multipart field of the 'post' resource.
|
|
271
|
+
const file = await this._fileService.saveFile(
|
|
272
|
+
data,
|
|
273
|
+
post,
|
|
274
|
+
this._postService.client
|
|
275
|
+
);
|
|
276
|
+
|
|
277
|
+
return file;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Saving an in-memory file
|
|
283
|
+
|
|
284
|
+
`saveBuffer()` stores a file that did not arrive as a multipart upload — a downloaded avatar, a generated report, a
|
|
285
|
+
thumbnail. It behaves exactly like `saveFile()` (media type check, size limit, name pattern, image processing,
|
|
286
|
+
checksum, `File` record), except the content comes from a buffer and the target file field is named explicitly:
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
import { inject, injectService } from '@appweaver/core';
|
|
290
|
+
import { FileService } from '@appweaver/data';
|
|
291
|
+
|
|
292
|
+
const users = injectService('User');
|
|
293
|
+
const user = await users.find(userId);
|
|
294
|
+
|
|
295
|
+
const file = await inject(FileService).saveBuffer(
|
|
296
|
+
'avatar', // the file field of the User model
|
|
297
|
+
{ name: 'avatar.png', mimeType: 'image/png', data: buffer },
|
|
298
|
+
user,
|
|
299
|
+
users.client
|
|
300
|
+
);
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
The optional `size` (defaults to the buffer length) is what the size limit is checked against, and `encoding` defaults
|
|
304
|
+
to `7bit`. The owning resource must already exist — to attach files while a user is registering, use the
|
|
305
|
+
[`registrationFiles`](./security.md) callback of `createAuthService`.
|
|
306
|
+
|
|
307
|
+
### File integrity (checksum)
|
|
308
|
+
|
|
309
|
+
When a file is uploaded through `FileService.saveFile()` (or the resource file upload routes), a **SHA-256 checksum**
|
|
310
|
+
(hex-encoded) of the stored content is calculated during the upload and persisted on the `File` record in the
|
|
311
|
+
`checksum` field. The checksum is calculated over the exact bytes written to storage (i.e., after any configured image
|
|
312
|
+
processing), so it can be used at any later point to verify that the file on disk has not been modified or corrupted.
|
|
313
|
+
|
|
314
|
+
The checksum is included in file API responses, so clients can verify downloaded content against it.
|
|
315
|
+
|
|
316
|
+
To verify a file's integrity, recalculate the checksum with the `makeHash` utility from `@appweaver/common` and compare
|
|
317
|
+
it with the stored value:
|
|
318
|
+
|
|
319
|
+
```ts
|
|
320
|
+
import { createReadStream } from 'node:fs';
|
|
321
|
+
import { makeHash } from '@appweaver/common';
|
|
322
|
+
|
|
323
|
+
// From a readable stream (no memory buffering, works for large files) — returns a promise
|
|
324
|
+
const checksum = await makeHash(createReadStream('/path/to/stored/file'));
|
|
325
|
+
|
|
326
|
+
// Or from a Buffer / string — returns the hash synchronously
|
|
327
|
+
// const checksum = makeHash(downloadedBuffer);
|
|
328
|
+
|
|
329
|
+
if (checksum !== file.checksum) {
|
|
330
|
+
throw new Error(`File ${file.name} has been modified or corrupted`);
|
|
331
|
+
}
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
Stored file checksums always use the defaults: **`sha256` + `hex`**.
|
|
335
|
+
|
|
336
|
+
### Streaming a file
|
|
337
|
+
|
|
338
|
+
`FileService.stream()` handles authorization checks (public, private, or protected) and range-based requests
|
|
339
|
+
automatically. `FileService.download()` authorizes the same way and returns the `{ url, fileName, mimeType }` of the
|
|
340
|
+
storage URL when `storage.url()` gives one, otherwise the stream, which the files route answers with a `302` redirect
|
|
341
|
+
or the content.
|
|
342
|
+
|
|
343
|
+
```ts
|
|
344
|
+
// Streams a file while checking if the current user has access
|
|
345
|
+
const fileStream = await fileService.stream(
|
|
346
|
+
'photo-c7d3a1f2.jpg',
|
|
347
|
+
req.headers.range
|
|
348
|
+
);
|
|
349
|
+
|
|
350
|
+
reply
|
|
351
|
+
.status(fileStream.start > 0 ? 206 : 200)
|
|
352
|
+
.header('Content-Type', fileStream.mimeType)
|
|
353
|
+
.header(
|
|
354
|
+
'Content-Disposition',
|
|
355
|
+
`attachment; filename="${fileStream.fileName}"`
|
|
356
|
+
)
|
|
357
|
+
.send(fileStream.content.stream);
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
### Deleting a file
|
|
361
|
+
|
|
362
|
+
Deleting a file via `FileService` removes it from both the storage backend and the database.
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
await fileService.deleteFile(
|
|
366
|
+
'photo-c7d3a1f2.jpg',
|
|
367
|
+
'image', // resource field name
|
|
368
|
+
post, // resource instance
|
|
369
|
+
postClient // ResourceClient
|
|
370
|
+
);
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
### Deleting all files on resource deletion
|
|
374
|
+
|
|
375
|
+
When a resource is deleted, its stored files are cleaned up automatically, as configured per file field:
|
|
376
|
+
|
|
377
|
+
| Option | Applies to | Default |
|
|
378
|
+
| ----------------------- | -------------------------------------------- | ---------- |
|
|
379
|
+
| `onResourceDeleted` | A resource removed from the database | `'delete'` |
|
|
380
|
+
| `onResourceSoftDeleted` | A soft deleted resource (model `softDelete`) | `'keep'` |
|
|
381
|
+
|
|
382
|
+
Both options behave the same way:
|
|
383
|
+
|
|
384
|
+
- `'delete'` removes the file from the storage and its `File` row from the database.
|
|
385
|
+
- `'keep'` retains the file in the storage and its `File` row in the database, e.g. for audit, but never serves it
|
|
386
|
+
again: the row is soft deleted with the same `deletedAt` and `deletedById` values as its resource, and downloads
|
|
387
|
+
respond with 404 whatever the file access type is.
|
|
388
|
+
|
|
389
|
+
The resource service `delete` method removes them once the delete commits, whether it is called by the delete route or
|
|
390
|
+
directly from code, together with the files of every record deleted with it through an `onDelete: 'cascade'` relation.
|
|
391
|
+
The same happens to the orphans an `update` deletes through a relation with `orphanRemoval: true`.
|
|
392
|
+
|
|
393
|
+
The kept files are marked in the same transaction as the delete, while the removed ones leave the storage once it
|
|
394
|
+
commits. A model with `softDelete` enabled keeps the files of its deleted records by default, so a manual restore loses
|
|
395
|
+
nothing; set `onResourceSoftDeleted: 'delete'` on a field to remove its files on a soft delete too.
|
|
396
|
+
|
|
397
|
+
The framework never removes kept files by itself. Purging them after a retention period is up to the application, e.g.
|
|
398
|
+
with a scheduled job removing the `File` rows with an old `deletedAt` and their stored files.
|
|
399
|
+
|
|
400
|
+
```ts
|
|
401
|
+
const config = {
|
|
402
|
+
files: {
|
|
403
|
+
coverImage: {
|
|
404
|
+
mimeType: 'image/*',
|
|
405
|
+
onResourceDeleted: 'delete' // default: files removed when resource is deleted
|
|
406
|
+
},
|
|
407
|
+
documents: {
|
|
408
|
+
array: true,
|
|
409
|
+
onResourceDeleted: 'keep' // opt out: files are retained, but no longer served
|
|
410
|
+
},
|
|
411
|
+
idScan: {
|
|
412
|
+
onResourceSoftDeleted: 'delete' // also removed when the resource is soft deleted
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
You can also call `deleteResourceFiles` manually if needed, or `deleteResourcesFiles` for many records of one model:
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
await fileService.deleteResourceFiles('Post', postId);
|
|
422
|
+
await fileService.deleteResourcesFiles('Post', [firstId, secondId]);
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
### File versions
|
|
426
|
+
|
|
427
|
+
With `storage.versions.enabled` (off by default, see the `STORAGE_VERSIONS_*` keys of
|
|
428
|
+
[configuration.md](./configuration.md)), uploading a file again keeps the replaced file as a previous version instead of
|
|
429
|
+
deleting it. Each version is a `File` row and a stored object of its own: `version` numbers them from 1, `supersededAt`
|
|
430
|
+
is set on the previous ones, and `lineageId` refers every later version to the first one. The current version is always
|
|
431
|
+
the newest one, the one linked to the resource.
|
|
432
|
+
|
|
433
|
+
```ts
|
|
434
|
+
const config = {
|
|
435
|
+
files: {
|
|
436
|
+
contract: { mimeType: 'application/pdf' }, // the config: 10 versions, kept forever
|
|
437
|
+
gallery: { array: true, versions: { maxCount: 3, maxAge: '30d' } },
|
|
438
|
+
avatar: { versions: false } // replaced and deleted as without versions
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
- **Upload**: a single file field always creates a new version. An array field creates one only for a file named by a
|
|
444
|
+
`<field>:replace` text part sent before the file (`{ file, replace }` in `uploadFiles` of the client), any other
|
|
445
|
+
file being a new file of its own. A replace naming no current file of the field fails with
|
|
446
|
+
`FILE_REPLACE_TARGET_INVALID`, and with `FILE_VERSIONING_DISABLED` on a field without versions. A replace does not
|
|
447
|
+
count against `maxCount` of an array field. A failed upload restores the files it replaced.
|
|
448
|
+
|
|
449
|
+
```
|
|
450
|
+
--boundary
|
|
451
|
+
Content-Disposition: form-data; name="gallery:replace"
|
|
452
|
+
|
|
453
|
+
gallery/a-1f2e.png
|
|
454
|
+
--boundary
|
|
455
|
+
Content-Disposition: form-data; name="gallery"; filename="a.png"
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
- **Download**: a previous version is served only by the name of the current file and its number,
|
|
459
|
+
`GET /files/public/<current name>?version=2`. The name of a previous version answers `FILE_NOT_FOUND`, so an old URL
|
|
460
|
+
stops working once its file is replaced, as without versions. The file policy applies to every version. A version
|
|
461
|
+
that does not exist answers `FILE_VERSION_NOT_FOUND`, and a version of a field without versions
|
|
462
|
+
`FILE_VERSIONING_DISABLED`.
|
|
463
|
+
- **List**: `GET /<resource>/:id/file-versions?name=<current name>` lists the versions newest first, the `url` of a
|
|
464
|
+
previous version being the URL of the current file with its `version`.
|
|
465
|
+
- **Delete a version**: `POST /<resource>/:id/delete-file-versions` with
|
|
466
|
+
`{ "<field>": { "name": "<current name>", "version": 2 } }` (or a list of them). Deleting the current version
|
|
467
|
+
(`"latest"`, or its number) makes the previous version current again, linked to the resource, or deletes the file
|
|
468
|
+
without one. The route inherits the config of `fileDelete`, and runs the `canDelete` of the file policy on the version.
|
|
469
|
+
- **Delete the file**: `delete-files`, `deleteFile` and the deletion of the resource delete the file with all its
|
|
470
|
+
versions.
|
|
471
|
+
- **Retention**: `maxCount` (default `10`, the current version included, `0` for no limit) is applied after every
|
|
472
|
+
upload, and `maxAge` (a duration since the version was replaced, unlimited by default) hides the older versions and
|
|
473
|
+
deletes them after an upload and by the `fileVersionsPrune` maintenance job, every hour by default, in batches
|
|
474
|
+
(`FileService.pruneExpiredVersions`, see the [maintenance jobs](./modules.md#maintenance-jobs)).
|
|
475
|
+
|
|
476
|
+
The resource file routes (`/:id/files`, `delete-files`, `file-versions`, `delete-file-versions`) are registered only
|
|
477
|
+
when the `actions` of `createRoutes` list them, or the `files` group (`actions: ['crud', 'files']`), never by `crud`
|
|
478
|
+
alone (see [resources.md](./resources.md#file-and-series-routes)).
|
|
479
|
+
|
|
480
|
+
Without `storage.versions.enabled` the routes listing and deleting the versions are not registered, the `version` query
|
|
481
|
+
parameter is rejected with `FILE_VERSIONING_DISABLED`, and replacing a file deletes it as before, with any version it
|
|
482
|
+
kept. The columns stay in the database.
|
|
483
|
+
|
|
484
|
+
```ts
|
|
485
|
+
const current = await fileService.findByName('gallery/a-9c8d.png');
|
|
486
|
+
const previous = await fileService.findVersion(current, 2);
|
|
487
|
+
const versions = await fileService.listVersions(current.name, post, postClient);
|
|
488
|
+
await fileService.saveBuffer('gallery', buffer, post, postClient, current.name); // a new version of the file
|
|
489
|
+
await fileService.deleteVersions(
|
|
490
|
+
{ gallery: { name: current.name, version: 'latest' } },
|
|
491
|
+
post,
|
|
492
|
+
postClient
|
|
493
|
+
);
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
### Owning resource reference
|
|
497
|
+
|
|
498
|
+
The `File` model records its owner through the `resourceName`, `resourceField` and `resourceId` columns. `resourceId`
|
|
499
|
+
is a text column holding the owning record ID, so files attach to models with either an integer or a string primary
|
|
500
|
+
key, and `deleteResourceFiles` accepts an ID of either type.
|