Skip to content

Drizzle db setup - #1

Merged
nirajmaharjan783 merged 5 commits into
mainfrom
drizzle-db-setup
Mar 27, 2026
Merged

nirajmaharjan783 merged 5 commits into
mainfrom
drizzle-db-setup

Conversation

@nirajmaharjan783

@nirajmaharjan783 nirajmaharjan783 commented Mar 26, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Established PostgreSQL database backend for application functionality
    • Implemented user account management with create, read, update, and upsert capabilities
    • Implemented product management with full CRUD operations and listing
    • Implemented comment management with create, read, and delete operations
    • Added automatic timestamp tracking for user modifications
  • Bug Fixes

    • Corrected product-comment relationship reference in database schema

@coderabbitai

coderabbitai Bot commented Mar 26, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 89c25cf3-4f24-457a-9472-0d093b852271

📥 Commits

Reviewing files that changed from the base of the PR and between e09884b and a2cfa03.

📒 Files selected for processing (1)
  • backend/src/db/schema.ts

📝 Walkthrough

Walkthrough

A new database layer has been established with PostgreSQL connection pooling via pg, Drizzle ORM initialization with schema bindings, and a comprehensive set of query helper functions for managing users, products, and comments entities with standard CRUD operations.

Changes

Cohort / File(s) Summary
Database Connection & Initialization
backend/src/db/index.ts
Creates a PostgreSQL connection pool using ENV.DATABASE_URL, registers event handlers for logging, and exports a Drizzle ORM instance configured with the schema module.
Database Schema Definitions
backend/src/db/schema.ts
Updates users table updatedAt column with auto-refresh hook; corrects foreign key reference in commentsRelations from userId to productId; contains unresolved merge conflict markers requiring resolution.
Database Query Helpers
backend/src/db/queries.ts
Exports 13 async query functions for users (create, read, update, upsert), products (create, read, read-all, read-by-user, update, delete), and comments (create, read, delete) with relation loading and error handling for missing entities.

Poem

