Skip to content

5 post api#11

Draft
MCSwainConnor wants to merge 8 commits intomainfrom
5-post-api
Draft

5 post api#11
MCSwainConnor wants to merge 8 commits intomainfrom
5-post-api

Conversation

@MCSwainConnor
Copy link
Copy Markdown
Collaborator

@MCSwainConnor MCSwainConnor commented Apr 20, 2026

Summary by CodeRabbit

  • New Features
    • Order management API with full CRUD operations (create, read, update, delete)
    • Database schema extended to support order records including customer information, size, and creation timestamps

@MCSwainConnor MCSwainConnor self-assigned this Apr 20, 2026
@MCSwainConnor MCSwainConnor linked an issue Apr 20, 2026 that may be closed by this pull request
5 tasks
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 20, 2026

📝 Walkthrough

Walkthrough

This pull request introduces a new Orders module alongside an extended Prisma module, both featuring complete CRUD operations backed by database schema updates. New dependencies for validation and ORM support are added to enable the functionality, with database migrations applied and modules integrated into the application root.

Changes

Cohort / File(s) Summary
Dependencies & Database Layer
package.json, prisma/schema.prisma, prisma/migrations/20260422114150/migration.sql
Added NestJS utilities, class-validator, TypeORM, and sanitize-html dependencies; introduced new Order Prisma model with UUID PK, name, size, costumer, and createdAt fields; created matching SQL migration table.
Orders Module DTOs
src/modules/orders/dto/create-order.dto.ts, src/modules/orders/dto/update-order.dto.ts
Defined CreateOrderDto with validated name and costumer (required, max 128 chars) and optional size; UpdateOrderDto extends PartialType(CreateOrderDto) for optional fields on updates.
Orders Module Core
src/modules/orders/order.service.ts, src/modules/orders/order.controller.ts, src/modules/orders/order.module.ts, src/modules/orders/mappings/order-dto.mappers.ts
Implemented OrderService with async CRUD methods delegating to PrismaService; OrdersController exposing POST/PATCH/DELETE endpoints; OrdersModule wiring controller and service; added mapOrderDTO mapper for DTO transformation.
Orders Module Tests
src/modules/orders/order.service.spec.ts, src/modules/orders/order.controller.spec.ts
Added basic instantiation test suites for OrderService and OrdersController using NestJS testing utilities.
Prisma Module Core
src/prisma/prisma.service.ts, src/prisma/prisma.controller.ts, src/prisma/prisma.module.ts, src/prisma/entities/prisma.entity.ts
Implemented PrismaService extending PrismaClient with lifecycle hooks (OnModuleInit, OnModuleDestroy) and wrapped CRUD methods for products; PrismaController exposing POST/GET/PATCH/DELETE endpoints; PrismaModule registering controller and service; added empty Prisma entity class.
Prisma Module DTOs & Tests
src/prisma/dto/create-prisma.dto.ts, src/prisma/dto/update-prisma.dto.ts, src/prisma/prisma.service.spec.ts, src/prisma/prisma.controller.spec.ts
Defined CreatePrismaDto with validated name (required, max 128 chars) and optional size/description; UpdatePrismaDto extends PartialType(CreatePrismaDto); added basic instantiation test suites.
Root Module Integration
src/app.module.ts
Added OrdersModule to root AppModule imports alongside existing PrismaModule and ProductModule.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • 4 get api #10 — Both PRs modify Prisma schema and introduce PrismaService with lifecycle management and client adapter configuration.

Suggested reviewers

  • ac-tiffi

Poem

🐰 A new Order hops into the fray,
With Prisma's touch, data comes to play,
DTOs validated, controllers prancing free,
CRUD operations swift as can be,
Migrations applied, the schema's refined,
A modular feast for code so refined!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title '5 post api' is vague and generic, failing to convey the actual scope of changes which include adding Orders module with CRUD operations, database schema, DTOs, and services alongside existing Prisma module additions. Revise the title to accurately describe the main changes, such as 'Add Orders module with CRUD endpoints and database migration' or 'Implement Orders feature with Prisma integration'.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 5-post-api

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 16

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
prisma/schema.prisma (1)

1-24: ⚠️ Potential issue | 🟠 Major

No Order model despite an orders feature module.

OrdersModule/OrdersController/OrdersService and CreateOrderDto are introduced, but schema.prisma contains only User and Product — there is no Order model. OrdersService cannot realistically persist orders through Prisma without one. Add the Order model (with the relations to User/Product you intend) and run a migration, or wire the orders endpoints to the correct delegate.

Also minor: stray trailing whitespace on line 9 (} ) and inconsistent column spacing in the Product model — worth a quick prisma format pass.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@prisma/schema.prisma` around lines 1 - 24, The schema.prisma is missing an
Order model required by
OrdersModule/OrdersController/OrdersService/CreateOrderDto so persistence fails;
add an Order model to schema.prisma that includes a primary id (UUID), relation
fields to User and Product (e.g., userId and productId with proper `@relation` to
User and Product), order-specific fields from CreateOrderDto (quantity, status,
total, createdAt), and appropriate `@db`.* annotations, then run a Prisma
migration and regenerate the client; alternatively, if you intended not to
persist orders, update OrdersService/OrdersController to use the correct
delegate instead of Prisma. Also remove the trailing whitespace on the
datasource block and run prisma format to normalize spacing in the Product
model.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@package.json`:
- Around line 25-40: Remove the unused TypeORM packages from package.json by
deleting "typeorm" and "@nestjs/typeorm"; in the DTO files
src/prisma/dto/create-prisma.dto.ts and
src/modules/orders/dto/create-order.dto.ts change imports that currently
reference "@nestjs/class-validator" and "@nestjs/class-transformer" to the
upstream packages "class-validator" and "class-transformer" (update any
decorators/usage import paths accordingly); and add "@types/sanitize-html" to
devDependencies in package.json to provide type definitions for sanitize-html.

In `@src/modules/orders/entities/order.entity.ts`:
- Line 1: The Order entity class is empty; either implement its domain fields to
match your data model or remove the stub to avoid dead code. If you intend to
keep it, add properties (e.g., id, userId, status, total, createdAt, updatedAt)
and any decorators/validation used across your project so it aligns with your
persistence layer (and update or add a corresponding model in schema.prisma);
otherwise delete the Order class to remove unused scaffolding. Locate the empty
Order class declaration (export class Order {}) and update or remove it
accordingly.

In `@src/modules/orders/orders.controller.spec.ts`:
- Around line 8-12: The test registers the real OrdersService which depends on
PrismaService; replace it with a mock so the controller test compiles. In the
beforeEach/Test.createTestingModule setup, provide a mocked OrdersService by
using a provider object (provide: OrdersService, useValue: mockOrdersService)
instead of the real class; create a simple mockOrdersService object that
implements the methods the OrdersController calls (e.g., findAll, findOne,
create, etc.) returning suitable stubs or promises, then compile the
TestingModule and inject OrdersController as before.

