Skip to content

chore: Auto-generate schema type aliases alongside API schema#3580

Open
Anty0 wants to merge 2 commits intomainfrom
jirikuchynka/auto-generate-schema-types
Open

chore: Auto-generate schema type aliases alongside API schema#3580
Anty0 wants to merge 2 commits intomainfrom
jirikuchynka/auto-generate-schema-types

Conversation

@Anty0
Copy link
Copy Markdown
Collaborator

@Anty0 Anty0 commented Mar 31, 2026

I wanted to add something like this for a while. Premise:

// What if do:
import type { QaIssueModel } from 'tg.service/apiSchemaTypes.generated'

// Instead of:
import { components } from 'tg.service/apiSchema.generated';
type QaIssueModel = components['schemas']['QaIssueModel']

Summary

  • Extends webapp/scripts/generate-schemas.js to produce a companion *Types.generated.ts file alongside the existing apiSchema.generated.ts
  • The types file re-exports all OpenAPI schema types as named exports, enabling import type { QaIssueModel } from 'tg.service/apiSchemaTypes.generated' instead of type QaIssueModel = components['schemas']['QaIssueModel']
  • Schema names are fetched directly from the OpenAPI JSON spec (no regex parsing)

Summary by CodeRabbit

  • New Features

    • Automatically generated TypeScript type aliases provide type-safe access to all API schema definitions, improving IDE support and compile-time validation.
  • Chores

    • Improved schema generation tooling: generation now streams progress output, validates fetched OpenAPI documents, and produces an additional types file for consistent schema aliases.

Extends generate-schemas.js to produce a companion *Types.generated.ts
file that re-exports all OpenAPI schema types as named exports. This
allows importing types directly (e.g. `import type { QaIssueModel }
from 'tg.service/apiSchemaTypes.generated'`) instead of extracting them
from the components interface in every file.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 31, 2026

📝 Walkthrough

Walkthrough

Replaces async command execution with synchronous runs in the schema generator, adds fetching and validation of the OpenAPI JSON (specUrl), derives sorted schema names, writes a new generated type-alias file, improves CLI error messaging, and changes execution order to generate schemas then types, then log completion.

Changes

Cohort / File(s) Summary
Schema generation script
webapp/scripts/generate-schemas.js
Switched exec(..., callback) to execSync(...) with stdio: 'inherit', logged the executed command, added specUrl reuse, improved invalid-argument error text, introduced generateSchemaTypes() to fetch/validate the OpenAPI JSON, extract sorted components.schemas keys, and write Types.generated.ts; updated control flow to run schema generation then type generation.
Generated schema type aliases
webapp/src/service/apiSchemaTypes.generated.ts
New auto-generated file exporting ~380+ TypeScript aliases mapping local type names to components['schemas'][<SchemaName>] (no runtime logic; type-level re-exports for compile-time usage).

Sequence Diagram(s)

sequenceDiagram
    participant Script as Schema Generation Script
    participant Tool as openapi-typescript Tool
    participant Spec as OpenAPI Spec Server
    participant FS as File System

    Script->>Script: prepare command & specUrl
    Script->>Tool: run openapi-typescript (sync, stdio: inherit)
    Tool->>FS: write `apiSchema.generated.ts`
    Script->>Spec: fetch OpenAPI JSON from specUrl
    Spec-->>Script: return OpenAPI JSON (response.ok)
    Script->>Script: validate components.schemas exists & extract keys
    Script->>Script: sort schema names & build type aliases
    Script->>FS: write `apiSchemaTypes.generated.ts`
    Script->>Script: log "Schema generation completed."
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • JanCizmar
  • dkrizan

Poem

🐰
Hop, I fetched the spec at dawn,
names sorted, types now drawn—
aliases stitched, files all bright,
scripts ran sync and logged the light.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: auto-generating schema type aliases as a companion to the existing API schema generation.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ 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 jirikuchynka/auto-generate-schema-types

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

@Anty0 Anty0 changed the title Auto-generate schema type aliases alongside API schema chore: Auto-generate schema type aliases alongside API schema Mar 31, 2026
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: 2

🧹 Nitpick comments (1)
webapp/scripts/generate-schemas.js (1)

38-79: Refactor to top-down flow to satisfy the Stepdown Rule.

The high-level orchestration (Lines 77-79) appears after helper details. Prefer a main() defined near the top, with helper functions below it.

As per coding guidelines **/*.{ts,tsx,js,jsx,kt,kts}: The Stepdown Rule... Functions should be ordered so that a caller appears before the functions it calls.

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

In `@webapp/scripts/generate-schemas.js` around lines 38 - 79, Define a top-level
async function main() near the top of the file that orchestrates the flow (call
generateSchema(); await generateSchemaTypes(); console.log('Schema generation
completed.')), move the helper functions generateSchema and generateSchemaTypes
below it, and replace the existing top-level calls (generateSchema(); await
generateSchemaTypes(); console.log(...)) with a single call to main(); this
removes the top-level await and satisfies the Stepdown Rule so callers (main)
appear before the functions they invoke (generateSchema, generateSchemaTypes).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@webapp/scripts/generate-schemas.js`:
- Line 65: The emitted import uses a relative path string `import type {
components } from './${schemaBasename}';` in generate-schemas.js; change the
template to use the Tolgee alias form `tg.service/${schemaBasename}` so
generated files use the repo's path alias. Update the string/template that
constructs that import (where `schemaBasename` is interpolated) in
generate-schemas.js to emit `tg.service/${schemaBasename}` instead of a leading
"./", and ensure any surrounding code that writes the import line still formats
correctly for TypeScript type imports.
- Around line 51-53: The code assumes spec.components.schemas exists before
calling Object.keys, which causes a generic crash when missing; update the logic
around spec (the variable parsed from response.json) to guard that
spec.components and spec.components.schemas are present and are objects before
calling Object.keys, and if not, throw or log a clear, fast-fail error message
referencing spec.components.schemas (e.g., in the block that assigns
schemaNames) so the script exits with an explicit message instead of a generic
runtime error.

---

Nitpick comments:
In `@webapp/scripts/generate-schemas.js`:
- Around line 38-79: Define a top-level async function main() near the top of
the file that orchestrates the flow (call generateSchema(); await
generateSchemaTypes(); console.log('Schema generation completed.')), move the
helper functions generateSchema and generateSchemaTypes below it, and replace
the existing top-level calls (generateSchema(); await generateSchemaTypes();
console.log(...)) with a single call to main(); this removes the top-level await
and satisfies the Stepdown Rule so callers (main) appear before the functions
they invoke (generateSchema, generateSchemaTypes).
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f2e2bbcf-f7c6-4818-b7db-9cba4c32c20d

📥 Commits

Reviewing files that changed from the base of the PR and between ab5ae03 and 5acf26f.

📒 Files selected for processing (2)
  • webapp/scripts/generate-schemas.js
  • webapp/src/service/apiSchemaTypes.generated.ts

@Anty0 Anty0 requested review from JanCizmar, bdshadow and dkrizan April 1, 2026 12:19
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.

2 participants