mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 08:00:06 +00:00
refactor(places): spool place-image and collection uploads through storage
This commit is contained in:
@@ -18,11 +18,8 @@ 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 type { Request } from 'express';
|
||||
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 { CollectionsService } from './collections.service';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
@@ -30,7 +27,8 @@ import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { PLACE_IMAGE_UPLOAD } from '../common/place-image-upload';
|
||||
import { PLACE_IMAGE_FILE_FILTER } from '../common/place-image-upload';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { placeImageUrl } from '../places/place-image';
|
||||
import {
|
||||
CollectionCreateDto,
|
||||
@@ -56,23 +54,16 @@ import {
|
||||
} from './collections.dto';
|
||||
import { PlaceRatingDto } from '../places/places.dto';
|
||||
|
||||
const MAX_COVER_SIZE = 20 * 1024 * 1024;
|
||||
const coversDir = path.join(__dirname, '../../../uploads/covers');
|
||||
const COVER_UPLOAD = {
|
||||
storage: diskStorage({
|
||||
destination: (_req, _file, cb) => {
|
||||
if (!fs.existsSync(coversDir)) fs.mkdirSync(coversDir, { recursive: true });
|
||||
cb(null, coversDir);
|
||||
},
|
||||
filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`),
|
||||
}),
|
||||
limits: { fileSize: MAX_COVER_SIZE },
|
||||
fileFilter: (_req: Request, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
|
||||
if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowed.includes(ext)) cb(null, true);
|
||||
else cb(new Error('Only jpg, png, gif, webp images allowed'), false);
|
||||
},
|
||||
export const MAX_COVER_SIZE = 20 * 1024 * 1024;
|
||||
// Duplicated on purpose from trips.controller.ts (historical parity — no
|
||||
// drive-by consolidation). Quirk preserved: a plain Error without statusCode
|
||||
// maps to 500, not 400. Passed inline on the cover route; the storage engine
|
||||
// comes from collections.module.ts's storage-upload factory options.
|
||||
const COVER_FILE_FILTER: Options['fileFilter'] = (_req, file, cb) => {
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
|
||||
if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowed.includes(ext)) cb(null, true);
|
||||
else cb(new Error('Only jpg, png, gif, webp images allowed'));
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -89,7 +80,7 @@ const COVER_UPLOAD = {
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
|
||||
export class CollectionsController {
|
||||
constructor(private readonly collections: CollectionsService, private readonly env: RuntimeEnvService) {}
|
||||
constructor(private readonly collections: CollectionsService, private readonly env: RuntimeEnvService, private readonly storage: StorageService) {}
|
||||
|
||||
// ── Lists ─────────────────────────────────────────────────────────────────
|
||||
@Get()
|
||||
@@ -184,8 +175,8 @@ export class CollectionsController {
|
||||
|
||||
@Post('places/:pid/image')
|
||||
@HttpCode(200)
|
||||
@UseInterceptors(FileInterceptor('image', PLACE_IMAGE_UPLOAD))
|
||||
uploadPlaceImage(
|
||||
@UseInterceptors(FileInterceptor('image', { fileFilter: PLACE_IMAGE_FILE_FILTER }))
|
||||
async uploadPlaceImage(
|
||||
@CurrentUser() user: User,
|
||||
@Param('pid') pid: string,
|
||||
@UploadedFile() file: Express.Multer.File | undefined,
|
||||
@@ -195,6 +186,9 @@ export class CollectionsController {
|
||||
throw new HttpException(DEMO_WRITE_ERROR, 403);
|
||||
}
|
||||
if (!file) throw new HttpException({ error: 'No image uploaded' }, 400);
|
||||
// Commit the spooled upload to its final storage location (atomic
|
||||
// same-volume rename) before the DB row references the final path.
|
||||
await this.storage.put('places', file.filename, { tmpPath: file.path });
|
||||
return this.collections.setPlaceImage(user.id, Number(pid), placeImageUrl(file.filename), socketId);
|
||||
}
|
||||
|
||||
@@ -360,12 +354,15 @@ export class CollectionsController {
|
||||
}
|
||||
|
||||
@Post(':id/cover')
|
||||
@UseInterceptors(FileInterceptor('cover', COVER_UPLOAD))
|
||||
uploadCover(@CurrentUser() user: User, @Param('id') id: string, @UploadedFile() file: Express.Multer.File | undefined, @Headers('x-socket-id') socketId?: string) {
|
||||
@UseInterceptors(FileInterceptor('cover', { fileFilter: COVER_FILE_FILTER }))
|
||||
async uploadCover(@CurrentUser() user: User, @Param('id') id: string, @UploadedFile() file: Express.Multer.File | undefined, @Headers('x-socket-id') socketId?: string) {
|
||||
if (isDemoWriteBlocked(this.env, user.email)) {
|
||||
throw new HttpException(DEMO_WRITE_ERROR, 403);
|
||||
}
|
||||
if (!file) throw new HttpException({ error: 'No image uploaded' }, 400);
|
||||
// Commit the spooled upload to its final storage location (atomic
|
||||
// same-volume rename) before the DB row references the final path.
|
||||
await this.storage.put('covers', file.filename, { tmpPath: file.path });
|
||||
const coverUrl = `/uploads/covers/${file.filename}`;
|
||||
return this.collections.setCollectionCover(user.id, Number(id), coverUrl, socketId);
|
||||
}
|
||||
|
||||
@@ -9,12 +9,33 @@ import { AddonsModule } from '../addons/addons.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { MulterModule } from '@nestjs/platform-express';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { buildStorageUploadOptions } from '../storage/storage-upload.factory';
|
||||
import { MAX_COVER_SIZE } from './collections.controller';
|
||||
|
||||
/** Collections domain (saved-places library). Registered in AppModule.
|
||||
* Exports CollectionsService for in-container consumers (PluginsModule's
|
||||
* RPC host deps factory). */
|
||||
@Module({
|
||||
imports: [NotificationsModule, AddonsModule, PermissionsModule, AuthModule, AppConfigModule, PluginGuardsModule],
|
||||
imports: [
|
||||
// Two upload routes, two categories: the per-file resolver routes each part
|
||||
// to the right spool. Fieldname routing is exact — FileInterceptor('cover')/
|
||||
// FileInterceptor('image') reject any other part with LIMIT_UNEXPECTED_FILE
|
||||
// before the storage callbacks run. Both routes pass their fileFilter
|
||||
// inline (cover keeps its plain-Error 500 quirk; image its statusCode 400).
|
||||
MulterModule.registerAsync({
|
||||
imports: [StorageModule],
|
||||
inject: [StorageService],
|
||||
useFactory: (storage: StorageService) =>
|
||||
buildStorageUploadOptions(storage, {
|
||||
category: (_req, file) => (file.fieldname === 'image' ? 'places' : 'covers'),
|
||||
maxSize: MAX_COVER_SIZE, // same 20 MB cap for covers and place images
|
||||
}),
|
||||
}),
|
||||
StorageModule,
|
||||
NotificationsModule, AddonsModule, PermissionsModule, AuthModule, AppConfigModule, PluginGuardsModule],
|
||||
controllers: [CollectionsController],
|
||||
providers: [CollectionsService, CollectionsMcp, CollectionsRpc],
|
||||
exports: [CollectionsService],
|
||||
|
||||
@@ -1,38 +1,24 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { diskStorage } from 'multer';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { Request } from 'express';
|
||||
import { PLACE_IMAGES_DIR } from '../places/place-image';
|
||||
import type { Options } from 'multer';
|
||||
|
||||
const MAX_PLACE_IMAGE_SIZE = 20 * 1024 * 1024; // 20 MB — same cap as covers.
|
||||
export const MAX_PLACE_IMAGE_SIZE = 20 * 1024 * 1024; // 20 MB — same cap as covers.
|
||||
|
||||
/**
|
||||
* Multer config for the custom place-image upload (#1136). Mirrors the collection
|
||||
* COVER_UPLOAD: server-chosen UUID filename, image-only filter, written to the
|
||||
* dedicated uploads/places dir. Shared by the trip-place and collection-place
|
||||
* upload endpoints.
|
||||
* fileFilter for the custom place-image upload (#1136), shared by the
|
||||
* trip-place and collection-place upload endpoints (passed inline on each
|
||||
* route; the storage engine — spool destination + UUID filename — comes from
|
||||
* the owning module's storage-upload factory options).
|
||||
*/
|
||||
export const PLACE_IMAGE_UPLOAD = {
|
||||
storage: diskStorage({
|
||||
destination: (_req, _file, cb) => {
|
||||
if (!fs.existsSync(PLACE_IMAGES_DIR)) fs.mkdirSync(PLACE_IMAGES_DIR, { recursive: true });
|
||||
cb(null, PLACE_IMAGES_DIR);
|
||||
},
|
||||
filename: (_req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`),
|
||||
}),
|
||||
limits: { fileSize: MAX_PLACE_IMAGE_SIZE },
|
||||
fileFilter: (_req: Request, file: Express.Multer.File, cb: (err: Error | null, accept: boolean) => void) => {
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
|
||||
if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowed.includes(ext)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
// Carry statusCode so TrekExceptionFilter maps the rejection to a 400 rather
|
||||
// than a 500 (same contract as the avatar upload's fileFilter).
|
||||
const err: Error & { statusCode?: number } = new Error('Only jpg, png, gif, webp images allowed');
|
||||
err.statusCode = 400;
|
||||
cb(err, false);
|
||||
}
|
||||
},
|
||||
export const PLACE_IMAGE_FILE_FILTER: Options['fileFilter'] = (_req, file, cb) => {
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
const allowed = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
|
||||
if (file.mimetype.startsWith('image/') && !file.mimetype.includes('svg') && allowed.includes(ext)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
// Carry statusCode so TrekExceptionFilter maps the rejection to a 400 rather
|
||||
// than a 500 (same contract as the avatar upload's fileFilter).
|
||||
const err: Error & { statusCode?: number } = new Error('Only jpg, png, gif, webp images allowed');
|
||||
err.statusCode = 400;
|
||||
cb(err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -27,7 +27,8 @@ import { isUpdateConflict } from '../common/conflictResult';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { PLACE_IMAGE_UPLOAD } from '../common/place-image-upload';
|
||||
import { PLACE_IMAGE_FILE_FILTER } from '../common/place-image-upload';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { placeImageUrl } from './place-image';
|
||||
import {
|
||||
PlaceBulkDeleteDto,
|
||||
@@ -93,6 +94,7 @@ export class PlacesController {
|
||||
constructor(
|
||||
private readonly places: PlacesService,
|
||||
private readonly env: RuntimeEnvService,
|
||||
private readonly storage: StorageService,
|
||||
) {}
|
||||
|
||||
private requireTrip(tripId: string, user: User) {
|
||||
@@ -340,8 +342,8 @@ export class PlacesController {
|
||||
|
||||
@Post(':id/image')
|
||||
@HttpCode(200)
|
||||
@UseInterceptors(FileInterceptor('image', PLACE_IMAGE_UPLOAD))
|
||||
uploadImage(
|
||||
@UseInterceptors(FileInterceptor('image', { fileFilter: PLACE_IMAGE_FILE_FILTER }))
|
||||
async uploadImage(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('id') id: string,
|
||||
@@ -358,6 +360,9 @@ export class PlacesController {
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'No image uploaded' }, 400);
|
||||
}
|
||||
// Commit the spooled upload to its final storage location (atomic
|
||||
// same-volume rename) before the DB row references the final path.
|
||||
await this.storage.put('places', file.filename, { tmpPath: file.path });
|
||||
// Reuse the existing image_url slot (the top-precedence thumbnail source); the
|
||||
// update path reclaims any previously uploaded file it replaces.
|
||||
const result = this.places.update(tripId, id, { image_url: placeImageUrl(file.filename) } as never);
|
||||
|
||||
@@ -15,6 +15,11 @@ import { QueryHelpersModule } from '../query-helpers/query-helpers.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { MulterModule } from '@nestjs/platform-express';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { buildStorageUploadOptions } from '../storage/storage-upload.factory';
|
||||
import { MAX_PLACE_IMAGE_SIZE } from '../common/place-image-upload';
|
||||
|
||||
/**
|
||||
* Places domain (S8 — Phase 2 trip sub-domain). Depends on L4 Categories + L5
|
||||
@@ -25,7 +30,19 @@ import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
* is no places.bridge.ts: nothing outside the container consumes this domain.
|
||||
*/
|
||||
@Module({
|
||||
imports: [McpSharedModule, PermissionsModule, QueryHelpersModule, MapsModule, AuthModule, AppConfigModule, UnsplashModule, PlacePhotosModule, JourneyDomainModule, RealtimeModule, PluginGuardsModule, AssignmentsDomainModule],
|
||||
imports: [
|
||||
// Module-level options deliberately carry NO fileFilter: the GPX/KML import
|
||||
// route keeps its inline memoryStorage config and would inherit a
|
||||
// module-level filter via the interceptor's shallow merge — the image
|
||||
// route passes PLACE_IMAGE_FILE_FILTER inline instead.
|
||||
MulterModule.registerAsync({
|
||||
imports: [StorageModule],
|
||||
inject: [StorageService],
|
||||
useFactory: (storage: StorageService) =>
|
||||
buildStorageUploadOptions(storage, { category: 'places', maxSize: MAX_PLACE_IMAGE_SIZE }),
|
||||
}),
|
||||
StorageModule,
|
||||
McpSharedModule, PermissionsModule, QueryHelpersModule, MapsModule, AuthModule, AppConfigModule, UnsplashModule, PlacePhotosModule, JourneyDomainModule, RealtimeModule, PluginGuardsModule, AssignmentsDomainModule],
|
||||
controllers: [PlacesController],
|
||||
providers: [PlacesService, PlacesMcp, PlacesRpc],
|
||||
exports: [PlacesService],
|
||||
|
||||
Reference in New Issue
Block a user