In `@src/modules/orders/orders.controller.ts`:
- Around line 6-34: The OrdersController/OrdersService currently target the
products delegate (PrismaService using this.products / prisma.products) while
exposing an "orders" API with CreateOrderDto fields; either add a real Order
model to the Prisma schema and update PrismaService to expose an orders delegate
and change OrdersService methods (create, findAll, findOne, update, remove) to
call prisma.orders (and adjust CreateOrderDto/UpdateOrderDto to order fields),
or rename and refactor the controller/service/DTOs to "Products" (rename
OrdersController -> ProductsController, OrdersService -> ProductsService,
CreateOrderDto -> CreateProductDto, UpdateOrderDto -> UpdateProductDto) and
ensure methods call prisma.products; update routing accordingly so the public
API and underlying Prisma delegate (PrismaService) stay consistent.
- Around line 20-32: Update the route handlers to validate the :id param as a
UUID before calling Prisma: apply Nest's ParseUUIDPipe to the id param in the
findOne, update, and remove methods (e.g., change `@Param`('id') id: string to
`@Param`('id', new ParseUUIDPipe()) id: string) and add ParseUUIDPipe to the
`@nestjs/common` import; also ensure a global ValidationPipe is registered in
main.ts so DTO validations (CreateOrderDto/UpdateOrderDto) are enforced.

In `@src/modules/orders/orders.service.spec.ts`:
- Around line 8-10: The test module fails because OrdersService depends on
PrismaService but the test providers only include OrdersService; update the
Test.createTestingModule call to provide a mock PrismaService (e.g., add a
provider object with provide: PrismaService and useValue: a minimal stub/mock
implementing the Prisma methods used by OrdersService or jest.fn() spies) so the
DI can resolve the dependency; ensure the mock is added to the providers array
passed into Test.createTestingModule before calling .compile() and that its
methods return the shapes OrdersService expects.

In `@src/modules/orders/orders.service.ts`:
- Around line 10-33: The OrdersService methods (create, findAll, findOne,
update, remove) and DTOs (CreateOrderDto, UpdateOrderDto) are delegating to
this.prisma CRUD for a non-existent Order model (Prisma schema has Product), so
either add an Order model and corresponding Prisma client methods or rename the
module/DTOs/controllers to operate on Product; to fix, choose one: (A) Add an
Order model to Prisma schema and run generate/migrate, then implement
orders-specific prisma methods used in OrdersService (create, findAll, findOne,
update, remove) so they target prisma.order instead of prisma.product; or (B)
Rename OrdersService, controller, DTOs and references to
ProductService/ProductDto and update method calls to use prisma.product.* so the
API consistently operates on Product. Ensure all references to
CreateOrderDto/UpdateOrderDto and OrdersService are updated to match the chosen
model.

In `@src/prisma/dto/create-prisma.dto.ts`:
- Around line 1-16: Register the global ValidationPipe in main.ts (call
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelowed:
true })) before app.listen()) so the decorators on CreatePrismaDto are enforced;
rename and consolidate ORM-named artifacts to domain names (rename
CreatePrismaDto → CreateProductDto, move PrismaController/PrismaService
responsibilities so PrismaService remains the thin DB client and use
ProductService/ProductsController for product routes) to avoid duplication with
existing ProductService/ProductsController; change the import from
`@nestjs/class-validator` to class-validator in the DTO file and add
`@MaxLength`(64) to size and `@MaxLength`(2048) to description on the DTO class
fields to bound input.

In `@src/prisma/entities/prisma.entity.ts`:
- Line 1: The file contains an empty placeholder class named Prisma which both
provides no functionality and conflicts with the `@prisma/client` Prisma
namespace; either remove this class entirely or replace it with a real domain
entity and a non-conflicting name (e.g., rename class Prisma to Product and add
appropriate fields/decorators) and update any imports accordingly so the
shadowed Prisma symbol is eliminated.

In `@src/prisma/prisma.controller.spec.ts`:
- Around line 1-20: Replace the real PrismaService provider in the
PrismaController test with a mock that stubs out PrismaService methods (and
prevents PrismaClient $connect from being called): instead of listing
PrismaService in providers, provide a mocked value for the token PrismaService
that implements the service methods used by PrismaController (e.g., create,
findAll, findOne, update, remove) and any $connect/$disconnect no-op, so the
test never opens a real DB connection; then add unit tests that call
PrismaController.create / findAll / findOne / update / remove (or the actual
CRUD handler names on PrismaController) and assert they delegate to the mocked
PrismaService methods (using spies/expect calls and returned mock values) rather
than only checking controller toBeDefined.

In `@src/prisma/prisma.controller.ts`:
- Around line 6-33: Remove PrismaController from the PrismaModule controllers
array and ensure PrismaModule only registers and exports the PrismaService
provider; locate the PrismaModule class (symbol PrismaModule) and remove
PrismaController from its controllers metadata, keeping PrismaService in the
providers and exports lists so domain modules can inject PrismaService while
HTTP routing remains with domain controllers (e.g., ProductsController,
OrdersController).
- Around line 20-32: Add UUID validation to the route params by importing
ParseUUIDPipe from `@nestjs/common` and applying it to the id route parameters in
the PrismaController methods findOne, update, and remove (i.e., change
`@Param`('id') id: string to `@Param`('id', new ParseUUIDPipe()) id: string) so
malformed IDs return 400 instead of reaching Prisma; make the identical change
in the OrdersController methods that accept an id param (import ParseUUIDPipe
there as well and apply new ParseUUIDPipe() to the id `@Param`).

In `@src/prisma/prisma.module.ts`:
- Around line 1-10: PrismaModule currently mixes infra and feature concerns:
remove PrismaController from PrismaModule so PrismaModule only provides and
exports PrismaService (keep providers: [PrismaService] and exports:
[PrismaService]) and optionally mark PrismaModule with `@Global`() if you want it
available app-wide; create a new ProductsModule that registers PrismaController
(rename/move PrismaController to ProductsController if appropriate) and its
feature provider ProductsService, and import PrismaModule into ProductsModule
(ProductsModule: controllers: [ProductsController], providers:
[ProductsService], imports: [PrismaModule]); ensure any modules that used
PrismaController now import ProductsModule instead.

