Skip to content

feat: enhance seed script with environment variable support and error handling#25

Merged
JoachimLK merged 2 commits intomainfrom
fix/typescript-problems
Feb 21, 2026
Merged

feat: enhance seed script with environment variable support and error handling#25
JoachimLK merged 2 commits intomainfrom
fix/typescript-problems

Conversation

@JoachimLK
Copy link
Copy Markdown
Contributor

@JoachimLK JoachimLK commented Feb 21, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Improved data validation during system initialization to prevent invalid records and configuration errors.
  • Chores

    • Added environment-driven configuration with safe fallbacks for initialization settings.
    • Enhanced error handling and defensive checks throughout the seeding process to improve system reliability.

@railway-app
Copy link
Copy Markdown

railway-app Bot commented Feb 21, 2026

🚅 Deployed to the applirank-pr-25 environment in applirank

Service Status Web Updated (UTC)
applirank ✅ Success (View Logs) Web Feb 21, 2026 at 11:13 am

@railway-app railway-app Bot temporarily deployed to applirank / applirank-pr-25 February 21, 2026 10:58 Destroyed
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 21, 2026

Warning

Rate limit exceeded

@JoachimLK has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 13 minutes and 6 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📝 Walkthrough

Walkthrough

The 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

Cohort / File(s) Summary
Seed Script Hardening
server/scripts/seed.ts
Replaced hard-coded demo password with environment variable fallback; replaced simple randomItem helper with bounds-checking getArrayItemOrThrow; added validation guards for job IDs and candidate data existence; applied defensive lookups throughout response generation; aligned database insertions with validated variables; strengthened error messages for invalid configurations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A rabbit hops through validation gates,
Each guard now checks what data waits,
No more blind index, safe and sound,
Our seedlings flourish, tightly bound! 🌱

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is completely missing. The template requires Summary, Type of change, Validation, and DCO sections, but none were provided. Add a complete pull request description following the repository template, including what changed, why it's needed, type of change, validation steps, and DCO sign-off confirmation.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately reflects the main changes: environment variable support (DEMO_PASSWORD) and error handling improvements (validation guards, better error messages, data safety checks).

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/typescript-problems

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

@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: 1

🧹 Nitpick comments (1)
server/scripts/seed.ts (1)

29-36: process.env usage in server/**/*.ts — acceptable exception for a standalone script.

The coding guideline for server/**/*.ts states to use the Zod-validated env import from server/utils/env.ts instead of process.env directly. Since this is a standalone CLI script (run via npx tsx) that bootstraps its own DB connection outside the Nuxt runtime, the shared env utility 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 use process.env.X directly in server code—always import env from server/utils/env.ts which 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).

Comment thread server/scripts/seed.ts
Comment on lines +253 to +256
const candidate = CANDIDATES_DATA[candidateIndex]
if (!candidate) {
return {}
}
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 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.

Suggested change
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.

@railway-app railway-app Bot temporarily deployed to applirank / applirank-pr-25 February 21, 2026 11:05 Destroyed
@JoachimLK JoachimLK requested a review from Copilot February 21, 2026 11:21
@JoachimLK JoachimLK merged commit 45033e7 into main Feb 21, 2026
4 of 5 checks passed
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

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.

Comment thread server/scripts/seed.ts

const DEMO_EMAIL = 'demo@applirank.com'
const DEMO_PASSWORD = 'demo1234'
const DEMO_PASSWORD = process.env.DEMO_PASSWORD ?? 'demo1234'
Copy link

Copilot AI Feb 21, 2026

Choose a reason for hiding this comment

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

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.

Suggested change
const DEMO_PASSWORD = process.env.DEMO_PASSWORD ?? 'demo1234'
const rawDemoPassword = process.env.DEMO_PASSWORD
const DEMO_PASSWORD = rawDemoPassword && rawDemoPassword.trim() !== '' ? rawDemoPassword : 'demo1234'

Copilot uses AI. Check for mistakes.
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.

3 participants