Skip to content

Commit fdf93cc

Browse files
V2 scaffolding (#18)
* feat: add comprehensive rules for architecture, controllers, services, and development workflows * chore: remove VSCode extensions configuration and clean up settings * chore: update configuration files and enhance middleware structure * chore: remove unused dependencies and session store reference from configuration files * feat: implement server-managed session lifecycle with MongoDB and Redis support * fix: resolve session token hash mismatch by updating hash after final token generation * feat: implement session cleanup functionality with scheduled tasks and user session management * refactor: enhance session management logging and code readability * chore: add AGENTS.md for repository guidelines and project structure documentation * refactor: standardize formatting in ResetPassword email template for improved readability * chore: update OpenAPI generation script to use dotenv for environment configuration and add openapi.yml to .gitignore * chore: remove session management plugin plan document as it is no longer needed * chore: standardize quote style in ESLint configuration for consistency * chore: update new module creation guide to include tbk CLI usage and customization steps * feat: implement seeding system with CLI commands for database management * feat: add CLI commands for module and seeder generation with detailed usage instructions * feat: enhance module and seeder CLI documentation with detailed steps and examples * chore: update configuration references in documentation to reflect changes in env.ts * refactor: optimize file writing in tbk CLI and update import paths for configuration * refactor: standardize quote style in can-access middleware for consistency * refactor: clean up error handling, db call and type definitions in can-access middleware and seed script * feat: implement admin dashboard with CRUD functionality and resource registration * feat: add modal functionality for record creation and editing in admin dashboard * feat: implement file upload functionality in admin dashboard with support for fileFields * refactor: improve code readability and consistency in admin dashboard JavaScript and HTML files * feat: implement profile picture upload functionality with new upload routes and controller * refactor: reorganize healthcheck functionality into modules and update routing * refactor: migrate logger service to observability module and update import paths across the codebase * refactor: replace socket.io setup with a new realtime plugin and update main application initialization * feat: add realtime testing interface with connection management and logging features * feat: add relation lookup endpoint and enhance admin dashboard with relation field handling * feat: enhance admin dashboard with subdocument handling and editor functionality * fix: correct subdocument handling logic in schema introspection utility * refactor: simplify ResponseExtended interface by removing unused locals property * chore: remove outdated documentation files for email service, seeders, and session management * feat: implement new response validation system and update controllers to use typed response helpers * chore: update API documentation paths and enhance frontend styles for consistency * chore: add OpenAPI generation script and update .gitignore to include generated files * feat: add socket testing suite URL to server bootstrap logs * chore: update admin queue references to remove '/admin/' prefix in documentation and code * chore: refine project structure documentation for clarity and add testing guidelines * feat: implement room management features in realtime app, including join, leave, and broadcast functionality * feat: add collapsible panel for custom emit functionality in realtime app * refactor: improve code readability by formatting and organizing JavaScript in admin.js * chore: update OpenAPI generation paths to ensure correct output location and enhance documentation links * chore: update OpenAPI documentation file path to save in public directory * feat: implement recent items feature in admin lookup, displaying recent selections based on user input * feat: implement bulk delete and clear all functionality in admin interface, including UI updates for selection and sorting * feat: add filtering options for event logs in realtime app, including UI elements for enabled listeners and listener selection * feat: add admin authentication and login page * refactor: improve S3 upload implementation with streaming and better error handling * feat: add comprehensive HTTP status codes and improve OpenAPI response definitions * refactor: standardize OpenAPI response schemas across auth, blog, and user modules * refactor: reorganize utilities into focused modules and move error handler to middlewares * refactor: extract admin login JS to separate file and update production config * feat: add Google OAuth redirect URI utility function * fix: google sign in support with zod schema and url builder * chore: update gitignore and PM2 ecosystem configuration * chore: add favicon * fix: script path in ecosystem.config.js * feat: add intelligent port resolver with conflict detection and fallback * refactor: remove unused validation function and clean up S3 upload logic * refactor: enhance src/lib structure * refactor: update email provider integration and improve file storage references * feat: implement multi-provider storage configuration with AWS S3, Cloudflare R2, and local filesystem support * feat: enhance admin file upload handling with local storage provider and improved error logging * feat: implement cache provider abstraction with Redis and in-memory support * refactor: reorganize observability plugin structure and enhance health check routes * refactor: update routing and status code references to use new MagicRouter and plugins structure * refactor: update ESLint configuration and enhance plugin import paths for better module organization * refactor: reorganize import paths and add port resolver utility for enhanced server startup * refactor: improve logging structure in createApp by using child logger for plugin registration * fix: enable authentication guard for admin dashboard in app initialization * refactor: update module registration paths and improve user schema structure * refactor: enhance port availability check by using direct socket connections for improved accuracy (win-fix) * refactor: update seeder registration paths and enhance error handling in middleware * chore: add robots.txt to disallow all web crawlers * feat: add Resend email provider and update email configuration options in .env.sample * refactor: reorganize static asset paths and enhance HTML file references for improved structure * feat: implement queue authentication with login page and session management * feat: add custom CSS and JS injection for BullBoard with logout functionality * style: update BullBoard layout and theme with improved CSS overrides and reposition logout button * feat: add logo asset and enhance BullBoard theme with improved CSS structure * feat: implement TypeScript Backend Toolkit CLI with commands for generating plugins, middleware, modules, and seeders * feat: enhance CLI with options for seeder and factory generation, and introduce introspection utility for model metadata * refactor: remove basicParserPlugin and streamline middleware usage in MagicRouter * chore: update .gitignore to include cursor AI rules * fix: update module registration path in documentation and correct TypeScript SDK path in VSCode settings * feat: add basicparserPlugin for enhanced request parsing and middleware integration * refactor: rename basicparserPlugin to basicParserPlugin for consistency and clarity * docs: update controller guidelines with ResponseExtended pattern - Replace successResponse() with typed ResponseExtended helpers - Add optional chaining for JWT payload (req.user?.sub) - Document two error handling approaches: typed responses vs thrown errors - Update examples to use res.ok?.(), res.created?.(), res.notFound?.() patterns - Remove legacy successResponse() documentation - Add response type annotations to controller signatures * docs: update routing guidelines with formidable integration - Replace multer middleware with formidable integration - Document multipart route configuration with multipart: true - Add comprehensive file upload workflow with zFile() and zFiles() helpers - Include schema validation patterns for file uploads - Update controller examples to access files via req.body (not req.file) - Document MIME_GROUPS and file validation options - Add mixed field (text + files) upload examples * docs: enhance schema guidelines with response type workflow - Add complete response schema workflow section - Document end-to-end type safety from schema to controller - Update naming conventions: camelCase for schemas, PascalCase for types - Add router configuration examples with response schemas - Include controller typing with ResponseExtended - Document available response builders (R.success, R.paginated, etc.) - Remove deprecated zod import patterns, enforce named imports * docs: update service error handling patterns - Document that services ALWAYS throw errors, controllers decide handling - Add decision tree for error handling approaches - Include pattern examples for null returns vs thrown errors - Document permission errors, validation errors, and business logic failures - Add guidance on when to return null vs throw errors - Include unexpected error handling (let bubble up as 500) * chore: update gitignore for development files * docs: rewrite README with AI-optimized development focus - Highlight AI assistant compatibility (Cursor, Windsurf, Claude, ChatGPT) - Document comprehensive AI agent configuration with .cursor/rules/ - Add AI-optimized workflow examples with CLI commands - Restructure architecture section to emphasize plugin-based system - Update key features to include OpenAPI, auth, file upload, queues, realtime - Add comprehensive documentation links and development commands - Include production deployment instructions - Modernize formatting and add contribution guidelines * docs: developer-first README, highlight Artisan-like CLI, remove emojis - Clarify intent (beginner→expert) and predictable structure for tools without guesswork - Highlight auto-generated admin dashboard, OpenAPI docs, plugin system - Add dedicated CLI section; switch examples to 'pnpm tbk' - Remove emojis; clean anchors for consistency - Replace webp logo with png and update references for consistent rendering Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> * docs: update module creation instructions and enhance MongoDB ID validation - Add recommended command for generating modules using pnpm tbk - Specify the main app file path for router registration in module creation output - Introduce zMongoId for improved MongoDB ObjectId validation with customizable error messages - Update common schema to utilize zMongoId for ID validation * docs: add CLAUDE.md for comprehensive project guidance - Introduce CLAUDE.md to provide detailed instructions for using the TypeScript Backend Toolkit - Outline project overview, common commands, critical architecture patterns, and module structure - Include guidelines for response schemas, validation with Zod, and error handling - Document plugin system, session management, and environment configuration - Emphasize the importance of using the CLI for module creation and maintaining consistency * docs: update module generation command in CLAUDE.md - Simplify the command for generating modules by removing the path specification - Ensure clarity in instructions for scaffolding project files following established patterns * docs: add create-module and create-seeder commands for module scaffolding - Introduce create-module.md to guide users in generating a fully-typed module with necessary files and integration steps. - Add create-seeder.md to assist in creating seeders and factories for populating test data, including registration and execution instructions. - Update .gitignore to remove the .claude directory from tracking. * docs: add NEXT_STEPS and SCAFFOLDING_SUMMARY for project progression - Introduce NEXT_STEPS.md to outline upcoming tasks including documentation and beta testing. - Add SCAFFOLDING_SUMMARY.md to summarize the completion of Phase 1 and readiness for Phase 2. - Update pnpm-lock.yaml and pnpm-workspace.yaml for package management consistency. - Enhance README.md with installation instructions and environment configuration. - Introduce new files in create-tbk-app package for project scaffolding, including configuration, templates, and utility functions. * feat: complete Phase 1 and Phase 2 of project scaffolding - Finalize Phase 1 and Phase 2 Week 1-3 tasks, ensuring all three presets (minimal, standard, full) are functional and generate successfully. - Extract and templatize approximately 4500 lines of code for improved maintainability. - Update NEXT_STEPS.md to reflect the completion of major milestones and outline future tasks. - Introduce new files and templates for admin and authentication modules, enhancing project structure and functionality. - Remove outdated test-minimal files to streamline the project. * chore: update package metadata and improve documentation links - Set author information in package.json for better attribution. - Add repository, homepage, and bugs URLs to package.json for enhanced project visibility. - Update README.md with direct links to the main repository, documentation, and issue reporting for user convenience. - Modify prompts.ts to ensure type safety by casting to 'any'. - Update config.types.ts to make googleOAuth optional, improving flexibility in project configuration. - Adjust template.engine.ts to provide a default value for AUTH_GOOGLE_OAUTH, enhancing robustness. --------- Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
1 parent e0c806a commit fdf93cc

File tree

337 files changed

+43099
-2920
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

337 files changed

+43099
-2920
lines changed

.claude/commands/create-module.md

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
---
2+
description: Scaffold a fully-typed module with controller, service, router, schema, and model files
3+
argument-hint: <moduleName> [--path <apiPath>]
4+
allowed-tools: Bash, Read, Edit
5+
model: claude-sonnet-4-5
6+
---
7+
8+
# Create Module
9+
10+
Generate a complete module with all required files and wire it into the application.
11+
12+
## Task
13+
14+
**Arguments:**
15+
- `$1` (required): module name (e.g., `product`, `payment`)
16+
- `$2` (optional): API path flag `--path`
17+
- `$3` (optional): API path value (e.g., `/api/v1`); defaults to `/api`
18+
19+
**Module Name:** `$1`
20+
21+
1. **Generate module files**
22+
23+
Run the generator command:
24+
```bash
25+
pnpm tbk generate:module $1 $2 $3
26+
```
27+
28+
This creates:
29+
30+
- `src/modules/<moduleName>/<moduleName>.dto.ts`
31+
- `src/modules/<moduleName>/<moduleName>.model.ts`
32+
- `src/modules/<moduleName>/<moduleName>.schema.ts`
33+
- `src/modules/<moduleName>/<moduleName>.services.ts`
34+
- `src/modules/<moduleName>/<moduleName>.controller.ts`
35+
- `src/modules/<moduleName>/<moduleName>.router.ts` (exports `<MODULE>_ROUTER_ROOT` and default router)
36+
37+
2. **Register router in routes**
38+
39+
Read `src/routes/routes.ts` and add the router registration:
40+
41+
- Add import at top with other module imports
42+
- Add `router.use()` call with other registrations
43+
- Use camelCase for router variable name
44+
- Use UPPER_SNAKE_CASE for the router root constant
45+
46+
3. **Rebuild OpenAPI documentation**
47+
48+
```bash
49+
pnpm openapi
50+
```
51+
52+
Auto-generates Swagger from MagicRouter + Zod schemas.
53+
54+
4. **Typecheck and lint**
55+
56+
```bash
57+
pnpm typecheck && pnpm lint
58+
```
59+
60+
5. **Register with admin dashboard** (optional)
61+
62+
Ask the user if they want to add this module to the admin panel.
63+
64+
If yes, read and edit `src/plugins/admin/registry.ts` to add the resource.
65+
66+
6. **Optional: Create seeder and factory**
67+
68+
Ask the user if they need test data generation for this module.
69+
70+
If yes, run:
71+
```bash
72+
pnpm tbk make:factory $1/$(echo $1 | sed 's/.*/\u&/')
73+
pnpm tbk make:seeder $1/$(echo $1 | sed 's/.*/\u&/')
74+
```
75+
76+
## Verification
77+
78+
After completing all steps, verify:
79+
80+
1. Module files exist in `src/modules/$1/`
81+
2. Router is registered in `src/routes/routes.ts`
82+
3. OpenAPI spec regenerated successfully
83+
4. No type errors or lint warnings
84+
5. Admin panel configured (if requested)
85+
86+
Report success with the module name and available endpoints.
87+
88+
## Context
89+
90+
- All routes use MagicRouter (NOT plain Express)
91+
- Response schemas use `R.success()`, `R.paginated()`, `R.error()` builders
92+
- Controllers use `ResponseExtended<T>` for type-safe responses
93+
- Update `src/config/env.ts` and `.env.sample` if new env vars are needed

.claude/commands/create-seeder.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
---
2+
description: Scaffold a seeder and factory for a module to populate test data
3+
argument-hint: <module>/<Name>
4+
allowed-tools: Bash, Read, Edit
5+
model: claude-sonnet-4-5
6+
---
7+
8+
# Create Seeder & Factory
9+
10+
Generate a factory and seeder for an existing module, register it, and optionally run it.
11+
12+
## Task
13+
14+
**Arguments:**
15+
- `$1` (required): module/name path (e.g., `user/User`, `product/Product`)
16+
17+
Parse `$1` to extract:
18+
- Module name: everything before `/`
19+
- Entity name: everything after `/`
20+
21+
## Steps
22+
23+
1. **Generate factory and seeder files**
24+
25+
Run both commands:
26+
```bash
27+
pnpm tbk make:factory $1 && pnpm tbk make:seeder $1
28+
```
29+
30+
This creates:
31+
- `src/modules/{module}/factories/{name}.factory.ts` (exports camelCase factory)
32+
- `src/modules/{module}/seeders/{Name}Seeder.ts`
33+
34+
2. **Implement seeder logic**
35+
36+
Read the generated seeder file and verify it:
37+
- Imports the correct factory
38+
- Imports the module's model
39+
- Has proper collection name in config
40+
- Uses factory.build() correctly
41+
42+
If the seeder needs customization, ask the user about:
43+
- Number of records to generate (default: 10)
44+
- Any specific field overrides needed
45+
- Dependencies on other seeders
46+
47+
3. **Register seeder**
48+
49+
Read `src/seeders/registry.ts` and add the new seeder to the array:
50+
- Import the seeder class
51+
- Add it to the `seeders` export array
52+
53+
4. **Run seeders**
54+
55+
Ask the user if they want to run the seeder now.
56+
57+
If yes, offer options:
58+
- Dry run first (recommended): `pnpm tbk seed --dry-run --only {Name}Seeder`
59+
- Run for real: `pnpm tbk seed --only {Name}Seeder`
60+
- Fresh run (drops collection): `pnpm tbk seed --fresh --only {Name}Seeder`
61+
62+
Run the selected command.
63+
64+
## Verification
65+
66+
After completing all steps, verify:
67+
68+
1. Factory file exists with `build()` method
69+
2. Seeder file exists with correct imports
70+
3. Seeder registered in `src/seeders/registry.ts`
71+
4. Dry run executes without errors
72+
5. Actual seeding creates expected records (if run)
73+
74+
Report success with the seeder name and record count.
75+
76+
## Context
77+
78+
- Factories export `{camelName}Factory` with a `build(i, overrides)` method
79+
- Seeders use `ctx.refs.set()` and `ctx.refs.get()` to share data between seeders
80+
- MongoDB must be running before seeding (`docker compose up -d`)

.claude/settings.local.json

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
{
2+
"permissions": {
3+
"allow": [
4+
"Bash(tree:*)",
5+
"Bash(pnpm build:*)",
6+
"Bash(node dist/cli.js test-minimal:*)",
7+
"Bash(node bin/index.js:*)",
8+
"Bash(node -e \"import { pathExists } from ''./dist/cli.js''; console.log(await pathExists(''templates''));\")",
9+
"Bash(test:*)",
10+
"Bash(/dev/null)",
11+
"Bash(pnpm install:*)",
12+
"Bash(pnpm typecheck:*)",
13+
"Bash(xargs:*)",
14+
"Bash(if [ -d test-minimal ])",
15+
"Bash(then rm -rf test-minimal)",
16+
"Bash(fi)",
17+
"Bash(node packages/create-tbk-app/dist/cli.js:*)",
18+
"Bash(for file in \"c:\\Users\\themuneebh\\repos\\typescript-backend-toolkit\\packages\\create-tbk-app\\templates\\auth\\src\\modules\\auth\\auth.service.ts.hbs\" \"c:\\Users\\themuneebh\\repos\\typescript-backend-toolkit\\packages\\create-tbk-app\\templates\\auth\\src\\modules\\auth\\auth.controller.ts.hbs\" \"c:\\Users\\themuneebh\\repos\\typescript-backend-toolkit\\packages\\create-tbk-app\\templates\\auth\\src\\modules\\auth\\auth.router.ts.hbs\" \"c:\\Users\\themuneebh\\repos\\typescript-backend-toolkit\\packages\\create-tbk-app\\templates\\auth\\src\\plugins\\auth\\index.ts.hbs\" \"c:\\Users\\themuneebh\\repos\\typescript-backend-toolkit\\packages\\create-tbk-app\\templates\\auth\\src\\middlewares\\extract-jwt.ts.hbs\")",
19+
"Bash(do)",
20+
"Bash(done)",
21+
"Bash(if [ -d test-standard-jwt ])",
22+
"Bash(then rm -rf test-standard-jwt)",
23+
"Bash(node dist/cli.js:*)",
24+
"Bash(npx tsc:*)",
25+
"Bash(node -e:*)",
26+
"Bash(cat:*)"
27+
],
28+
"deny": [],
29+
"ask": []
30+
}
31+
}

.cursor/commands/create-module.md

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
# Create a new module (tbk CLI)
2+
3+
## Overview
4+
5+
Scaffold a fully-typed module with controller, service, router, schema, and model files, then wire it into the application routing system.
6+
7+
## Inputs
8+
9+
- **moduleName**: module folder/name in `src/modules/` (e.g., `product`)
10+
- **apiPath**: optional API root path; defaults to `/api` (e.g., `/api/v1`)
11+
12+
## Steps
13+
14+
1. **Generate module files**
15+
16+
```bash
17+
pnpm tbk generate:module <moduleName> --path <apiPath>
18+
```
19+
20+
Examples:
21+
22+
```bash
23+
pnpm tbk generate:module product (recommended)
24+
pnpm tbk generate:module product --path /api
25+
pnpm tbk generate:module product --path /api/v1
26+
```
27+
28+
This creates:
29+
30+
- `src/modules/<moduleName>/<moduleName>.dto.ts`
31+
- `src/modules/<moduleName>/<moduleName>.model.ts`
32+
- `src/modules/<moduleName>/<moduleName>.schema.ts`
33+
- `src/modules/<moduleName>/<moduleName>.services.ts`
34+
- `src/modules/<moduleName>/<moduleName>.controller.ts`
35+
- `src/modules/<moduleName>/<moduleName>.router.ts` (exports `<MODULE>_ROUTER_ROOT` and default router)
36+
37+
2. **Register router in routes**
38+
Add an import and `router.use(...)` in `src/routes/routes.ts`:
39+
40+
```ts
41+
// add with other imports
42+
import <moduleName>Router, { <MODULE_NAME>_ROUTER_ROOT } from '../modules/<moduleName>/<moduleName>.router';
43+
44+
// add with other router.use calls
45+
router.use(<MODULE_NAME>_ROUTER_ROOT, <moduleName>Router);
46+
```
47+
48+
- Replace `<moduleName>` with your actual module name (e.g., `product`)
49+
- Replace `<MODULE_NAME>` with the uppercased module name (e.g., `PRODUCT`)
50+
51+
Example for `product`:
52+
53+
```ts
54+
import productRouter, {
55+
PRODUCT_ROUTER_ROOT,
56+
} from '../modules/product/product.router';
57+
router.use(PRODUCT_ROUTER_ROOT, productRouter);
58+
```
59+
60+
3. **Rebuild OpenAPI documentation**
61+
62+
```bash
63+
pnpm openapi
64+
```
65+
66+
Auto-generates Swagger from MagicRouter + Zod schemas.
67+
68+
4. **Typecheck and lint**
69+
70+
```bash
71+
pnpm typecheck && pnpm lint
72+
```
73+
74+
5. **Register with admin dashboard** (if needed)
75+
76+
Add your module to `src/plugins/admin/registry.ts`:
77+
78+
```ts
79+
import <ModuleName>Model from '../modules/<moduleName>/<moduleName>.model';
80+
81+
export const adminResources: AdminResource[] = [
82+
// ... existing resources
83+
{
84+
name: '<moduleName>s',
85+
label: '<ModuleName>s',
86+
model: <ModuleName>Model,
87+
readOnlyFields: ['_id', 'createdAt', 'updatedAt']
88+
},
89+
];
90+
```
91+
92+
- Replace `<moduleName>` with your module name (e.g., `product`)
93+
- Replace `<ModuleName>` with PascalCase version (e.g., `Product`)
94+
- Adjust `readOnlyFields` as needed for your module
95+
96+
6. **Optional: Create seeder and factory**
97+
```bash
98+
pnpm tbk make:factory <moduleName>/<Name>
99+
pnpm tbk make:seeder <moduleName>/<Name>
100+
```
101+
102+
## Module Checklist
103+
104+
- [ ] Module files generated successfully
105+
- [ ] Router registered in `src/routes/routes.ts`
106+
- [ ] Module registered in admin dashboard (`src/plugins/admin/registry.ts`) (if needed)
107+
- [ ] OpenAPI documentation rebuilt
108+
- [ ] Code passes typecheck and lint
109+
- [ ] Environment variables added to `src/config/env.ts` and `.env.sample` (if needed)
110+
- [ ] Committed with Conventional Commits format
111+
112+
## Response Validation
113+
114+
Generated modules automatically use the **response validation system**:
115+
116+
- **Response schemas** defined in schema files using `R.success()`, `R.paginated()`, `R.error()` helpers
117+
- **Response types** exported from schema files for type-safe controllers
118+
- **Typed response helpers** (`res.ok()`, `res.created()`, `res.noContent()`) in controllers
119+
- **OpenAPI documentation** includes accurate per-status response schemas
120+
- **Runtime validation** ensures responses match schemas (configurable via `RESPONSE_VALIDATION` env var)
121+
122+
### Example from generated code:
123+
124+
**Schema file (module.schema.ts):**
125+
126+
```typescript
127+
import { R } from '../../openapi/response.builders';
128+
import { itemOutSchema } from './item.dto';
129+
130+
// Response schemas
131+
export const getItemsResponseSchema = R.paginated(itemOutSchema);
132+
export const createItemResponseSchema = R.success(itemOutSchema);
133+
134+
// Response types
135+
export type GetItemsResponseSchema = z.infer<typeof getItemsResponseSchema>;
136+
export type CreateItemResponseSchema = z.infer<typeof createItemResponseSchema>;
137+
```
138+
139+
**Router (module.router.ts):**
140+
141+
```typescript
142+
import { getItemsResponseSchema } from './module.schema';
143+
144+
router.get(
145+
'/',
146+
{
147+
requestType: { query: getItemsSchema },
148+
responses: {
149+
200: getItemsResponseSchema,
150+
},
151+
},
152+
canAccess(),
153+
handleGetItems,
154+
);
155+
```
156+
157+
**Controller (module.controller.ts):**
158+
159+
```typescript
160+
import type { ResponseExtended } from '../../types';
161+
import type { GetItemsResponseSchema } from './module.schema';
162+
163+
export const handleGetItems = async (
164+
req: Request<unknown, unknown, unknown, GetItemsSchemaType>,
165+
res: ResponseExtended<GetItemsResponseSchema>,
166+
) => {
167+
const { results, paginatorInfo } = await getItems(req.query);
168+
return res.ok?.({
169+
success: true,
170+
data: { items: results, paginator: paginatorInfo },
171+
});
172+
};
173+
```
174+
175+
## Notes
176+
177+
- Routes must use `MagicRouter`; the generator already sets this up and defines `<MODULE>_ROUTER_ROOT` using the `--path` you pass
178+
- Generated code uses **new response validation pattern** - see `docs/RESPONSE_VALIDATION.md` for details
179+
- Legacy `successResponse()` still works but new pattern is recommended
180+
- Keep environment configs valid, and update `src/config/env.ts` and `.env.sample` if you introduce new variables
181+
- Commit with Conventional Commits (e.g., `feat(<moduleName>): add <feature>`)

0 commit comments

Comments
 (0)