In `@src/prisma/prisma.service.ts`:
- Around line 43-70: PrismaService currently contains domain CRUD (create,
findAll, findOne, update, remove) tied to products via productsDelegate; move
these methods out of PrismaService and into a new ProductsService that injects
PrismaService and calls this.prisma.product.create / findMany / findUnique /
update / delete respectively; remove the product-specific methods (create,
findAll, findOne, update, remove, productsDelegate usage) from PrismaService so
it remains a thin PrismaClient lifecycle wrapper, then update controllers (e.g.,
ProductsController and OrdersController) to inject ProductsService (or inject
PrismaService only when accessing true DB primitives) so OrdersController no
longer reaches through PrismaService to products.
- Around line 26-30: The constructor in PrismaService currently passes
process.env.DATABASE_URL (typed string | undefined) directly into new PrismaPg
which can produce confusing driver errors when the env var is missing; update
the constructor to validate that process.env.DATABASE_URL is a non-empty string
and throw a clear startup Error if missing (or better, refactor to inject Nest's
ConfigService and read a validated DATABASE_URL from a ConfigModule validation
schema) before instantiating new PrismaPg so PrismaPg never receives undefined.
- Around line 38-70: The service currently accesses prismaClient.products which
is undefined at runtime; rename the helper and usages to use the singular
delegate (e.g., change productsDelegate() to productDelegate(), update the
cast/type to { product: ProductDelegate } or, better, remove the unsafe "as
unknown as" cast and directly access this.product), then update all call sites
(create, findAll, findOne, update, remove) to call productDelegate() (or
this.product) so they use the actual Prisma delegate; finally add an integration
test that invokes at least one CRUD method to prevent regressions.

---

Outside diff comments:
In `@prisma/schema.prisma`:
- Around line 1-24: The schema.prisma is missing an Order model required by
OrdersModule/OrdersController/OrdersService/CreateOrderDto so persistence fails;
add an Order model to schema.prisma that includes a primary id (UUID), relation
fields to User and Product (e.g., userId and productId with proper `@relation` to
User and Product), order-specific fields from CreateOrderDto (quantity, status,
total, createdAt), and appropriate `@db`.* annotations, then run a Prisma
migration and regenerate the client; alternatively, if you intended not to
persist orders, update OrdersService/OrdersController to use the correct
delegate instead of Prisma. Also remove the trailing whitespace on the
datasource block and run prisma format to normalize spacing in the Product
model.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: ad6d9b7d-7c55-4e85-aa60-b95f8a99bc38

📥 Commits

Reviewing files that changed from the base of the PR and between 6e8b424 and bcfd635.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (18)
  • package.json
  • prisma/schema.prisma
  • src/modules/orders/dto/create-order.dto.ts
  • src/modules/orders/dto/update-order.dto.ts
  • src/modules/orders/entities/order.entity.ts
  • src/modules/orders/orders.controller.spec.ts
  • src/modules/orders/orders.controller.ts
  • src/modules/orders/orders.module.ts
  • src/modules/orders/orders.service.spec.ts
  • src/modules/orders/orders.service.ts
  • src/prisma/dto/create-prisma.dto.ts
  • src/prisma/dto/update-prisma.dto.ts
  • src/prisma/entities/prisma.entity.ts
  • src/prisma/prisma.controller.spec.ts
  • src/prisma/prisma.controller.ts
  • src/prisma/prisma.module.ts
  • src/prisma/prisma.service.spec.ts
  • src/prisma/prisma.service.ts

Comment thread package.json
Comment thread src/modules/orders/entities/order.entity.ts Outdated
Comment on lines +8 to +12
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [OrdersController],
providers: [OrdersService],
}).compile();
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot Apr 22, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify the DI mismatch without running tests.
rg -n -C3 --type=ts 'class OrdersService|constructor\(private readonly prisma: PrismaService\)|controllers:\s*\[OrdersController\]|providers:\s*\[OrdersService\]'

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 2206


🏁 Script executed:

# Check OrdersController to see what OrdersService methods are called
rg -n -A 10 'class OrdersController|@' src/modules/orders/orders.controller.ts

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 1079


Mock OrdersService so this controller spec can compile.

OrdersService requires PrismaService, but this test registers the real service without providing that dependency. Use a service mock instead of pulling in the database layer.

🧪 Proposed fix
     const module: TestingModule = await Test.createTestingModule({
       controllers: [OrdersController],
-      providers: [OrdersService],
+      providers: [
+        {
+          provide: OrdersService,
+          useValue: {
+            create: jest.fn(),
+            findAll: jest.fn(),
+            findOne: jest.fn(),
+            update: jest.fn(),
+            remove: jest.fn(),
+          },
+        },
+      ],
     }).compile();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/orders/orders.controller.spec.ts` around lines 8 - 12, The test
registers the real OrdersService which depends on PrismaService; replace it with
a mock so the controller test compiles. In the
beforeEach/Test.createTestingModule setup, provide a mocked OrdersService by
using a provider object (provide: OrdersService, useValue: mockOrdersService)
instead of the real class; create a simple mockOrdersService object that
implements the methods the OrdersController calls (e.g., findAll, findOne,
create, etc.) returning suitable stubs or promises, then compile the
TestingModule and inject OrdersController as before.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MCSwainConnor Mocking und test schreiben müssen wir uns denke ich getrennt ma unterhalten

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment thread src/modules/orders/orders.controller.ts Outdated
Comment thread src/modules/orders/orders.controller.ts Outdated
Comment on lines +20 to +32
@Get(':id')
findOne(@Param('id') id: string) {
return this.prismaService.findOne(id);
}

@Patch(':id')
update(@Param('id') id: string, @Body() updatePrismaDto: UpdatePrismaDto) {
return this.prismaService.update(id, updatePrismaDto);
}

@Delete(':id')
remove(@Param('id') id: string) {
return this.prismaService.remove(id);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify raw id params and UUID-backed schema fields.
rg -n -C2 --type=ts "@Param\\('id'\\) id: string|ParseUUIDPipe"
rg -n -C2 '@db\\.Uuid|@default\\(dbgenerated\\("gen_random_uuid\\(\\)"\\)\\)'

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 1958


🏁 Script executed:

# Find and examine the Prisma schema file
find . -name "*.prisma" -type f

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 97


🏁 Script executed:

# Check the current imports in prisma.controller.ts
sed -n '1,10p' src/prisma/prisma.controller.ts

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 456


🏁 Script executed:

# Search for UUID field definitions in schema
rg -n "id.*@db\.Uuid|UUID" --type prisma

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 105


🏁 Script executed:

# Check all controllers for similar patterns
rg -l "findOne.*@Param\('id'\)" --type ts

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 146


🏁 Script executed:

# Read the Prisma schema to check ID field types
cat prisma/schema.prisma

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 649


🏁 Script executed:

# Check orders.controller.ts imports
sed -n '1,10p' src/modules/orders/orders.controller.ts

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 452


Add UUID validation to route parameters.

The Prisma schema defines UUID IDs (@db.Uuid), but route handlers accept any string without validation. This affects both src/prisma/prisma.controller.ts and src/modules/orders/orders.controller.ts. Add ParseUUIDPipe to return 400 for malformed IDs instead of leaking Prisma/database errors.

Proposed fix (src/prisma/prisma.controller.ts)
-import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
+import { Controller, Get, Post, Body, Patch, Param, Delete, ParseUUIDPipe } from '@nestjs/common';
 
   `@Get`(':id')
-  findOne(`@Param`('id') id: string) {
+  findOne(`@Param`('id', ParseUUIDPipe) id: string) {
     return this.prismaService.findOne(id);
   }
 
   `@Patch`(':id')
-  update(`@Param`('id') id: string, `@Body`() updatePrismaDto: UpdatePrismaDto) {
+  update(`@Param`('id', ParseUUIDPipe) id: string, `@Body`() updatePrismaDto: UpdatePrismaDto) {
     return this.prismaService.update(id, updatePrismaDto);
   }
 
   `@Delete`(':id')
-  remove(`@Param`('id') id: string) {
+  remove(`@Param`('id', ParseUUIDPipe) id: string) {
     return this.prismaService.remove(id);
   }

Apply the same changes to src/modules/orders/orders.controller.ts.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Get(':id')
findOne(@Param('id') id: string) {
return this.prismaService.findOne(id);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updatePrismaDto: UpdatePrismaDto) {
return this.prismaService.update(id, updatePrismaDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.prismaService.remove(id);
import { Controller, Get, Post, Body, Patch, Param, Delete, ParseUUIDPipe } from '@nestjs/common';
`@Get`(':id')
findOne(`@Param`('id', ParseUUIDPipe) id: string) {
return this.prismaService.findOne(id);
}
`@Patch`(':id')
update(`@Param`('id', ParseUUIDPipe) id: string, `@Body`() updatePrismaDto: UpdatePrismaDto) {
return this.prismaService.update(id, updatePrismaDto);
}
`@Delete`(':id')
remove(`@Param`('id', ParseUUIDPipe) id: string) {
return this.prismaService.remove(id);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/prisma/prisma.controller.ts` around lines 20 - 32, Add UUID validation to
the route params by importing ParseUUIDPipe from `@nestjs/common` and applying it
to the id route parameters in the PrismaController methods findOne, update, and
remove (i.e., change `@Param`('id') id: string to `@Param`('id', new
ParseUUIDPipe()) id: string) so malformed IDs return 400 instead of reaching
Prisma; make the identical change in the OrdersController methods that accept an
id param (import ParseUUIDPipe there as well and apply new ParseUUIDPipe() to
the id `@Param`).