🐰 A database takes shape with pools and with care,
Relations now flow like lettuce so fair,
Queries cascade through the schema we've laid,
From users to products, no query's afraid!
PostgreSQL pools and Drizzle unite—
Our backend's foundation burns ever so bright! 🌟

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Drizzle db setup' accurately describes the main objective of the pull request, which adds a complete Drizzle ORM database setup including configuration, schema, connection pool, and query utilities.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ 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 drizzle-db-setup

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/drizzle.config.ts`:
- Around line 5-10: The drizzle.config.ts currently passes ENV.DATABASE_URL!
directly into dbCredentials.url which can be undefined when Drizzle Kit runs;
add a runtime guard before returning defineConfig that checks ENV.DATABASE_URL
(the same way backend/src/db/index.ts does) and throw a clear Error like
"Missing DATABASE_URL env var" if it's falsy, then use the validated value in
dbCredentials.url; locate the defineConfig call and replace the direct
ENV.DATABASE_URL usage with the validated variable.

In `@backend/src/config/env.ts`:
- Line 7: The exported ENV value for DATABASE_URL is using the misspelled
process.env.DATABSE_URL which yields undefined; update the initializer to read
process.env.DATABASE_URL (fix the typo) so ENV.DATABASE_URL is populated
correctly for consumers such as the DB initialization code and drizzle
configuration.

In `@backend/src/db/index.ts`:
- Around line 7-9: The error message thrown when ENV.DATABASE_URL is missing is
misleading; update the thrown Error in the guard that checks ENV.DATABASE_URL to
reference "DATABASE_URL" (e.g., throw new Error("DATABASE_URL is not set in
environment variables")) so the message matches the actual environment variable
being checked (look for the ENV.DATABASE_URL check in this module).
- Line 26: The exported db is currently a plain object ({ client: pool, schema
}) but needs to be a Drizzle instance so downstream code can use Drizzle query
methods; replace the plain object export with a Drizzle initialization by
calling drizzle({ client: pool, schema }) and export that result as db, and
ensure the drizzle function is imported (e.g., import { drizzle } from the
appropriate Drizzle node-postgres package) so symbols db, pool, schema, and
drizzle are used consistently.

In `@backend/src/db/schema.ts`:
- Around line 59-62: The product relation in commentsRelations is using the
wrong source field; change the product relation to reference comments.productId
instead of comments.userId so fields: [comments.productId] and references:
[products.id] are used (keep the user relation as-is referencing comments.userId
-> users.id); update the relation definition in commentsRelations to use the
comments.productId foreign key for the products relation.
- Around line 21-22: The products table's updatedAt column is missing Drizzle's
runtime update hook so updates don't refresh the timestamp; mirror
users.updatedAt by adding the $onUpdate hook to the products.updatedAt column
(e.g., products.updatedAt.$onUpdate(() => new Date())) so Drizzle will set the
updated_at on modifications; update the timestamp definition for updatedAt in
the products schema to include $onUpdate() matching the users.updatedAt pattern.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4fdb87f1-d24e-44a5-9a86-8180f7be32df

📥 Commits

Reviewing files that changed from the base of the PR and between f47233b and ebffc5a.

📒 Files selected for processing (4)
  • backend/drizzle.config.ts
  • backend/src/config/env.ts
  • backend/src/db/index.ts
  • backend/src/db/schema.ts

Comment thread backend/drizzle.config.ts
Comment on lines +5 to +10
export default defineConfig({
schema: "./src/db/schema.ts",
dialect: "postgresql",
dbCredentials: {
url: ENV.DATABASE_URL!,
}

Copy link
Copy Markdown

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:

cat -n backend/drizzle.config.ts

Repository: nirajmaharjan783/productify

Length of output: 384


🏁 Script executed:

find . -type f -name "env.ts" -o -name "env.js" | head -20

Repository: nirajmaharjan783/productify

Length of output: 98


🏁 Script executed:

cat -n src/config/env.ts

Repository: nirajmaharjan783/productify

Length of output: 120


🏁 Script executed:

cat -n backend/src/config/env.ts

Repository: nirajmaharjan783/productify

Length of output: 507


🏁 Script executed:

head -50 backend/src/config/env.ts

Repository: nirajmaharjan783/productify

Length of output: 423


🏁 Script executed:

rg "DATABSE_URL|DATABASE_URL" --no-heading

Repository: nirajmaharjan783/productify

Length of output: 332


🏁 Script executed:

rg "ENV\.DATABASE_URL" --no-heading -A 2 -B 2

Repository: nirajmaharjan783/productify

Length of output: 736


Add runtime guard for DATABASE_URL in the CLI config to fail fast with Drizzle Kit commands.

Drizzle Kit commands (pull, push, migrate) read dbCredentials.url from drizzle.config.ts independently of runtime initialization. Currently, the file passes ENV.DATABASE_URL without validation, allowing undefined values to reach Drizzle. Add an explicit check here to match the guard already in place in backend/src/db/index.ts and ensure clear error messages when the environment variable is missing.

🛡️ Proposed fix
 import { defineConfig } from "drizzle-kit"
 import { ENV } from "./src/config/env"
 
+if (!ENV.DATABASE_URL) {
+    throw new Error("DATABASE_URL is not set in environment variables")
+}
 
 export default defineConfig({
     schema: "./src/db/schema.ts",
     dialect: "postgresql",
     dbCredentials: {
-        url: ENV.DATABASE_URL!,
+        url: ENV.DATABASE_URL,
     }
 })
📝 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
export default defineConfig({
schema: "./src/db/schema.ts",
dialect: "postgresql",
dbCredentials: {
url: ENV.DATABASE_URL!,
}
import { defineConfig } from "drizzle-kit"
import { ENV } from "./src/config/env"
if (!ENV.DATABASE_URL) {
throw new Error("DATABASE_URL is not set in environment variables")
}
export default defineConfig({
schema: "./src/db/schema.ts",
dialect: "postgresql",
dbCredentials: {
url: ENV.DATABASE_URL,
}
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/drizzle.config.ts` around lines 5 - 10, The drizzle.config.ts
currently passes ENV.DATABASE_URL! directly into dbCredentials.url which can be
undefined when Drizzle Kit runs; add a runtime guard before returning
defineConfig that checks ENV.DATABASE_URL (the same way backend/src/db/index.ts
does) and throw a clear Error like "Missing DATABASE_URL env var" if it's falsy,
then use the validated value in dbCredentials.url; locate the defineConfig call
and replace the direct ENV.DATABASE_URL usage with the validated variable.

