Repository navigation
Updated Complete Code for first prodution frontend Connection - #20
Conversation
…I for fast error resolving and Folder Structure Cleaning
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (93)
📝 WalkthroughWalkthroughThe pull request introduces a comprehensive refactoring and feature expansion that modernizes the codebase's HTTP response handling, file upload strategy, AWS S3 integration, and type system architecture. It adds new features for JSON scene uploads, project/story context profiles, and implements consistent response standardization across controllers while migrating Multer to in-memory storage and refactoring S3 interactions to use presigned URLs. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Controller as SceneController
participant Service as SceneService
participant Multer as scenesJSONUpload
participant DB as Database
participant Response as sendSuccess
Client->>Controller: POST /upload-json
Controller->>Multer: validate JSON upload
Multer->>Multer: extract file buffer
Multer->>Controller: pass to next
Controller->>Service: createScenesFromJSON(userId, storyId, scenes)
Service->>Service: withTransaction(session)
Service->>DB: deactivate existing scenes
Service->>DB: insert new scenes with authorType='user'
DB-->>Service: created scenes
Service-->>Controller: scenes array
Controller->>Response: sendSuccess(201, scenes)
Response-->>Client: {message, data: scenes[], status: 201}
sequenceDiagram
participant Client
participant Controller as SceneAssetsController
participant Service as SceneAssetsService
participant S3 as uploadFile
participant DB as Database
participant Response as sendSuccess
Client->>Controller: POST /generate-image
Controller->>Service: generateImageAsset(userId, sceneId)
Service->>DB: validate scene ownership
Service->>S3: uploadFile(buffer, key, contentType)
S3-->>Service: upload result with URL
Service->>DB: create SceneAsset with status='ready'
Service->>DB: update Scene.activeAssetId
Service->>DB: update Scene.status
DB-->>Service: asset object
Service-->>Controller: asset
Controller->>Response: sendSuccess(201, asset)
Response-->>Client: {message, data: asset, status: 201}
sequenceDiagram
participant Client
participant Controller as ProjectController
participant Service as ProjectService
participant ContextSvc as ContextProfileService
participant DB as Database
participant Response as sendSuccess
Client->>Controller: PATCH /:projectId/context-profile
Controller->>Service: updateProjectContextProfile(userId, projectId, payload)
Service->>Service: withTransaction(session)
Service->>DB: load project (validate ownership)
Service->>ContextSvc: create ContextProfile(scope='PROJECT', isDefault=true)
ContextSvc->>DB: insert new context profile
DB-->>ContextSvc: new context
Service->>DB: demote old defaultContextProfileId (isDefault=false)
Service->>DB: update project.defaultContextProfileId
DB-->>Service: updated project
Service-->>Controller: sanitized project
Controller->>Response: sendSuccess(res, project)
Response-->>Client: {message, data: project}
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Pull request overview
This PR standardizes backend API responses for frontend consumption by introducing shared response helpers and explicit “sanitized” response shapes, while also expanding validation, adding JSON upload flows, and integrating S3-based media handling.
Changes:
- Added shared API response envelope helpers (
sendSuccess,sendPaginated) and updated many controllers to use them. - Introduced/expanded response “sanitizers” and centralized app type exports via
@app-types/*. - Added new upload/creation flows (scene JSON upload, avatar/media S3 upload) and updated several schemas/models accordingly.
Reviewed changes
Copilot reviewed 90 out of 94 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| tsconfig.json | Adds path aliases for @shared/* and @app-types/*. |
| src/validation/user.schema.ts | Refactors link URL validation via a shared urlField. |
| src/validation/scenes.schema.ts | Adds schemas/types for uploading scenes via JSON. |
| src/validation/project.schema.ts | Adds schema/type for updating project context profile payload. |
| src/validation/narration.schema.ts | Moves narration constant to shared constants module. |
| src/utils/sanitizers/sanitizeUserResponse.ts | Expands sanitized user shapes and switches to id string. |
| src/utils/sanitizers/sanitizeStoryResponse.ts | Adds story sanitizer returning id-based response. |
| src/utils/sanitizers/sanitizeScenesResponse.ts | Adds scenes sanitizer with optional active asset expansion. |
| src/utils/sanitizers/sanitizeSceneAssetResponse.ts | Adds scene asset sanitizer. |
| src/utils/sanitizers/sanitizeProjectResponse.ts | Adds project sanitizer (list/detail variants). |
| src/utils/sanitizers/sanitizeNarrationResponse.ts | Adds narration sanitizer with active audio asset. |
| src/utils/sanitizers/sanitizeContextProfileResponse.ts | Adds context profile sanitizer. |
| src/utils/sanitizers/sanitizeAudioAssetResponse.ts | Adds audio asset sanitizer. |
| src/utils/sanitizers/index.ts | Adds barrel exports for sanitizer utilities. |
| src/utils/sanitizeProjectResponse.ts | Removes legacy project sanitizer in favor of new sanitizers. |
| src/utils/paginationResponse.ts | Updates Pagination import to @app-types. |
| src/utils/logger.ts | Changes “production vs pretty logging” environment logic. |
| src/utils/getVideoDuration.ts | Minor formatting change in exported function declaration. |
| src/utils/file.ts | Adds temp file cleanup helper (removeTempFile). |
| src/types/index.ts | Adds central type barrel + exports UserReturnType and Plan. |
| src/types/express.d.ts | Fixes imports to .js paths and constants module. |
| src/types/Story.ts | Adds sanitized story response interface. |
| src/types/SceneAsset.ts | Adds sanitized scene asset response interface. |
| src/types/Scene.ts | Adds sanitized scene response interface + scene mode types. |
| src/types/Project.ts | Adds project status and sanitized project response interfaces. |
| src/types/Error.ts | Re-exports ErrorCode type. |
| src/types/ContextProfile.ts | Adds sanitized context profile response interface. |
| src/types/Auth.ts | Adds auth response output types. |
| src/types/Audio.ts | Adds sanitized audio asset response interface. |
| src/shared/response.ts | Adds response envelope + generic object-id stripping sanitizer. |
| src/shared/index.ts | Adds barrel exports for shared response utilities. |
| src/server.ts | Minor startup flow cleanup. |
| src/routes/index.ts | Adds Cache-Control: no-store and updates /health envelope. |
| src/routes/api.ts | Adds audio router and reorders private route middleware usage. |
| src/modules/user/user.service.ts | Uses new user sanitizer; adds S3 avatar upload/delete logic. |
| src/modules/user/user.controller.ts | Migrates responses to sendSuccess and error throwing. |
| src/modules/story/story.service.ts | Switches imports to aliases and adds story context list service. |
| src/modules/story/story.private.routes.ts | Adds route to list story context profiles. |
| src/modules/story/story.controller.ts | Migrates many handlers to shared response helpers. |
| src/modules/scenes/scenes.service.ts | Returns sanitized scenes + adds JSON upload/create flows. |
| src/modules/scenes/scenes.private.routes.ts | Adds routes/middleware for scenes JSON upload (body + file). |
| src/modules/scenes/scenes.controller.ts | Adds controllers for scenes JSON upload + shared response envelope. |
| src/modules/sceneAssets/sceneAssets.service.ts | Adds S3 upload + temp cleanup; updates generation/upload paths. |
| src/modules/sceneAssets/sceneAssets.private.routes.ts | Fixes route handler reference for permanent bulk delete. |
| src/modules/sceneAssets/sceneAssets.controller.ts | Migrates handlers to shared response helpers; adds image generation. |
| src/modules/project/utils/transitionProjectById.ts | Updates sanitizer import path. |
| src/modules/project/rules/projectStatus.ts | Moves project status types to @app-types. |
| src/modules/project/project.service.ts | Adds project context update service + updated imports. |
| src/modules/project/project.routes.ts | Adds route for updating project context profile. |
| src/modules/project/project.controller.ts | Migrates to shared response helpers; adds context update controller. |
| src/modules/narration/narration.service.ts | Adds narration sanitization; changes list API shape and population. |
| src/modules/narration/narration.routes.ts | Adjusts middleware usage for deleted narrations endpoint. |
| src/modules/narration/narration.controller.ts | Migrates to shared response envelope; refactors pagination usage. |
| src/modules/contextProfile/contextProfile.service.ts | Adds sanitization + uses withTransaction. |
| src/modules/contextProfile/contextProfile.controller.ts | Migrates to shared response helper. |
| src/modules/auth/auth.service.ts | Uses aliased constants + returns safe SignOutput user shape. |
| src/modules/auth/auth.controller.ts | Refactors cookie-setting and standardizes response envelopes. |
| src/modules/audio/audio.service.ts | Updates Pagination import path. |
| src/modules/audio/audio.routes.ts | Removes unused schema import and keeps routes aligned. |
| src/modules/audio/audio.controller.ts | Migrates to shared response helpers. |
| src/modules/audio/audio.constants.ts | Re-exports audio constants from global constants module. |
| src/models/User.ts | Changes privacy prefs enum/fields and removes usage subdocument. |
| src/models/Story.ts | Adds contentStatus into story content. |
| src/models/SceneAssets.ts | Adds thumbnailUrl and status to scene assets. |
| src/models/Scene.ts | Adds status to scenes. |
| src/models/Narration.ts | Adds segment source and narration status. |
| src/models/ContextProfile.ts | Adds storyId support and index. |
| src/models/AudioAsset.ts | Adds status to audio assets. |
| src/middleware/security/requireCsrf.ts | Updates constants import and adjusts origin extraction/validation. |
| src/middleware/request/paginationAndSorting.ts | Updates Pagination import to @app-types. |
| src/middleware/multer/scenesJSONUpload.ts | Adds dedicated multer wrapper for scenes JSON uploads. |
| src/middleware/multer/filenameLogic/multerVideo.ts | Increases max video upload size limit. |
| src/middleware/multer/filenameLogic/multerJSON.ts | Switches JSON uploads to memory storage + simplified filter. |
| src/middleware/multer/filenameLogic/multerImage.ts | Switches image uploads to memory storage + simplified filter. |
| src/middleware/multer/filenameLogic/multerAudio.ts | Switches audio uploads to memory storage + simplified filter. |
| src/middleware/error/index.ts | Adjusts error constructors to new AppError signature. |
| src/middleware/error/globalErrorHandler.ts | Removes stray console logging and standardizes 500 envelope. |
| src/middleware/error/appError.ts | Standardizes serialized error envelope and hides prod details. |
| src/middleware/404/notFoundHandler.ts | Standardizes 404 JSON response envelope. |
| src/libs/aws/s3.ts | Replaces localstack demo code with real S3 upload/delete/presign helpers. |
| src/libs/ai/prompts/singleScenePrompt.ts | Switches to @app-types and re-exports scene mode types. |
| src/libs/ai/prompts/narrationPrompt.ts | Switches StoryContent import to @app-types. |
| src/libs/ai/prompts/generateStoryRegenerationPrompt.ts | Fixes import path to @libs alias. |
| src/libs/ai/prompts/batchScenesPrompt.ts | Switches to @app-types and re-exports scene mode types. |
| src/libs/ai/policies/resolveModel.ts | Switches type imports to @app-types. |
| src/libs/ai/clients/openAI.ts | Updates OpenRouter model identifier. |
| src/db/connect.ts | Refactors env handling + connection string selection. |
| src/constants/narrationConsts.ts | Adds header comment and formatting cleanup. |
| src/constants/globalConts.ts | Simplifies allowed origins list to env-provided URLs. |
| src/constants/audioConsts.ts | Adds new global audio constants module. |
| src/config/corsConfig.ts | Updates constants import and filters undefined origins. |
| package.json | Bumps AWS SDK packages and adds sharp. |
| Dockerfile | Sets NODE_ENV=production in container. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| @@ -95,10 +92,6 @@ const privacyPrefsSchema = new Schema( | |||
| type: Boolean, | |||
| default: true, | |||
| }, | |||
| allowDiscoverability: { | |||
| type: Boolean, | |||
| default: true, | |||
| }, | |||
| }, | |||
| { _id: false } | |||
There was a problem hiding this comment.
privacyPrefsSchema no longer allows profileVisibility: 'unlisted' and no longer defines allowDiscoverability, but other parts of the code (e.g., the privacyPrefs default object and updatePrivacySettings logic) still reference allowDiscoverability, and validation still accepts 'unlisted'. This mismatch will cause updates/defaults to be dropped (or invalid values to be stored) depending on Mongoose update settings. Align the schema with the expected fields/enum values, or update the rest of the codebase and request validation accordingly.
| import ffmpeg from 'fluent-ffmpeg'; | ||
|
|
||
| export function getVideoDuration(filePath: string): Promise<number> { | ||
| export function getVideoDuration(filePath: string): Promise<number> { |
There was a problem hiding this comment.
There are extra spaces in the function declaration (export function getVideoDuration...). This is easy to miss in reviews and can cause noisy diffs / formatter churn; please normalize the whitespace.
| const origin = req.headers.Origin; | ||
| if (origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) { | ||
| const origin = req.header('Origin') || req.headers['origin'] || req.headers.origin; | ||
| if (!origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) { |
There was a problem hiding this comment.
CSRF origin validation logic is inverted: if (!origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) will (a) reject requests without an Origin header, and (b) allow requests with a disallowed Origin header. This effectively disables the origin allowlist and can break non-browser clients. Change the condition to validate when an origin is present (and explicitly handle origin === 'null').
| if (!origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) { | |
| if (origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) { |
| if (scene.duration !== undefined && Math.abs(duration - scene.duration) < 0.25) { | ||
| await removeTempFile(file.path); | ||
| throw new BadRequestError('Video duration does not match existing scene duration and cannot be uploaded'); | ||
| } |
There was a problem hiding this comment.
The video-duration mismatch check is reversed: it currently throws when the uploaded video duration is within 0.25s of the scene duration (< 0.25). This will reject valid uploads and allow mismatched ones. Flip the comparison so it rejects when the difference exceeds the tolerance.
| router.get( | ||
| '/story/:storyId/deleted', | ||
| validateParams(storyIdParamSchema), | ||
| paginationAndSortingMiddleware, | ||
| asyncHandler(getAllDeletedNarrationsController) | ||
| ); |
There was a problem hiding this comment.
This route no longer applies paginationAndSortingMiddleware, but getAllDeletedNarrationsController still reads req.pagination / req.sorting and calls paginationResponse(...). As-is, requests to /story/:storyId/deleted will likely crash or return incorrect pagination. Either re-add the middleware here, or update the controller/service to not require pagination for this endpoint.
| export async function getAllNarrationForSceneOrder(userId: string, storyId: string, sceneOrderIds: string[]) { | ||
| const sceneOrderHash = hashSceneOrder(sceneOrderIds.map((id) => new Types.ObjectId(id))); | ||
| const narration = await StoryNarrationModel.findOne({ | ||
| userId, | ||
| storyId, | ||
| sceneOrderHash, | ||
| deletedAt: { $exists: false }, | ||
| }); | ||
| return narration; | ||
| }).populate('activeAudioAssetId'); | ||
|
|
||
| const sanitizedResponse = sanitizeNarrationsResponse([narration as StoryNarration]); | ||
|
|
||
| return sanitizedResponse; |
There was a problem hiding this comment.
getAllNarrationForSceneOrder can return null from findOne(...), but the code force-casts it to StoryNarration and passes it into sanitizeNarrationsResponse, which will throw at runtime. Handle the not-found case explicitly (e.g., return null or throw NotFoundError) before sanitizing. Also consider returning a single sanitized narration rather than an array, since the function name implies a single match.
| export const upload = multer({ | ||
| storage: multer.memoryStorage(), | ||
| fileFilter, | ||
| limits: { fileSize: 10 * 1024 * 1024 }, // 10 MB limit | ||
| limits: { | ||
| fileSize: 10 * 1024 * 1024, // 10MB | ||
| }, | ||
| }); |
There was a problem hiding this comment.
multer.memoryStorage() does not set req.file.path (it only provides req.file.buffer). Downstream code (e.g., audio upload controller/service) currently passes req.file.path, which will be undefined and break uploads. Either switch back to disk storage or update the upload flow to consume req.file.buffer and/or stream directly to S3.
| export const uploadAudioAssetController = async (req: Request, res: Response) => { | ||
| const userId = req.user!.id; | ||
| const { narrationId } = req.params; | ||
|
|
||
| if (!req.file) { | ||
| return res.status(400).json({ | ||
| message: 'No file uploaded', | ||
| }); | ||
| throw new BadRequestError('No file uploaded'); | ||
| } | ||
|
|
||
| const audioAsset = await uploadNarrationAudioAsset(userId, narrationId, req.file.path); | ||
|
|
||
| res.status(201).json({ | ||
| message: 'Audio asset uploaded successfully', | ||
| data: audioAsset, | ||
| }); | ||
| return sendSuccess(res, audioAsset, 'Audio asset uploaded successfully', 201); |
There was a problem hiding this comment.
This controller passes req.file.path into uploadNarrationAudioAsset(...), but the multer audio upload now uses memoryStorage, so req.file.path will be undefined. Use req.file.buffer (or adjust multer storage back to disk) and update uploadNarrationAudioAsset to accept/process a Buffer or a persisted object-store URL.
Used Antigravity for fast error resolving and Folder Structure Cleaning
Summary by CodeRabbit
Release Notes
New Features
Improvements
Chores