Comment on lines +1 to +10
import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
import { PrismaController } from './prisma.controller';

@Module({
controllers: [PrismaController],
providers: [PrismaService],
exports: [PrismaService],
})
export class PrismaModule {}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Mixing infrastructure and feature concerns in one module.

PrismaModule simultaneously (a) exports PrismaService as shared infrastructure for other modules (OrdersModule, ProductModule both import it) and (b) registers a PrismaController that exposes product CRUD endpoints. These should be split:

  • PrismaModule → only providers: [PrismaService] + exports: [PrismaService] (infra, reusable).
  • A dedicated ProductsModulecontrollers: [ProductsController], providers: [ProductsService], imports: [PrismaModule].

Also consider marking PrismaModule as @Global() if every feature module will import it, so you don't have to add it to each imports array.

🔧 Suggested shape
 import { Module } from '@nestjs/common';
 import { PrismaService } from './prisma.service';
-import { PrismaController } from './prisma.controller';

+@Global()
 `@Module`({
-  controllers: [PrismaController],
   providers: [PrismaService],
   exports: [PrismaService],
 })
 export class PrismaModule {}

(and move the controller to a new ProductsModule).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/prisma/prisma.module.ts` around lines 1 - 10, PrismaModule currently
mixes infra and feature concerns: remove PrismaController from PrismaModule so
PrismaModule only provides and exports PrismaService (keep providers:
[PrismaService] and exports: [PrismaService]) and optionally mark PrismaModule
with `@Global`() if you want it available app-wide; create a new ProductsModule
that registers PrismaController (rename/move PrismaController to
ProductsController if appropriate) and its feature provider ProductsService, and
import PrismaModule into ProductsModule (ProductsModule: controllers:
[ProductsController], providers: [ProductsService], imports: [PrismaModule]);
ensure any modules that used PrismaController now import ProductsModule instead.

Comment on lines +26 to +30
constructor() {
super({
adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Validate DATABASE_URL before instantiating PrismaPg.

process.env.DATABASE_URL is typed as string | undefined. If the env var is missing (e.g. .env not loaded in a given environment), PrismaPg receives undefined as connectionString and the failure mode is a confusing connection/driver error rather than a clear startup error.

Proposed fix
   constructor() {
+    const connectionString = process.env.DATABASE_URL;
+    if (!connectionString) {
+      throw new Error('DATABASE_URL is not set');
+    }
     super({
-      adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
+      adapter: new PrismaPg({ connectionString }),
     });
   }

Or, preferably, wire this through Nest's ConfigModule with a validation schema so all required env vars fail fast on boot.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/prisma/prisma.service.ts` around lines 26 - 30, The constructor in
PrismaService currently passes process.env.DATABASE_URL (typed string |
undefined) directly into new PrismaPg which can produce confusing driver errors
when the env var is missing; update the constructor to validate that
process.env.DATABASE_URL is a non-empty string and throw a clear startup Error
if missing (or better, refactor to inject Nest's ConfigService and read a
validated DATABASE_URL from a ConfigModule validation schema) before
instantiating new PrismaPg so PrismaPg never receives undefined.

Comment on lines +38 to +70
private productsDelegate(): ProductsDelegate {
const prismaClient = this as unknown as { products: ProductsDelegate };
return prismaClient.products;
}

create(createPrismaDto: CreatePrismaDto) {
return this.productsDelegate().create({
data: createPrismaDto,
});
}

findAll() {
return this.productsDelegate().findMany();
}

findOne(id: string) {
return this.productsDelegate().findUnique({
where: { id },
});
}

update(id: string, updatePrismaDto: UpdatePrismaDto) {
return this.productsDelegate().update({
where: { id },
data: updatePrismaDto,
});
}