Comment thread backend/src/config/env.ts Outdated
Comment thread backend/src/db/index.ts
Comment on lines +7 to +9
if (!ENV.DATABASE_URL) {
throw new Error("DB_URL is not set in environment variables")
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Rename the missing-env error to DATABASE_URL.

The guard is checking ENV.DATABASE_URL, but the thrown message still says DB_URL. That will point anyone debugging this failure at the wrong variable name.

✏️ Proposed fix
 if (!ENV.DATABASE_URL) {
-    throw new Error("DB_URL is not set in environment variables")
+    throw new Error("DATABASE_URL is not set in environment variables")
 }
📝 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
if (!ENV.DATABASE_URL) {
throw new Error("DB_URL is not set in environment variables")
}
if (!ENV.DATABASE_URL) {
throw new Error("DATABASE_URL is not set in environment variables")
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/db/index.ts` around lines 7 - 9, The error message thrown when
ENV.DATABASE_URL is missing is misleading; update the thrown Error in the guard
that checks ENV.DATABASE_URL to reference "DATABASE_URL" (e.g., throw new
Error("DATABASE_URL is not set in environment variables")) so the message
matches the actual environment variable being checked (look for the
ENV.DATABASE_URL check in this module).

Comment thread backend/src/db/index.ts Outdated
Comment thread backend/src/db/schema.ts
Comment on lines +21 to +22
createdAt: timestamp("created_at", { mode: "date" }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date" }).notNull().defaultNow()

Copy link
Copy Markdown

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:

find . -name "schema.ts" -path "*/backend/src/db/*" | head -5

Repository: nirajmaharjan783/productify

Length of output: 97


🏁 Script executed:

cat -n backend/src/db/schema.ts | head -30

Repository: nirajmaharjan783/productify

Length of output: 1716


🌐 Web query:

Drizzle ORM $onUpdate timestamp behavior defaultNow

💡 Result:

In Drizzle ORM, the $onUpdate (or $onUpdateFn) method on a column defines a function that executes at runtime during UPDATE queries. The returned value automatically sets the column if no explicit value is provided in the .set object. Key behavior with timestamps and defaultNow: - If the column has .defaultNow (or .default/.defaultFn), $onUpdate applies only on updates. - If no default is set, $onUpdate also applies on inserts. - This is runtime-only; it does not affect schema generation or migrations via drizzle-kit. - Common pattern for updatedAt: timestamp('updated_at').defaultNow.$onUpdate( => new Date) or . $onUpdate( => sqlCURRENT_TIMESTAMP) for DB time. - Works across PostgreSQL, MySQL, SQLite. - Early bugs with sql... in $onUpdate fixed in later versions (e.g., PR #2911). Example: updatedAt: timestamp('updated_at', { mode: 'date' }).defaultNow.$onUpdate( => new Date), On update: db.update(table).set({ name: 'new' }) // updatedAt auto-updates, no need to specify it.

Citations:


Add $onUpdate() to products.updatedAt to sync updates.

users.updatedAt opts into Drizzle's runtime update hook via $onUpdate(), but products.updatedAt does not. Without it, product rows updated through Drizzle will retain their insert-time updated_at instead of reflecting the last modification.

-    updatedAt: timestamp("updated_at", { mode: "date" }).notNull().defaultNow()
+    updatedAt: timestamp("updated_at", { mode: "date" }).notNull().defaultNow().$onUpdate(() => new Date())
📝 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
createdAt: timestamp("created_at", { mode: "date" }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date" }).notNull().defaultNow()
createdAt: timestamp("created_at", { mode: "date" }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date" }).notNull().defaultNow().$onUpdate(() => new Date())
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/db/schema.ts` around lines 21 - 22, The products table's
updatedAt column is missing Drizzle's runtime update hook so updates don't
refresh the timestamp; mirror users.updatedAt by adding the $onUpdate hook to
the products.updatedAt column (e.g., products.updatedAt.$onUpdate(() => new
Date())) so Drizzle will set the updated_at on modifications; update the
timestamp definition for updatedAt in the products schema to include $onUpdate()
matching the users.updatedAt pattern.

Comment thread backend/src/db/schema.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
backend/src/db/queries.ts (1)

31-36: Consider using Drizzle's onConflictDoUpdate for atomic upsert.

The current implementation has a race condition: between getUserById and createUser, another request could insert the same user, causing a unique constraint violation. Drizzle ORM supports atomic upserts via onConflictDoUpdate.

♻️ Suggested atomic upsert implementation
-// upsert => create or update
-export const upsertUser = async (data: NewUser) => {
-    const existingUser = await getUserById(data.id)
-    if (existingUser) return updateUser(data.id, data)
-
-    return createUser(data)
-}
+// upsert => create or update (atomic)
+export const upsertUser = async (data: NewUser) => {
+    const [user] = await db
+        .insert(users)
+        .values(data)
+        .onConflictDoUpdate({
+            target: users.id,
+            set: data,
+        })
+        .returning()
+    return user
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/db/queries.ts` around lines 31 - 36, The current upsertUser
implementation does a separate getUserById then createUser/updateUser which has
a race condition; replace it with a single atomic upsert using Drizzle's
onConflictDoUpdate on the unique id (use the same table/model used by
createUser/updateUser) so the insert will update existing rows on conflict.
Modify upsertUser to call the Drizzle insert with .onConflictDoUpdate({ target:
userTable.id, set: { /* map fields from NewUser that should be updated */ } })
and remove the getUserById/createUser/updateUser branching so the operation is
atomic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/src/db/queries.ts`:
- Around line 66-72: Rename the exported function getProductsByuserId to
getProductsByUserId to fix the camelCase inconsistency; update the function
declaration/export symbol from getProductsByuserId to getProductsByUserId and
adjust all references/imports/usages across the codebase (tests, call sites, and
any index re-exports) to use getProductsByUserId so nothing breaks at runtime.
- Around line 91-94: Rename the exported function deleteComments to
deleteComment (it deletes a single comment by id) and update its export
signature accordingly; inside the function keep the implementation using
db.delete(comments).where(eq(comments.id, id)).returning() and returning the
single comment variable, then update all call sites/imports that reference
deleteComments to the new name deleteComment and adjust any tests or type
annotations that expect the plural name.
- Around line 96-101: The function getCommentById currently awaits
db.query.comments.findFirst but does not return its result, so callers get
undefined; fix it by adding a return before the await in getCommentById so the
resolved comment (including the with: { user: true } relation) is returned to
callers, ensuring any downstream code receives the query result.

---

Nitpick comments:
In `@backend/src/db/queries.ts`:
- Around line 31-36: The current upsertUser implementation does a separate
getUserById then createUser/updateUser which has a race condition; replace it
with a single atomic upsert using Drizzle's onConflictDoUpdate on the unique id
(use the same table/model used by createUser/updateUser) so the insert will
update existing rows on conflict. Modify upsertUser to call the Drizzle insert
with .onConflictDoUpdate({ target: userTable.id, set: { /* map fields from
NewUser that should be updated */ } }) and remove the
getUserById/createUser/updateUser branching so the operation is atomic.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 48eb53b0-dfb1-4bde-8c50-8fee6375d2de

📥 Commits

Reviewing files that changed from the base of the PR and between ebffc5a and 57a756b.

📒 Files selected for processing (2)
  • backend/src/db/index.ts
  • backend/src/db/queries.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/db/index.ts

Comment thread backend/src/db/queries.ts
Comment on lines +66 to +72
export const getProductsByuserId = async (userId: string) => {
return db.query.products.findMany({
where: eq(products.userId, userId),
with: { user: true },
orderBy: (products, { desc }) => [desc(products.createdAt)]
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Inconsistent function naming: getProductsByuserId should be getProductsByUserId.

The lowercase 'u' in userId breaks camelCase consistency with other functions like getUserById and getProductById.

✏️ Proposed fix
-export const getProductsByuserId = async (userId: string) => {
+export const getProductsByUserId = async (userId: string) => {
📝 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
export const getProductsByuserId = async (userId: string) => {
return db.query.products.findMany({
where: eq(products.userId, userId),
with: { user: true },
orderBy: (products, { desc }) => [desc(products.createdAt)]
})
}
export const getProductsByUserId = async (userId: string) => {
return db.query.products.findMany({
where: eq(products.userId, userId),
with: { user: true },
orderBy: (products, { desc }) => [desc(products.createdAt)]
})
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/db/queries.ts` around lines 66 - 72, Rename the exported function
getProductsByuserId to getProductsByUserId to fix the camelCase inconsistency;
update the function declaration/export symbol from getProductsByuserId to
getProductsByUserId and adjust all references/imports/usages across the codebase
(tests, call sites, and any index re-exports) to use getProductsByUserId so
nothing breaks at runtime.

Comment thread backend/src/db/queries.ts
Comment thread backend/src/db/queries.ts

@nirajmaharjan783 nirajmaharjan783 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

a

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/src/db/queries.ts`:
- Around line 95-98: The updateProduct function currently returns undefined when
no product matches; make it consistent with updateUser/deleteProduct by throwing
an explicit error when not found. After awaiting
db.update(products).set(data).where(eq(products.id, id)).returning(), check the
returned product (the variable product) and if falsy throw a descriptive error
(e.g., "Product not found" or the project's NotFound error type) otherwise
return the product; update callers/tests if they expect the error.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 47c03d37-03f0-4b2d-b16e-476bf00b8055

📥 Commits

Reviewing files that changed from the base of the PR and between 57a756b and e09884b.

📒 Files selected for processing (3)
  • backend/src/config/env.ts
  • backend/src/db/queries.ts
  • backend/src/db/schema.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/config/env.ts

Comment thread backend/src/db/queries.ts
Comment on lines +95 to +98
export const updateProduct = async (id: string, data: Partial<NewProduct>) => {
const [product] = await db.update(products).set(data).where(eq(products.id, id)).returning()
return product
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

updateProduct silently returns undefined when product doesn't exist.

Unlike updateUser (lines 25-32) and deleteProduct (lines 100-107) which check existence and throw an error, updateProduct will return undefined if no matching product is found. This inconsistency could cause issues for callers expecting an error on missing products.

🔧 Proposed fix for consistency
 export const updateProduct = async (id: string, data: Partial<NewProduct>) => {
+    const existingProduct = await getProductById(id)
+    if (!existingProduct) {
+        throw new Error(`Product with id ${id} not found`)
+    }
     const [product] = await db.update(products).set(data).where(eq(products.id, id)).returning()
     return product
 }
📝 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
export const updateProduct = async (id: string, data: Partial<NewProduct>) => {
const [product] = await db.update(products).set(data).where(eq(products.id, id)).returning()
return product
}
export const updateProduct = async (id: string, data: Partial<NewProduct>) => {
const existingProduct = await getProductById(id)
if (!existingProduct) {
throw new Error(`Product with id ${id} not found`)
}
const [product] = await db.update(products).set(data).where(eq(products.id, id)).returning()
return product
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/db/queries.ts` around lines 95 - 98, The updateProduct function
currently returns undefined when no product matches; make it consistent with
updateUser/deleteProduct by throwing an explicit error when not found. After
awaiting db.update(products).set(data).where(eq(products.id, id)).returning(),
check the returned product (the variable product) and if falsy throw a
descriptive error (e.g., "Product not found" or the project's NotFound error
type) otherwise return the product; update callers/tests if they expect the
error.

@nirajmaharjan783 nirajmaharjan783 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Done

@nirajmaharjan783

Copy link
Copy Markdown
Owner Author

done

@nirajmaharjan783
nirajmaharjan783 merged commit 9930d2d into main Mar 27, 2026
1 check was pending
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.

1 participant