From 428d32b18a50a0494fd4b61c7ab6cf119715e735 Mon Sep 17 00:00:00 2001 From: jubnl Date: Sun, 16 Aug 2026 09:25:19 +0200 Subject: [PATCH] refactor(files): spool trip-file uploads through storage --- server/src/nest/files/files.controller.ts | 71 +++++++------- server/src/nest/files/files.module.ts | 21 +++- server/tests/integration/files.test.ts | 46 +++++++++ .../tests/unit/nest/files.controller.test.ts | 96 ++++++++++++------- 4 files changed, 158 insertions(+), 76 deletions(-) diff --git a/server/src/nest/files/files.controller.ts b/server/src/nest/files/files.controller.ts index 38caecebb..34f2c0767 100644 --- a/server/src/nest/files/files.controller.ts +++ b/server/src/nest/files/files.controller.ts @@ -18,55 +18,45 @@ import { import { FileInterceptor } from '@nestjs/platform-express'; import { isDemoWriteBlocked, DEMO_WRITE_ERROR } from '../common/demo-write'; import { RuntimeEnvService } from '../app-config/runtime-env.service'; -import { diskStorage } from 'multer'; +import type { Options } from 'multer'; import path from 'path'; import fs from 'fs'; -import { v4 as uuidv4 } from 'uuid'; import type { User } from '../../types'; +import { StorageService } from '../storage/storage.service'; import { FilesService } from './files.service'; import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import { CurrentUser } from '../auth/current-user.decorator'; import { TripAccessGuard } from '../permissions/trip-access.guard'; import type { TripAccess } from '../database/database.service'; import { Trip } from '../permissions/trip.decorator'; -import { MAX_FILE_SIZE, MAX_VIDEO_SIZE, BLOCKED_EXTENSIONS, filesDir, isVideoExtension } from './files.constants'; +import { MAX_FILE_SIZE, BLOCKED_EXTENSIONS, isVideoExtension } from './files.constants'; import { FileUploadDto, FileUpdateDto, FileLinkDto } from './files.dto'; import { AllowedFileTypesService } from './allowed-file-types.service'; /** - * Trip-file upload options, built from the container. + * Trip-file upload filter, built from the container. * - * A factory rather than a module-scope literal because the fileFilter reads the - * operator's allowed-extension list at request time, and that list lives in the - * database. It used to reach it through files.bridge.ts, which built a second - * FilesService outside the injector; MulterModule.registerAsync gives the - * closure the real one. + * A factory rather than a module-scope literal because it reads the operator's + * allowed-extension list at request time, and that list lives in the database. + * The rest of the multer options come from the storage upload factory + * (buildStorageUploadOptions in files.module.ts); this closure is passed + * through untouched. */ -export function buildFilesUploadOptions(allowedTypes: AllowedFileTypesService) { - return { - storage: diskStorage({ - destination: (_req, _file, cb) => { if (!fs.existsSync(filesDir)) fs.mkdirSync(filesDir, { recursive: true }); cb(null, filesDir); }, - filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`), - }), - // Allow up to the video cap; non-video files are still held to MAX_FILE_SIZE by - // the per-type guard in the upload handler (#823). - limits: { fileSize: MAX_VIDEO_SIZE }, - defParamCharset: 'utf8', // parity with legacy routes/files.ts — preserve non-ASCII original filenames - fileFilter: (_req: unknown, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => { - const ext = path.extname(file.originalname).toLowerCase(); - const reject = () => { - // i18n key — the client resolves it via t() (see translateApiError). - const err: Error & { statusCode?: number } = new Error('files.uploadErrorType'); - err.statusCode = 400; - cb(err, false); - }; - if (BLOCKED_EXTENSIONS.includes(ext) || file.mimetype.includes('svg')) return reject(); - const allowed = allowedTypes.get().split(',').map((e) => e.trim().toLowerCase()); - const fileExt = ext.replace('.', ''); - // Video is accepted as media regardless of the admin doc-types allowlist (#823). - if (allowed.includes(fileExt) || isVideoExtension(fileExt) || (allowed.includes('*') && !BLOCKED_EXTENSIONS.includes(ext))) return cb(null, true); - reject(); - }, +export function filesUploadFileFilter(allowedTypes: AllowedFileTypesService): Options['fileFilter'] { + return (_req, file, cb) => { + const ext = path.extname(file.originalname).toLowerCase(); + const reject = () => { + // i18n key — the client resolves it via t() (see translateApiError). + const err: Error & { statusCode?: number } = new Error('files.uploadErrorType'); + err.statusCode = 400; + cb(err); + }; + if (BLOCKED_EXTENSIONS.includes(ext) || file.mimetype.includes('svg')) return reject(); + const allowed = allowedTypes.get().split(',').map((e) => e.trim().toLowerCase()); + const fileExt = ext.replace('.', ''); + // Video is accepted as media regardless of the admin doc-types allowlist (#823). + if (allowed.includes(fileExt) || isVideoExtension(fileExt) || (allowed.includes('*') && !BLOCKED_EXTENSIONS.includes(ext))) return cb(null, true); + reject(); }; } @@ -97,6 +87,7 @@ export class FilesController { constructor( private readonly files: FilesService, private readonly env: RuntimeEnvService, + private readonly storage: StorageService, ) {} @@ -117,14 +108,14 @@ export class FilesController { @Post() @UseInterceptors(FileInterceptor('file')) - upload( + async upload( @CurrentUser() user: User, @Param('tripId') tripId: string, @UploadedFile() file: Express.Multer.File | undefined, @Body() body: FileUploadDto, @Headers('x-socket-id') socketId?: string, ) { - // multer (diskStorage) has already written the upload by the time we get here, + // multer (diskStorage) has already spooled the upload by the time we get here, // so every rejection below must remove the orphaned bytes — otherwise a 404/403 // leaves up to the 500 MB video cap on disk (#823). const cleanup = () => { if (file?.path) { try { fs.unlinkSync(file.path); } catch { /* best-effort */ } } }; @@ -162,6 +153,14 @@ export class FilesController { cleanup(); throw err; } + // Commit the spooled upload to its final storage location (atomic + // same-volume rename) before anything references the final path. + try { + await this.storage.put('files', file.filename, { tmpPath: file.path }); + } catch (err) { + cleanup(); + throw err; + } const created = this.files.createFile(tripId, file, user.id, { place_id: body.place_id, description: body.description, diff --git a/server/src/nest/files/files.module.ts b/server/src/nest/files/files.module.ts index 1788267c2..0c2a7f7c5 100644 --- a/server/src/nest/files/files.module.ts +++ b/server/src/nest/files/files.module.ts @@ -11,15 +11,28 @@ import { EphemeralTokenModule } from '../auth/ephemeral-token.module'; import { MulterModule } from '@nestjs/platform-express'; import { AllowedFileTypesModule } from './allowed-file-types.module'; import { AllowedFileTypesService } from './allowed-file-types.service'; -import { buildFilesUploadOptions } from './files.controller'; +import { StorageModule } from '../storage/storage.module'; +import { StorageService } from '../storage/storage.service'; +import { buildStorageUploadOptions } from '../storage/storage-upload.factory'; +import { filesUploadFileFilter } from './files.controller'; +import { MAX_VIDEO_SIZE } from './files.constants'; @Module({ imports: [ MulterModule.registerAsync({ - imports: [AllowedFileTypesModule], - inject: [AllowedFileTypesService], - useFactory: (allowedTypes: AllowedFileTypesService) => buildFilesUploadOptions(allowedTypes), + imports: [StorageModule, AllowedFileTypesModule], + inject: [StorageService, AllowedFileTypesService], + useFactory: (storage: StorageService, allowedTypes: AllowedFileTypesService) => + buildStorageUploadOptions(storage, { + category: 'files', + // Allow up to the video cap; non-video files are still held to + // MAX_FILE_SIZE by the per-type guard in the upload handler (#823). + maxSize: MAX_VIDEO_SIZE, + defParamCharset: 'utf8', // parity with legacy routes/files.ts — preserve non-ASCII original filenames + fileFilter: filesUploadFileFilter(allowedTypes), + }), }), + StorageModule, EphemeralTokenModule, PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule], controllers: [FilesController, FilesDownloadController], providers: [FilesService, FilesRpc], diff --git a/server/tests/integration/files.test.ts b/server/tests/integration/files.test.ts index 32733332f..c5bad0781 100644 --- a/server/tests/integration/files.test.ts +++ b/server/tests/integration/files.test.ts @@ -133,6 +133,52 @@ describe('Upload file', () => { } }); + it('FILE-P01 — stored filename is a bare uuid name and the bytes land in uploads/files', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + + const res = await uploadFile(trip.id, user.id, FIXTURE_PDF); + expect(res.status).toBe(201); + expect(res.body.file.filename).toMatch(/^[0-9a-f-]{36}\.pdf$/); + expect(fs.existsSync(path.join(uploadsDir, res.body.file.filename))).toBe(true); + // Nothing left behind in the spool after a successful commit. + const spoolDir = path.join(__dirname, '../../uploads/.tmp'); + if (fs.existsSync(spoolDir)) { + expect(fs.readdirSync(spoolDir)).not.toContain(res.body.file.filename); + } + }); + + it('FILE-P02 — non-video over 50 MB is rejected with no bytes left anywhere', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + + const before = fs.existsSync(uploadsDir) ? fs.readdirSync(uploadsDir) : []; + const res = await request(app) + .post(`/api/trips/${trip.id}/files`) + .set('Cookie', authCookie(user.id)) + .attach('file', Buffer.alloc(51 * 1024 * 1024), { filename: 'big.pdf', contentType: 'application/pdf' }); + expect(res.status).toBe(400); + expect(res.body.error).toBe('File is too large'); + const after = fs.existsSync(uploadsDir) ? fs.readdirSync(uploadsDir) : []; + expect(after).toEqual(before); + const spoolDir = path.join(__dirname, '../../uploads/.tmp'); + if (fs.existsSync(spoolDir)) { + expect(fs.readdirSync(spoolDir).filter((f) => f.endsWith('.pdf'))).toEqual([]); + } + }); + + it('FILE-P03 — non-ASCII original filenames are preserved (defParamCharset utf8)', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + + const res = await request(app) + .post(`/api/trips/${trip.id}/files`) + .set('Cookie', authCookie(user.id)) + .attach('file', Buffer.from('utf8 name test'), { filename: 'résumé.pdf', contentType: 'application/pdf' }); + expect(res.status).toBe(201); + expect(res.body.file.original_name).toBe('résumé.pdf'); + }); + it('FILE-021 — non-member cannot upload file', async () => { const { user: owner } = createUser(testDb); const { user: other } = createUser(testDb); diff --git a/server/tests/unit/nest/files.controller.test.ts b/server/tests/unit/nest/files.controller.test.ts index da0a1abb4..7c3e5e6ea 100644 --- a/server/tests/unit/nest/files.controller.test.ts +++ b/server/tests/unit/nest/files.controller.test.ts @@ -13,6 +13,7 @@ import { FilesDownloadController } from '../../../src/nest/files/files-download. import { PhotosController } from '../../../src/nest/photos/photos.controller'; import type { FilesService } from '../../../src/nest/files/files.service'; import type { PhotosService } from '../../../src/nest/photos/photos.service'; +import type { StorageService } from '../../../src/nest/storage/storage.service'; import { isDemoEmail } from '../../../src/nest/common/demo'; import type { User } from '../../../src/types'; @@ -28,6 +29,13 @@ function fsvc(o: Partial = {}): FilesService { } as unknown as FilesService; } +const storageStub = { put: vi.fn().mockResolvedValue(undefined) } as unknown as StorageService; + +/** Construct the controller with the standard env + storage stubs. */ +function fc(svc: FilesService): FilesController { + return new FilesController(svc, new RuntimeEnvService(), storageStub); +} + function thrown(fn: () => unknown): { status: number; body: unknown } { try { fn(); } catch (err) { expect(err).toBeInstanceOf(HttpException); @@ -37,6 +45,15 @@ function thrown(fn: () => unknown): { status: number; body: unknown } { throw new Error('expected throw'); } +async function rejected(p: Promise): Promise<{ status: number; body: unknown }> { + try { await p; } catch (err) { + expect(err).toBeInstanceOf(HttpException); + const e = err as HttpException; + return { status: e.getStatus(), body: e.getResponse() }; + } + throw new Error('expected reject'); +} + beforeEach(() => vi.clearAllMocks()); afterEach(() => { delete process.env.DEMO_MODE; }); @@ -47,121 +64,128 @@ const trip = { id: 5, user_id: 42 } as never; describe('FilesController (parity with the legacy /api/trips/:tripId/files route)', () => { it('GET / lists with the trash flag', () => { const listFiles = vi.fn().mockReturnValue([{ id: 1 }]); - expect(new FilesController(fsvc({ listFiles } as Partial), new RuntimeEnvService()).list(user, trip, '5', 'true')).toEqual({ files: [{ id: 1 }] }); + expect(fc(fsvc({ listFiles } as Partial)).list(user, trip, '5', 'true')).toEqual({ files: [{ id: 1 }] }); expect(listFiles).toHaveBeenCalledWith('5', true); }); describe('POST / (upload)', () => { - it('404 without trip access — upload keeps its own check so the body is read first', () => { + it('404 without trip access — upload keeps its own check so the body is read first', async () => { // The guard would answer before multer, and a response sent mid-upload destroys // the socket: the caller would see ECONNRESET rather than this 404. const svc = fsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }); - expect(thrown(() => new FilesController(svc, new RuntimeEnvService()).upload(user, '5', undefined, {}))).toEqual({ + expect(await rejected(fc(svc).upload(user, '5', undefined, {}))).toEqual({ status: 404, body: { error: 'Trip not found' }, }); }); const file = { filename: 'a.pdf' } as Express.Multer.File; - it('403 in demo mode for a demo email', () => { + it('403 in demo mode for a demo email', async () => { process.env.DEMO_MODE = 'true'; vi.mocked(isDemoEmail).mockReturnValue(true); - expect(thrown(() => new FilesController(fsvc(), new RuntimeEnvService()).upload(user, '5', file, {}))).toEqual({ status: 403, body: { error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' } }); + expect(await rejected(fc(fsvc()).upload(user, '5', file, {}))).toEqual({ status: 403, body: { error: 'Uploads are disabled in demo mode. Self-host TREK for full functionality.' } }); }); - it('403 without file_upload, 400 without a file, else creates + broadcasts', () => { - expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).upload(user, '5', file, {}))).toEqual({ status: 403, body: { error: 'No permission to upload files' } }); - expect(thrown(() => new FilesController(fsvc(), new RuntimeEnvService()).upload(user, '5', undefined, {}))).toEqual({ status: 400, body: { error: 'No file uploaded' } }); + it('403 without file_upload, 400 without a file, else commits + creates + broadcasts', async () => { + expect(await rejected(fc(fsvc({ can: vi.fn().mockReturnValue(false) })).upload(user, '5', file, {}))).toEqual({ status: 403, body: { error: 'No permission to upload files' } }); + expect(await rejected(fc(fsvc()).upload(user, '5', undefined, {}))).toEqual({ status: 400, body: { error: 'No file uploaded' } }); const createFile = vi.fn().mockReturnValue({ id: 9 }); const broadcast = vi.fn(); const s = fsvc({ createFile, broadcast } as Partial); - expect(new FilesController(s, new RuntimeEnvService()).upload(user, '5', file, { description: 'd' }, 'sock')).toEqual({ file: { id: 9 } }); + expect(await fc(s).upload(user, '5', file, { description: 'd' }, 'sock')).toEqual({ file: { id: 9 } }); + expect(storageStub.put).toHaveBeenCalledWith('files', 'a.pdf', { tmpPath: undefined }); expect(createFile).toHaveBeenCalledWith('5', file, 1, { place_id: undefined, description: 'd', reservation_id: undefined }); expect(broadcast).toHaveBeenCalledWith('5', 'file:created', { file: { id: 9 } }, 'sock'); }); - it('caps non-video by extension and accepts large video; cleans up on rejection (#823)', () => { + it('caps non-video by extension and accepts large video; cleans up on rejection (#823)', async () => { const big = { filename: 'big.pdf', originalname: 'big.pdf', size: 60 * 1024 * 1024, path: '' } as Express.Multer.File; - expect(thrown(() => new FilesController(fsvc(), new RuntimeEnvService()).upload(user, '5', big, {}))).toEqual({ status: 400, body: { error: 'File is too large' } }); + expect(await rejected(fc(fsvc()).upload(user, '5', big, {}))).toEqual({ status: 400, body: { error: 'File is too large' } }); const createFile = vi.fn().mockReturnValue({ id: 9 }); const vid = { filename: 'v.mp4', originalname: 'clip.mp4', size: 200 * 1024 * 1024, path: '' } as Express.Multer.File; - expect(new FilesController(fsvc({ createFile, broadcast: vi.fn() } as Partial), new RuntimeEnvService()).upload(user, '5', vid, {})).toEqual({ file: { id: 9 } }); + expect(await fc(fsvc({ createFile, broadcast: vi.fn() } as Partial)).upload(user, '5', vid, {})).toEqual({ file: { id: 9 } }); // A rejected upload with a real path triggers the unlink cleanup branch // (the file doesn't exist, so the inner best-effort catch swallows it). const withPath = { filename: 'a.pdf', path: '/nonexistent/zzz.pdf' } as Express.Multer.File; - expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).upload(user, '5', withPath, {}))).toEqual({ status: 403, body: { error: 'No permission to upload files' } }); + expect(await rejected(fc(fsvc({ can: vi.fn().mockReturnValue(false) })).upload(user, '5', withPath, {}))).toEqual({ status: 403, body: { error: 'No permission to upload files' } }); + }); + + it('500 with cleanup when the storage commit fails', async () => { + vi.mocked(storageStub.put).mockRejectedValueOnce(new Error('disk full')); + const withPath = { filename: 'a.pdf', path: '/nonexistent/zzz.pdf' } as Express.Multer.File; + await expect(fc(fsvc()).upload(user, '5', withPath, {})).rejects.toThrow('disk full'); }); }); it('PUT /:id 403 without file_edit, 404 unknown, else updates + broadcasts', () => { - expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).update(user, trip, '5', '9', {}))).toEqual({ status: 403, body: { error: 'No permission to edit files' } }); - expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial), new RuntimeEnvService()).update(user, trip, '5', '9', {}))).toEqual({ status: 404, body: { error: 'File not found' } }); + expect(thrown(() => fc(fsvc({ can: vi.fn().mockReturnValue(false) })).update(user, trip, '5', '9', {}))).toEqual({ status: 403, body: { error: 'No permission to edit files' } }); + expect(thrown(() => fc(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial)).update(user, trip, '5', '9', {}))).toEqual({ status: 404, body: { error: 'File not found' } }); const updateFile = vi.fn().mockReturnValue({ id: 9 }); const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9, description: 'x' }), updateFile, broadcast: vi.fn() } as Partial); - expect(new FilesController(s, new RuntimeEnvService()).update(user, trip, '5', '9', { description: 'new' })).toEqual({ file: { id: 9 } }); + expect(fc(s).update(user, trip, '5', '9', { description: 'new' })).toEqual({ file: { id: 9 } }); }); it('PATCH /:id/star 403/404, else toggles', () => { - expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).star(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission' } }); - expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial), new RuntimeEnvService()).star(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); + expect(thrown(() => fc(fsvc({ can: vi.fn().mockReturnValue(false) })).star(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission' } }); + expect(thrown(() => fc(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial)).star(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); const toggleStarred = vi.fn().mockReturnValue({ id: 9, starred: 1 }); const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9, starred: 0 }), toggleStarred, broadcast: vi.fn() } as Partial); - expect(new FilesController(s, new RuntimeEnvService()).star(user, trip, '5', '9')).toEqual({ file: { id: 9, starred: 1 } }); + expect(fc(s).star(user, trip, '5', '9')).toEqual({ file: { id: 9, starred: 1 } }); expect(toggleStarred).toHaveBeenCalledWith('9', 0); }); it('DELETE /:id soft-delete 403/404, else success', () => { - expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).remove(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission to delete files' } }); - expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial), new RuntimeEnvService()).remove(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); + expect(thrown(() => fc(fsvc({ can: vi.fn().mockReturnValue(false) })).remove(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission to delete files' } }); + expect(thrown(() => fc(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial)).remove(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); const softDeleteFile = vi.fn(); const broadcast = vi.fn(); const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9 }), softDeleteFile, broadcast } as Partial); - expect(new FilesController(s, new RuntimeEnvService()).remove(user, trip, '5', '9', 'sock')).toEqual({ success: true }); + expect(fc(s).remove(user, trip, '5', '9', 'sock')).toEqual({ success: true }); expect(broadcast).toHaveBeenCalledWith('5', 'file:deleted', { fileId: 9 }, 'sock'); }); it('POST /:id/restore 404 not in trash, else restores', () => { - expect(thrown(() => new FilesController(fsvc({ getDeletedFile: vi.fn().mockReturnValue(undefined) } as Partial), new RuntimeEnvService()).restore(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found in trash' } }); + expect(thrown(() => fc(fsvc({ getDeletedFile: vi.fn().mockReturnValue(undefined) } as Partial)).restore(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found in trash' } }); const restoreFile = vi.fn().mockReturnValue({ id: 9 }); const s = fsvc({ getDeletedFile: vi.fn().mockReturnValue({ id: 9 }), restoreFile, broadcast: vi.fn() } as Partial); - expect(new FilesController(s, new RuntimeEnvService()).restore(user, trip, '5', '9')).toEqual({ file: { id: 9 } }); + expect(fc(s).restore(user, trip, '5', '9')).toEqual({ file: { id: 9 } }); }); it('DELETE /:id/permanent 404 not in trash, else deletes', async () => { - await expect(new FilesController(fsvc({ getDeletedFile: vi.fn().mockReturnValue(undefined) } as Partial), new RuntimeEnvService()).permanent(user, trip, '5', '9')).rejects.toBeInstanceOf(HttpException); + await expect(fc(fsvc({ getDeletedFile: vi.fn().mockReturnValue(undefined) } as Partial)).permanent(user, trip, '5', '9')).rejects.toBeInstanceOf(HttpException); const permanentDeleteFile = vi.fn().mockResolvedValue(undefined); const s = fsvc({ getDeletedFile: vi.fn().mockReturnValue({ id: 9 }), permanentDeleteFile, broadcast: vi.fn() } as Partial); - expect(await new FilesController(s, new RuntimeEnvService()).permanent(user, trip, '5', '9')).toEqual({ success: true }); + expect(await fc(s).permanent(user, trip, '5', '9')).toEqual({ success: true }); }); it('DELETE /trash/empty 403, else returns the count', async () => { - await expect(new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).emptyTrash(user, trip, '5')).rejects.toBeInstanceOf(HttpException); + await expect(fc(fsvc({ can: vi.fn().mockReturnValue(false) })).emptyTrash(user, trip, '5')).rejects.toBeInstanceOf(HttpException); const s = fsvc({ emptyTrash: vi.fn().mockResolvedValue(3) } as Partial); - expect(await new FilesController(s, new RuntimeEnvService()).emptyTrash(user, trip, '5')).toEqual({ success: true, deleted: 3 }); + expect(await fc(s).emptyTrash(user, trip, '5')).toEqual({ success: true, deleted: 3 }); }); it('POST /:id/link 404 unknown file, else links', () => { - expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial), new RuntimeEnvService()).link(user, trip, '5', '9', {}))).toEqual({ status: 404, body: { error: 'File not found' } }); + expect(thrown(() => fc(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial)).link(user, trip, '5', '9', {}))).toEqual({ status: 404, body: { error: 'File not found' } }); const createFileLink = vi.fn().mockReturnValue([{ id: 1 }]); const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9 }), createFileLink } as Partial); - expect(new FilesController(s, new RuntimeEnvService()).link(user, trip, '5', '9', { reservation_id: 2 })).toEqual({ success: true, links: [{ id: 1 }] }); + expect(fc(s).link(user, trip, '5', '9', { reservation_id: 2 })).toEqual({ success: true, links: [{ id: 1 }] }); }); it('DELETE /:id/link/:linkId removes the link; GET /:id/links lists', () => { const deleteFileLink = vi.fn(); - expect(new FilesController(fsvc({ deleteFileLink } as Partial), new RuntimeEnvService()).unlink(user, trip, '5', '9', '3')).toEqual({ success: true }); + expect(fc(fsvc({ deleteFileLink } as Partial)).unlink(user, trip, '5', '9', '3')).toEqual({ success: true }); expect(deleteFileLink).toHaveBeenCalledWith('3', '9'); const s = fsvc({ getFileLinks: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial); - expect(new FilesController(s, new RuntimeEnvService()).links(user, trip, '5', '9')).toEqual({ links: [{ id: 1 }] }); + expect(fc(s).links(user, trip, '5', '9')).toEqual({ links: [{ id: 1 }] }); }); it('the trash + link routes all reject without file_delete / file_edit', async () => { const denied = () => fsvc({ can: vi.fn().mockReturnValue(false) }); - await expect(new FilesController(denied(), new RuntimeEnvService()).permanent(user, trip, '5', '9')).rejects.toMatchObject({ status: 403 }); - expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).restore(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission' } }); - expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).link(user, trip, '5', '9', {}))).toEqual({ status: 403, body: { error: 'No permission' } }); - expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).unlink(user, trip, '5', '9', '3'))).toEqual({ status: 403, body: { error: 'No permission' } }); + await expect(fc(denied()).permanent(user, trip, '5', '9')).rejects.toMatchObject({ status: 403 }); + expect(thrown(() => fc(denied()).restore(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission' } }); + expect(thrown(() => fc(denied()).link(user, trip, '5', '9', {}))).toEqual({ status: 403, body: { error: 'No permission' } }); + expect(thrown(() => fc(denied()).unlink(user, trip, '5', '9', '3'))).toEqual({ status: 403, body: { error: 'No permission' } }); }); });