remove(id: string) {
return this.productsDelegate().delete({
where: { id },
});
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm the generated delegate name and that no @@map renames the table.
fd -t f 'schema.prisma' --exec cat {}
echo '---'
rg -nP '\b(product|products)\s*:' --type=ts -g '!**/generated/**'

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 877


🏁 Script executed:

# Check the full prisma.service.ts to see all CRUD methods and type definition
fd -t f 'prisma.service.ts' -path '*/src/prisma/*' --exec cat {}

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 243


🏁 Script executed:

# Check the test file to see what is actually being tested
fd -t f 'prisma.service.spec.ts' --exec cat {}

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 994


🏁 Script executed:

# Check if there are any integration tests that hit the CRUD endpoints
fd -t f '.spec.ts' --exec rg -l 'create|findAll|findOne|update|remove' {} \; | head -20

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 433


🏁 Script executed:

# Get full prisma.service.ts content
cat -n src/prisma/prisma.service.ts

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 2481


🏁 Script executed:

# Check app.e2e-spec.ts to see if it has integration tests covering the CRUD endpoints
cat -n test/app.e2e-spec.ts

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 1002


Critical: prismaClient.products is undefined — all CRUD methods will throw at runtime.

The schema defines model Product (singular, no @@map), so Prisma generates the delegate as prisma.product, not prisma.products. The as unknown as { products: ProductsDelegate } cast silences TypeScript, but at runtime prismaClient.products is undefined. Calling .create(), .findMany(), .findUnique(), .update(), or .delete() on undefined throws TypeError: Cannot read properties of undefined.

All five CRUD methods (create, findAll, findOne, update, remove) will fail on the first request. The test suite does not catch this because prisma.service.spec.ts only asserts the service is defined, and app.e2e-spec.ts does not test any CRUD endpoints.

Fix: Rename the type and method to singular (ProductDelegate and productDelegate()), update the cast to { product: ProductDelegate }, and update all five call sites. Better: drop the as unknown as cast entirely and access this.product directly, letting the compiler enforce correctness.

Add an integration test that invokes one of the CRUD methods to catch this in the future.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/prisma/prisma.service.ts` around lines 38 - 70, The service currently
accesses prismaClient.products which is undefined at runtime; rename the helper
and usages to use the singular delegate (e.g., change productsDelegate() to
productDelegate(), update the cast/type to { product: ProductDelegate } or,
better, remove the unsafe "as unknown as" cast and directly access
this.product), then update all call sites (create, findAll, findOne, update,
remove) to call productDelegate() (or this.product) so they use the actual
Prisma delegate; finally add an integration test that invokes at least one CRUD
method to prevent regressions.

Comment on lines +43 to +70
create(createPrismaDto: CreatePrismaDto) {
return this.productsDelegate().create({
data: createPrismaDto,
});
}

findAll() {
return this.productsDelegate().findMany();
}

findOne(id: string) {
return this.productsDelegate().findUnique({
where: { id },
});
}

update(id: string, updatePrismaDto: UpdatePrismaDto) {
return this.productsDelegate().update({
where: { id },
data: updatePrismaDto,
});
}

remove(id: string) {
return this.productsDelegate().delete({
where: { id },
});
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Don't put domain CRUD on PrismaService.

PrismaService should be a thin lifecycle wrapper around PrismaClient; placing create/findAll/findOne/update/remove (specific to the Product table) on it couples the shared DB client to one entity and will not scale once a second model is added — you'd end up with either name collisions or a kitchen-sink service. The Products CRUD belongs in a ProductsService that injects PrismaService and calls this.prisma.product.* directly. OrdersService should then either inject its own (future) orders delegate or ProductsService, not reach through PrismaService.

This is also what's producing the orders → products confusion flagged in orders.controller.ts.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/prisma/prisma.service.ts` around lines 43 - 70, PrismaService currently
contains domain CRUD (create, findAll, findOne, update, remove) tied to products
via productsDelegate; move these methods out of PrismaService and into a new
ProductsService that injects PrismaService and calls this.prisma.product.create
/ findMany / findUnique / update / delete respectively; remove the
product-specific methods (create, findAll, findOne, update, remove,
productsDelegate usage) from PrismaService so it remains a thin PrismaClient
lifecycle wrapper, then update controllers (e.g., ProductsController and
OrdersController) to inject ProductsService (or inject PrismaService only when
accessing true DB primitives) so OrdersController no longer reaches through
PrismaService to products.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

♻️ Duplicate comments (3)
src/modules/orders/order.controller.spec.ts (1)

8-12: ⚠️ Potential issue | 🟠 Major

Missing PrismaService provider causes test to fail in CI.

The pipeline confirms Nest cannot resolve PrismaService for OrderService. Mock OrderService (or provide a PrismaService mock) so this controller spec compiles.

🧪 Proposed fix
     const module: TestingModule = await Test.createTestingModule({
       controllers: [OrdersController],
-      providers: [OrderService],
+      providers: [
+        {
+          provide: OrderService,
+          useValue: {
+            create: jest.fn(),
+            findAll: jest.fn(),
+            findOne: jest.fn(),
+            update: jest.fn(),
+            remove: jest.fn(),
+          },
+        },
+      ],
     }).compile();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/orders/order.controller.spec.ts` around lines 8 - 12, The test
fails because TestingModule cannot resolve PrismaService required by
OrderService; update the beforeEach Test.createTestingModule setup to either
mock OrderService or provide a PrismaService mock: add a provider for
PrismaService (e.g., { provide: PrismaService, useValue: mockPrisma }) or
replace OrderService with a mock provider (e.g., { provide: OrderService,
useValue: mockOrderService }) so OrdersController can be instantiated; ensure
your mock implements the methods used by OrdersController (referenced in
OrdersController and OrderService) and keep the provider names exact so Nest can
resolve them during beforeEach compilation.
src/modules/orders/order.service.spec.ts (1)

7-10: ⚠️ Potential issue | 🟠 Major

Provide a PrismaService mock — CI is red.

OrderService's constructor requires PrismaService; the pipeline failure at line 8 confirms Nest DI cannot resolve it. Add a mock provider.

🧪 Proposed fix
 import { Test, TestingModule } from '@nestjs/testing';
 import { OrderService } from './order.service';
+import { PrismaService } from '../../prisma/prisma.service';
 
 describe('OrderService', () => {
   let service: OrderService;
 
   beforeEach(async () => {
     const module: TestingModule = await Test.createTestingModule({
-      providers: [OrderService],
+      providers: [
+        OrderService,
+        {
+          provide: PrismaService,
+          useValue: {
+            order: {
+              create: jest.fn(),
+              findMany: jest.fn(),
+              findUnique: jest.fn(),
+              update: jest.fn(),
+              delete: jest.fn(),
+            },
+          },
+        },
+      ],
     }).compile();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/orders/order.service.spec.ts` around lines 7 - 10, The test setup
fails because OrderService depends on PrismaService; update the
Test.createTestingModule call in the beforeEach to provide a mock PrismaService:
add a provider object like { provide: PrismaService, useValue: mockPrisma } (or
inline useValue with the minimal methods OrderService calls, e.g.,
mockPrisma.order = { findUnique: jest.fn(), create: jest.fn(), ... }) so Nest
can resolve dependency when constructing OrderService; ensure the mock object
name (mockPrisma) and the provider reference (PrismaService) match the symbols
used in the spec and that Test.createTestingModule(... providers: [...])
includes both OrderService and the PrismaService mock.
package.json (1)

25-41: ⚠️ Potential issue | 🟠 Major

Unused TypeORM deps and stagnant NestJS validator forks still present.

  • @nestjs/typeorm (line 32) and typeorm (line 41) are not imported anywhere in this PR's code — remove both.
  • @nestjs/class-transformer and @nestjs/class-validator (lines 25–26) are abandoned forks (last release Feb 2022). The DTOs in this PR (src/modules/orders/dto/update-order.dto.ts, src/modules/orders/dto/create-order.dto.ts) already import from upstream class-validator, so the fork entries are dead weight — drop them and keep only upstream class-validator/class-transformer.
  • sanitize-html is declared but @types/sanitize-html is missing from devDependencies.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@package.json` around lines 25 - 41, Remove the unused/abandoned forked Nest
packages and redundant TypeORM entries from package.json: delete
"@nestjs/typeorm" and "typeorm", and drop "@nestjs/class-transformer" and
"@nestjs/class-validator"; keep the upstream "class-validator" and add the
official "class-transformer" dependency if needed. Ensure all DTOs import from
"class-validator" (not "@nestjs/class-validator") and update any imports to the
upstream "class-transformer" if used. Finally, add "@types/sanitize-html" to
devDependencies to provide typings for "sanitize-html".
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@prisma/migrations/20260422114150/migration.sql`:
- Around line 22-31: The "Order" table column is misspelled as "costumer" —
update the migration SQL to rename the column to "customer" in the CREATE TABLE
statement and then propagate that rename through the codebase by updating the
Prisma schema model Order field, all DTOs, mapper functions, and any service
methods that reference "costumer"; search for the exact token "costumer" and
replace with "customer", regenerate the Prisma client (prisma generate) and run
tests to ensure no remaining references exist.

In `@prisma/schema.prisma`:
- Around line 26-32: The Order model currently stores customer as the misspelled
free-text field costumer and duplicates product info in name/size; change Order
by renaming costumer to customerId (type String `@db.Uuid`) and add a relation
field customer User `@relation`(fields: [customerId], references: [id]) so Orders
reference the User model (update any DTOs that used costumer), and replace the
product name/size pair with a proper relation such as productId String `@db.Uuid`
and product Product `@relation`(fields: [productId], references: [id]) (or
explicitly mark name/size as guest fields if intended); after editing the Order
model and fixing the misspelling, regenerate the migration so the schema change
is applied cleanly before merging.

In `@src/modules/orders/dto/create-order.dto.ts`:
- Around line 13-16: The field name costumer is misspelled; rename it to
customer across the codebase: update the DTO property in create-order.dto.ts
(costumer -> customer), update the Prisma model Order (Order.costumer ->
Order.customer) and run prisma migrate/dev (or create a migration) then
regenerate the Prisma client, and update all references and method
signatures/usages such as OrderService.create and any DTO/validation,
controller, or repository code that refer to costumer to use customer instead.

In `@src/modules/orders/dto/update-order.dto.ts`:
- Around line 5-19: The UpdateOrderDto class is re-declaring name, size, and
costumer which overrides PartialType(CreateOrderDto) and forces required fields;
remove the explicit property declarations from UpdateOrderDto so it simply
extends PartialType(CreateOrderDto) (or if you need extra rules, declare the
same properties as optional (e.g., name?: string) and avoid `@IsNotEmpty`() /
definite-assignment `!`, or use conditional validators like `@ValidateIf` to keep
PATCH semantics). Ensure UpdateOrderDto relies on PartialType(CreateOrderDto)
for optionality and validation metadata instead of redeclaring name, size,
costumer.

In `@src/modules/orders/mappings/order-dto.mappers.ts`:
- Around line 4-10: The mapOrderDTO function currently maps an Order to
CreateOrderDto and drops id and createdAt; update this by either (A) creating a
new response type (e.g., OrderDto or OrderResponseDto) that includes id and
createdAt and change mapOrderDTO's return type to that, ensuring
mapOrderDTO(order: Order) returns { id: order.id, name: order.name, size:
order.size ?? undefined, costumer: order.costumer, createdAt: order.createdAt },
or (B) if the mapper was intended only for input reuse, delete mapOrderDTO and
rename any usages to make intent clear (or rename function to mapOrderInputDto)
so callers use the full Order type for responses; adjust all references to
mapOrderDTO and CreateOrderDto accordingly.

In `@src/modules/orders/order.controller.ts`:
- Around line 11-24: Add authentication and ownership checks to the order
endpoints: annotate the controller or these methods (create, update, remove)
with `@UseGuards`(JwtAuthGuard) so only authenticated callers can reach them; for
update and remove, fetch the existing order (via orderService.findOne or
orderService.findById) and compare its owner/customer id to the caller's id from
the JWT (injected via `@Req`() or a `@User`() decorator), and only call
orderService.update or orderService.remove if the caller is the owner or has an
admin role; if not authorized, throw an appropriate ForbiddenException.
- Around line 7-25: The controller lacks GET routes for listing and retrieving
single orders and the service is missing findOne; add a `@Get`() handler in
OrdersController that calls this.orderService.findAll(), and add a `@Get`(':id')
handler named findOne(`@Param`('id') id: string) that calls a new
OrderService.findOne(id) method; implement OrderService.findOne(id) to return
the single Order (or throw/not-found) so the controller can delegate to it and
ensure types return Promise<Order> or Promise<Order[]> as appropriate.

In `@src/modules/orders/order.service.ts`:
- Around line 11-18: In create(order: CreateOrderDto) within OrderService (async
create), remove the manual createdAt: new Date() from the data passed to
prisma.order.create so Prisma/Postgres can use the schema default; simply spread
the DTO (data: { ...order }) and ensure CreateOrderDto does not force a
createdAt field before calling prisma to avoid overriding the DB default.

In `@src/prisma/prisma.controller.ts`:
- Around line 1-36: PrismaController is exposing an unauthenticated CRUD surface
over Products (via prismaService -> productsDelegate) with a misleading name;
either secure it or remove/move it: add an authentication/authorization guard
(e.g., annotate the PrismaController class with `@UseGuards`(AdminGuard) and
import/provide AdminGuard) so only admins can access its
create/findAll/findOne/update/remove methods, or move the
create/findAll/findOne/update/remove delegations into the existing
ProductsController and remove PrismaController from PrismaModule.controllers to
avoid duplicate/hidden endpoints; update module registrations and imports
accordingly.

---

Duplicate comments:
In `@package.json`:
- Around line 25-41: Remove the unused/abandoned forked Nest packages and
redundant TypeORM entries from package.json: delete "@nestjs/typeorm" and
"typeorm", and drop "@nestjs/class-transformer" and "@nestjs/class-validator";
keep the upstream "class-validator" and add the official "class-transformer"
dependency if needed. Ensure all DTOs import from "class-validator" (not
"@nestjs/class-validator") and update any imports to the upstream
"class-transformer" if used. Finally, add "@types/sanitize-html" to
devDependencies to provide typings for "sanitize-html".

In `@src/modules/orders/order.controller.spec.ts`:
- Around line 8-12: The test fails because TestingModule cannot resolve
PrismaService required by OrderService; update the beforeEach
Test.createTestingModule setup to either mock OrderService or provide a
PrismaService mock: add a provider for PrismaService (e.g., { provide:
PrismaService, useValue: mockPrisma }) or replace OrderService with a mock
provider (e.g., { provide: OrderService, useValue: mockOrderService }) so
OrdersController can be instantiated; ensure your mock implements the methods
used by OrdersController (referenced in OrdersController and OrderService) and
keep the provider names exact so Nest can resolve them during beforeEach
compilation.

In `@src/modules/orders/order.service.spec.ts`:
- Around line 7-10: The test setup fails because OrderService depends on
PrismaService; update the Test.createTestingModule call in the beforeEach to
provide a mock PrismaService: add a provider object like { provide:
PrismaService, useValue: mockPrisma } (or inline useValue with the minimal
methods OrderService calls, e.g., mockPrisma.order = { findUnique: jest.fn(),
create: jest.fn(), ... }) so Nest can resolve dependency when constructing
OrderService; ensure the mock object name (mockPrisma) and the provider
reference (PrismaService) match the symbols used in the spec and that
Test.createTestingModule(... providers: [...]) includes both OrderService and
the PrismaService mock.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8198d164-8fea-4b35-8620-167e41e9ba07

📥 Commits

Reviewing files that changed from the base of the PR and between bcfd635 and dae3bae.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (13)
  • package.json
  • prisma/migrations/20260422114150/migration.sql
  • prisma/schema.prisma
  • src/app.module.ts
  • src/modules/orders/dto/create-order.dto.ts
  • src/modules/orders/dto/update-order.dto.ts
  • src/modules/orders/mappings/order-dto.mappers.ts
  • src/modules/orders/order.controller.spec.ts
  • src/modules/orders/order.controller.ts
  • src/modules/orders/order.module.ts
  • src/modules/orders/order.service.spec.ts
  • src/modules/orders/order.service.ts
  • src/prisma/prisma.controller.ts

Comment on lines +22 to +31
-- CreateTable
CREATE TABLE "Order" (
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
"name" TEXT NOT NULL,
"size" TEXT,
"costumer" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "Order_pkey" PRIMARY KEY ("id")
);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Spelling: costumercustomer.

The new Order.costumer column (line 27) is a typo that propagates into the Prisma schema, DTOs, mapper, and service. Renaming later requires a DB migration plus code changes across every layer; fixing it now while the column is still brand-new is essentially free.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@prisma/migrations/20260422114150/migration.sql` around lines 22 - 31, The
"Order" table column is misspelled as "costumer" — update the migration SQL to
rename the column to "customer" in the CREATE TABLE statement and then propagate
that rename through the codebase by updating the Prisma schema model Order
field, all DTOs, mapper functions, and any service methods that reference
"costumer"; search for the exact token "costumer" and replace with "customer",
regenerate the Prisma client (prisma generate) and run tests to ensure no
remaining references exist.

Comment thread prisma/schema.prisma
Comment on lines +26 to +32
model Order {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
name String
size String?
costumer String
createdAt DateTime @default(now()) @db.Timestamptz(6)
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Data model: customer should likely be a relation, not a free-text string.

Storing costumer (sic) as String denormalizes customer identity and precludes joining to User. Unless this is explicitly a guest-checkout name field, model it as customerId String @db.Uuid`` + customer User @relation`(fields: [customerId], references: [id])`. Also consider a relation to `Product` (what was actually ordered?) — the current `name` + `size` pair on `Order` duplicates product data and will drift.

Note: the costumer misspelling flagged on the DTO applies here too — fix it in the schema and regenerate the migration before this lands in main, since renaming a column post-release is disruptive.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@prisma/schema.prisma` around lines 26 - 32, The Order model currently stores
customer as the misspelled free-text field costumer and duplicates product info
in name/size; change Order by renaming costumer to customerId (type String
`@db.Uuid`) and add a relation field customer User `@relation`(fields: [customerId],
references: [id]) so Orders reference the User model (update any DTOs that used
costumer), and replace the product name/size pair with a proper relation such as
productId String `@db.Uuid` and product Product `@relation`(fields: [productId],
references: [id]) (or explicitly mark name/size as guest fields if intended);
after editing the Order model and fixing the misspelling, regenerate the
migration so the schema change is applied cleanly before merging.

Comment on lines +13 to +16
@IsString()
@IsNotEmpty()
@MaxLength(128)
costumer!: string;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Typo: costumer should be customer.

The field name costumer (a person wearing costumes) is misspelled throughout the stack — this DTO, prisma/schema.prisma (the Order.costumer column), and OrderService.create. Fixing this later requires a DB migration and a breaking API change, so correct it now before the endpoint ships.

🛠️ Proposed fix
   `@IsString`()
   `@IsNotEmpty`()
   `@MaxLength`(128)
-  costumer!: string;
+  customer!: string;

Apply the same rename in prisma/schema.prisma (model Order) and regenerate the migration.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@IsString()
@IsNotEmpty()
@MaxLength(128)
costumer!: string;
`@IsString`()
`@IsNotEmpty`()
`@MaxLength`(128)
customer!: string;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/orders/dto/create-order.dto.ts` around lines 13 - 16, The field
name costumer is misspelled; rename it to customer across the codebase: update
the DTO property in create-order.dto.ts (costumer -> customer), update the
Prisma model Order (Order.costumer -> Order.customer) and run prisma migrate/dev
(or create a migration) then regenerate the Prisma client, and update all
references and method signatures/usages such as OrderService.create and any
DTO/validation, controller, or repository code that refer to costumer to use
customer instead.

Comment on lines +5 to +19
export class UpdateOrderDto extends PartialType(CreateOrderDto) {
@IsString()
@IsNotEmpty()
@MaxLength(128)
name!: string;

@IsString()
@IsOptional()
size?: string;

@IsString()
@IsNotEmpty()
@MaxLength(128)
costumer!: string;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Re-declaring fields nullifies PartialType and breaks PATCH semantics.

PartialType(CreateOrderDto) already makes every field optional and carries over validation decorators. By re-declaring name, size, costumer here with @IsNotEmpty() and definite-assignment (!), you overwrite the partial metadata and force clients to send name and costumer on every PATCH /orders/:id — which defeats the purpose of a partial update DTO.

🛠 Proposed fix
 import { PartialType } from '@nestjs/swagger';
 import { CreateOrderDto } from './create-order.dto';
-import { IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator';
 
-export class UpdateOrderDto extends PartialType(CreateOrderDto) {
-  `@IsString`()
-  `@IsNotEmpty`()
-  `@MaxLength`(128)
-  name!: string;
-
-  `@IsString`()
-  `@IsOptional`()
-  size?: string;
-
-  `@IsString`()
-  `@IsNotEmpty`()
-  `@MaxLength`(128)
-  costumer!: string;
-}
+export class UpdateOrderDto extends PartialType(CreateOrderDto) {}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/orders/dto/update-order.dto.ts` around lines 5 - 19, The
UpdateOrderDto class is re-declaring name, size, and costumer which overrides
PartialType(CreateOrderDto) and forces required fields; remove the explicit
property declarations from UpdateOrderDto so it simply extends
PartialType(CreateOrderDto) (or if you need extra rules, declare the same
properties as optional (e.g., name?: string) and avoid `@IsNotEmpty`() /
definite-assignment `!`, or use conditional validators like `@ValidateIf` to keep
PATCH semantics). Ensure UpdateOrderDto relies on PartialType(CreateOrderDto)
for optionality and validation metadata instead of redeclaring name, size,
costumer.

Comment on lines +4 to +10
export function mapOrderDTO(order: Order): CreateOrderDto {
return {
name: order.name,
size: order.size ?? undefined,
costumer: order.costumer,
};
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Mapper drops id and createdAt — likely wrong target type.

Mapping a persisted Order into CreateOrderDto loses id/createdAt, so callers receiving this result cannot identify or order records. A mapper from entity → response DTO should produce a response type that includes id and createdAt (or re-use Order directly). If the intent is input-shape reuse, the naming mapOrderDTO is misleading.

Please either introduce an OrderDto/OrderResponseDto that includes id and createdAt, or remove this mapper if it's unused.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/orders/mappings/order-dto.mappers.ts` around lines 4 - 10, The
mapOrderDTO function currently maps an Order to CreateOrderDto and drops id and
createdAt; update this by either (A) creating a new response type (e.g.,
OrderDto or OrderResponseDto) that includes id and createdAt and change
mapOrderDTO's return type to that, ensuring mapOrderDTO(order: Order) returns {
id: order.id, name: order.name, size: order.size ?? undefined, costumer:
order.costumer, createdAt: order.createdAt }, or (B) if the mapper was intended
only for input reuse, delete mapOrderDTO and rename any usages to make intent
clear (or rename function to mapOrderInputDto) so callers use the full Order
type for responses; adjust all references to mapOrderDTO and CreateOrderDto
accordingly.

Comment thread src/modules/orders/order.controller.ts
Comment thread src/modules/orders/order.controller.ts
Comment on lines +11 to +18
async create(order: CreateOrderDto): Promise<Order> {
return this.prisma.order.create({
data: {
...order,
createdAt: new Date(),
},
});
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Drop the manual createdAt assignment.

The Prisma schema defines createdAt DateTime @default(now()) @db.Timestamptz(6), so Postgres will populate it. Setting createdAt: new Date() here overrides that with the app server's wall clock (timezone/skew sensitive) and adds noise to the insert. Spread the DTO alone.

🛠️ Proposed fix
   async create(order: CreateOrderDto): Promise<Order> {
     return this.prisma.order.create({
-      data: {
-        ...order,
-        createdAt: new Date(),
-      },
+      data: { ...order },
     });
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async create(order: CreateOrderDto): Promise<Order> {
return this.prisma.order.create({
data: {
...order,
createdAt: new Date(),
},
});
}
async create(order: CreateOrderDto): Promise<Order> {
return this.prisma.order.create({
data: { ...order },
});
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/orders/order.service.ts` around lines 11 - 18, In create(order:
CreateOrderDto) within OrderService (async create), remove the manual createdAt:
new Date() from the data passed to prisma.order.create so Prisma/Postgres can
use the schema default; simply spread the DTO (data: { ...order }) and ensure
CreateOrderDto does not force a createdAt field before calling prisma to avoid
overriding the DB default.

Comment on lines +1 to +36
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { ApiExcludeController } from '@nestjs/swagger';
import { PrismaService } from './prisma.service';
import { CreatePrismaDto } from './dto/create-prisma.dto';
import { UpdatePrismaDto } from './dto/update-prisma.dto';

@ApiExcludeController()
@Controller('prisma')
export class PrismaController {
constructor(private readonly prismaService: PrismaService) {}

@Post()
create(@Body() createPrismaDto: CreatePrismaDto) {
return this.prismaService.create(createPrismaDto);
}

@Get()
findAll() {
return this.prismaService.findAll();
}

@Get(':id')
findOne(@Param('id') id: string) {
return this.prismaService.findOne(id);
}

@Patch(':id')
update(@Param('id') id: string, @Body() updatePrismaDto: UpdatePrismaDto) {
return this.prismaService.update(id, updatePrismaDto);
}

@Delete(':id')
remove(@Param('id') id: string) {
return this.prismaService.remove(id);
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP --type=ts -C2 '\bPrismaController\b'
rg -nP --type=ts -C3 'controllers\s*:\s*\[' src/prisma src/app.module.ts

Repository: Tiffinger-Thiel-GmbH/Merch-Shop

Length of output: 3178


Misleading naming and unauthenticated CRUD surface.

The PrismaController concern has been clarified:

  • Correction: The controller IS registered in PrismaModule.controllers (line 6 of src/prisma/prisma.module.ts), so it is not dead code.

However, a design concern remains:

  • Per PrismaService, every method delegates to productsDelegate(), meaning /prisma provides an unauthenticated CRUD interface over Products with misleading naming. The @ApiExcludeController() decorator hides it from Swagger documentation but does not prevent runtime access.

If /prisma is intended as an internal/temporary endpoint, consider adding an admin guard (@UseGuards(AdminGuard)) or moving the logic to ProductsController to avoid confusion and unintended exposure.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/prisma/prisma.controller.ts` around lines 1 - 36, PrismaController is
exposing an unauthenticated CRUD surface over Products (via prismaService ->
productsDelegate) with a misleading name; either secure it or remove/move it:
add an authentication/authorization guard (e.g., annotate the PrismaController
class with `@UseGuards`(AdminGuard) and import/provide AdminGuard) so only admins
can access its create/findAll/findOne/update/remove methods, or move the
create/findAll/findOne/update/remove delegations into the existing
ProductsController and remove PrismaController from PrismaModule.controllers to
avoid duplicate/hidden endpoints; update module registrations and imports
accordingly.

import { CreateOrderDto } from './create-order.dto';
import { IsNotEmpty, IsOptional, IsString, MaxLength } from 'class-validator';

export class UpdateOrderDto extends PartialType(CreateOrderDto) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wenn du PartialType nutzt (an sich ok - wenn du wirklich alle felder von create auch updaten willst)
dann bringt es nichts alle felder nochmal aufzulisten. dann kannst du dir das partial sparen.

@IsString()
@IsNotEmpty()
@MaxLength(128)
name!: string;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Außerdem: in Update benutzt du ja "PATCH" und mit patch sollte man auch nur einen Teil der fleder updaten können.

Wenn du sie hier aber wieder required machst dann muss man ja immer alle mitgeben.

Ich hab zwar des PartialType noch nie verwendet, aber ich glaube es macht das schon korrekt.

dementsprechend würde

export class UpdateOrderDto extends PartialType(CreateOrderDto) { }

komplett reichen

(siehe rabbit comment)

Es gibt noch weiter Nestjs tools um zu vermeiden dtos doppelt zu schreiben, die kann man nutzten - aber immer mit bedacht. Zu viel krossreferenzierung macht den code auch nicht lesbarer :-)
(https://docs.nestjs.com/openapi/mapped-types)

Comment on lines +8 to +12
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [OrdersController],
providers: [OrdersService],
}).compile();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MCSwainConnor Mocking und test schreiben müssen wir uns denke ich getrennt ma unterhalten

Comment thread src/modules/orders/order.controller.ts
}

@Patch(':id')
update(@Param('id') id: string, @Body() updateOrderDto: UpdateOrderDto): Promise<Order> {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

für die Incoming daten kannst du auch DTOs verwenden, was cooler ist

z.b.

Suggested change
update(@Param('id') id: string, @Body() updateOrderDto: UpdateOrderDto): Promise<Order> {
update(@Param() param: OrderIdParamDTO, @Body() updateOrderDto: UpdateOrderDto): Promise<Order> {

Hier gibt es jetzt viele möglichkeiten das zu designen. Wenn du bestimmte ids öfter verwendest kannst du ein gemeinsames Id dto machen.

@Patch(':orderId')
export class OrderIdParamDTO {
  @ApiProperty({ example: '908096da-ade0-415b-aa40-48f53ff34b9c' }) 
  @IsUUID()
  orderId!: string;
}

Vorteil im vergleich zu deinem:

  • du kannst ein example mitgeben mit einer ID aus den seed daten.
    Dann wirds im swagger gleich vorausgefüllt. Finde es auch immer praktisch wenn jeder request examples definiert hat so dass man in der swagger ui zum ausprobieren einfach nur auf senden klicken muss.
  • validierung auf IsUUID
  • naming: ich finde es immer besser wenn du im code die ids nach dem benenst was für ids sie sind. (also wenn die id wo ein parameter oder so ist.)

}

@Delete(':id')
remove(@Param('id') id: string): Promise<Order> {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dann kannst dus hier genauso machen

Comment thread prisma/schema.prisma
} No newline at end of file
}

model Order {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eine Order besteht immer aus mehreren Items eigentlich.

Für Order gibt es mehrere Anforderungen:

  • sie muss den konkreten Item - stand zum zeitpunkt des kaufs wiederspiegeln. (kopie der tatsächlichen items)
  • Pro "Order" kann man mehrere Items haben.
  • Pro "Order" gibt es vlt noch einen bestellstatus etc.

--> damit du jetzt noch datenbankdesign lernst:

Erstelle ein ER Diagram das die datenbank beschreibt entsprechend dem Standard.

  • Inklusive der beziehungen
  • Inklusive der felder mit datentyp
  • Inklusive der FK PKs

Wir haben folgende Tabellen

  • User

  • Product

  • Order

  • OrderItem

  • Eine Order soll immer mehrere OrderItems gruppieren. (eine bestellung)

  • Eine Order hat einen OrderStatus als enum - Created, Ordered, Canceled, Done

  • Jedes OrderItem kopiert im prinzip die daten eines Products zum Zeitpunkt der Bestellung

  • Jedes OrderItem hat zusätzlich eine referenz zu dem original Produkt

@ac-tiffi ac-tiffi marked this pull request as draft April 23, 2026 14:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

POST-API

2 participants