feat: enhance seed script with environment variable support and error handling#25
feat: enhance seed script with environment variable support and error handling#25
Conversation
|
🚅 Deployed to the applirank-pr-25 environment in applirank
|
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📝 WalkthroughWalkthroughThe seed script is refactored to improve runtime safety and validation. Environment-driven configuration replaces hard-coded values, a safer array access helper with bounds checking replaces simple random selection, and defensive guards validate data existence before database operations throughout the generation flow. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
server/scripts/seed.ts (1)
29-36:process.envusage inserver/**/*.ts— acceptable exception for a standalone script.The coding guideline for
server/**/*.tsstates to use the Zod-validatedenvimport fromserver/utils/env.tsinstead ofprocess.envdirectly. Since this is a standalone CLI script (run vianpx tsx) that bootstraps its own DB connection outside the Nuxt runtime, the sharedenvutility likely isn't available here.If it's feasible to extract and reuse just the Zod validation schema from
env.ts(without Nuxt dependencies), that would bring this script in line with the guideline while still providing validation.As per coding guidelines:
server/**/*.ts— "Never useprocess.env.Xdirectly in server code—always importenvfromserver/utils/env.tswhich contains Zod-validated environment variables."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@server/scripts/seed.ts` around lines 29 - 36, This script uses process.env directly for DATABASE_URL and DEMO_PASSWORD; align with the project's env validation by either (A) importing the Zod-validated env export from server/utils/env.ts (use the exported env object to read DATABASE_URL and DEMO_PASSWORD) or (B) if that import pulls Nuxt runtime, extract the Zod schema from server/utils/env.ts into a small local validator in this script, run schema.parse(process.env) and then use the validated values instead of raw process.env (validate DATABASE_URL and DEMO_PASSWORD and assign to DATABASE_URL/DEMO_PASSWORD variables).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@server/scripts/seed.ts`:
- Around line 253-256: The guard silently returning {} when a candidate is
missing is inconsistent with the rest of the seed script; replace the
early-return with an explicit thrown error so out-of-bounds seed data fails
loudly. Locate the block that reads const candidate =
CANDIDATES_DATA[candidateIndex] and change the handling of !candidate to throw a
descriptive Error (including candidateIndex and CANDIDATES_DATA length) rather
than returning {} so subsequent code that builds applications/responses fails
fast and clearly.
---
Nitpick comments:
In `@server/scripts/seed.ts`:
- Around line 29-36: This script uses process.env directly for DATABASE_URL and
DEMO_PASSWORD; align with the project's env validation by either (A) importing
the Zod-validated env export from server/utils/env.ts (use the exported env
object to read DATABASE_URL and DEMO_PASSWORD) or (B) if that import pulls Nuxt
runtime, extract the Zod schema from server/utils/env.ts into a small local
validator in this script, run schema.parse(process.env) and then use the
validated values instead of raw process.env (validate DATABASE_URL and
DEMO_PASSWORD and assign to DATABASE_URL/DEMO_PASSWORD variables).
| const candidate = CANDIDATES_DATA[candidateIndex] | ||
| if (!candidate) { | ||
| return {} | ||
| } |
There was a problem hiding this comment.
Inconsistent error handling: silently returns {} instead of throwing.
Every other guard in this PR throws on invalid seed data (lines 441, 481, 487), and getArrayItemOrThrow also throws. A missing candidate here indicates a seed configuration bug (out-of-bounds candidateIndex), which should fail loudly rather than silently producing applications without responses.
Suggested fix
const candidate = CANDIDATES_DATA[candidateIndex]
if (!candidate) {
- return {}
+ throw new Error(`Missing candidate data at index ${candidateIndex}`)
}📝 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.
| const candidate = CANDIDATES_DATA[candidateIndex] | |
| if (!candidate) { | |
| return {} | |
| } | |
| const candidate = CANDIDATES_DATA[candidateIndex] | |
| if (!candidate) { | |
| throw new Error(`Missing candidate data at index ${candidateIndex}`) | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@server/scripts/seed.ts` around lines 253 - 256, The guard silently returning
{} when a candidate is missing is inconsistent with the rest of the seed script;
replace the early-return with an explicit thrown error so out-of-bounds seed
data fails loudly. Locate the block that reads const candidate =
CANDIDATES_DATA[candidateIndex] and change the handling of !candidate to throw a
descriptive Error (including candidateIndex and CANDIDATES_DATA length) rather
than returning {} so subsequent code that builds applications/responses fails
fast and clearly.
There was a problem hiding this comment.
Pull request overview
This PR strengthens initialization/seeding and related runtime flows by adding environment-driven configuration and defensive checks to reduce invalid records and runtime errors.
Changes:
- Allow configuring demo seed credentials via environment variables and add stricter seed-time validation/guardrails.
- Improve defensive handling around session/org access (typed active org) and DB/migration runtime safety.
- Expand dynamic sitemap generation to include blog URLs via Nuxt Content.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| server/utils/requireAuth.ts | Tightens typing/guarantees around activeOrganizationId for downstream server handlers. |
| server/utils/db.ts | Makes the lazy DB proxy safer for non-string property access. |
| server/scripts/seed.ts | Adds env-driven demo password and additional seed-time validation to avoid invalid configuration/data. |
| server/plugins/migrations.ts | Makes advisory-lock handling more defensive when reading query results. |
| server/middleware/demo-guard.ts | Hardens active-org extraction when guarding demo-mode write operations. |
| server/api/sitemap/urls.ts | Adds blog post URLs to the runtime sitemap source using Nuxt Content. |
| app/pages/onboarding/create-org.vue | Adds a defensive check before auto-switching to the single available org. |
| app/pages/index.vue | Avoids potential undefined access when auto-selecting the first org in demo flow. |
|
|
||
| const DEMO_EMAIL = 'demo@applirank.com' | ||
| const DEMO_PASSWORD = 'demo1234' | ||
| const DEMO_PASSWORD = process.env.DEMO_PASSWORD ?? 'demo1234' |
There was a problem hiding this comment.
DEMO_PASSWORD uses nullish coalescing, so an explicitly-set but empty env var (DEMO_PASSWORD="") will be treated as a valid password. That can seed an account with an empty password (or fail later if Better Auth enforces a minimum). Consider trimming and falling back when the value is empty/whitespace (e.g., use a ?.trim() check) so the seed behavior is predictable.
| const DEMO_PASSWORD = process.env.DEMO_PASSWORD ?? 'demo1234' | |
| const rawDemoPassword = process.env.DEMO_PASSWORD | |
| const DEMO_PASSWORD = rawDemoPassword && rawDemoPassword.trim() !== '' ? rawDemoPassword : 'demo1234' |
Summary by CodeRabbit
Bug Fixes
Chores