@venizia/ignis-docs 0.0.1-8 → 0.0.1-9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/package.json +1 -1
  2. package/wiki/changelogs/2025-12-17-refactor.md +22 -0
  3. package/wiki/changelogs/2025-12-18-performance-optimizations.md +192 -0
  4. package/wiki/changelogs/2025-12-18-repository-validation-security.md +445 -0
  5. package/wiki/changelogs/index.md +22 -0
  6. package/wiki/changelogs/v0.0.1-7-initial-architecture.md +137 -0
  7. package/wiki/changelogs/v0.0.1-8-model-repo-datasource-refactor.md +278 -0
  8. package/wiki/get-started/5-minute-quickstart.md +1 -1
  9. package/wiki/get-started/best-practices/api-usage-examples.md +12 -8
  10. package/wiki/get-started/best-practices/common-pitfalls.md +2 -2
  11. package/wiki/get-started/best-practices/data-modeling.md +14 -20
  12. package/wiki/get-started/building-a-crud-api.md +60 -75
  13. package/wiki/get-started/core-concepts/controllers.md +14 -14
  14. package/wiki/get-started/core-concepts/persistent.md +110 -130
  15. package/wiki/get-started/quickstart.md +1 -1
  16. package/wiki/references/base/controllers.md +40 -16
  17. package/wiki/references/base/datasources.md +195 -33
  18. package/wiki/references/base/dependency-injection.md +5 -5
  19. package/wiki/references/base/models.md +398 -28
  20. package/wiki/references/base/repositories.md +475 -22
  21. package/wiki/references/components/authentication.md +224 -7
  22. package/wiki/references/components/health-check.md +1 -1
  23. package/wiki/references/components/swagger.md +1 -1
  24. package/wiki/references/helpers/inversion.md +8 -3
  25. package/wiki/references/src-details/core.md +6 -5
  26. package/wiki/references/src-details/inversion.md +4 -4
  27. package/wiki/references/utilities/request.md +16 -7
@@ -26,49 +26,151 @@ Fundamental building block wrapping a Drizzle ORM schema.
26
26
  | **Schema Encapsulation** | Holds Drizzle `pgTable` schema for consistent repository access |
27
27
  | **Metadata** | Works with `@model` decorator to mark database entities |
28
28
  | **Schema Generation** | Uses `drizzle-zod` to generate Zod schemas (`SELECT`, `CREATE`, `UPDATE`) |
29
+ | **Static Properties** | Supports static `schema`, `relations`, and `TABLE_NAME` for cleaner syntax |
29
30
  | **Convenience** | Includes `toObject()` and `toJSON()` methods |
30
31
 
31
- ### Class Definition
32
+ ### Definition Patterns
33
+
34
+ `BaseEntity` supports two patterns for defining models:
35
+
36
+ #### Pattern 1: Static Properties (Recommended)
37
+
38
+ Define schema and relations as static properties:
39
+
40
+ ```typescript
41
+ import { pgTable, text } from 'drizzle-orm/pg-core';
42
+ import { BaseEntity, model, generateIdColumnDefs, createRelations } from '@venizia/ignis';
43
+
44
+ // Define table schema
45
+ export const userTable = pgTable('User', {
46
+ ...generateIdColumnDefs({ id: { dataType: 'string' } }),
47
+ name: text('name').notNull(),
48
+ email: text('email').notNull(),
49
+ });
50
+
51
+ // Define relations
52
+ export const userRelations = createRelations({
53
+ source: userTable,
54
+ relations: [],
55
+ });
56
+
57
+ // Entity class with static properties
58
+ @model({ type: 'entity' })
59
+ export class User extends BaseEntity<typeof User.schema> {
60
+ static override schema = userTable;
61
+ static override relations = () => userRelations.definitions;
62
+ static override TABLE_NAME = 'User';
63
+ }
64
+ ```
65
+
66
+ **Benefits:**
67
+ - Schema and relations are auto-resolved by repositories
68
+ - No need to pass `relations` in repository constructor
69
+ - Cleaner, more declarative syntax
70
+
71
+ #### Pattern 2: Constructor-Based (Legacy)
72
+
73
+ Pass schema in constructor:
74
+
75
+ ```typescript
76
+ @model({ type: 'entity' })
77
+ export class User extends BaseEntity<typeof userTable> {
78
+ constructor() {
79
+ super({ name: 'User', schema: userTable });
80
+ }
81
+ }
82
+ ```
83
+
84
+ ### Static Properties
85
+
86
+ | Property | Type | Description |
87
+ |----------|------|-------------|
88
+ | `schema` | `TTableSchemaWithId` | Drizzle table schema defined with `pgTable()` |
89
+ | `relations` | `TValueOrResolver<Array<TRelationConfig>>` | Relation definitions (can be a function for lazy loading) |
90
+ | `TABLE_NAME` | `string \| undefined` | Optional table name (defaults to class name if not set) |
91
+
92
+ ### IEntity Interface
93
+
94
+ Models implementing static properties conform to the `IEntity` interface:
32
95
 
33
96
  ```typescript
34
- import { createSchemaFactory } from 'drizzle-zod';
35
- import { BaseHelper } from '../helpers';
36
- import { SchemaTypes, TSchemaType, TTableSchemaWithId } from './common';
97
+ interface IEntity<Schema extends TTableSchemaWithId = TTableSchemaWithId> {
98
+ TABLE_NAME?: string;
99
+ schema: Schema;
100
+ relations?: TValueOrResolver<Array<TRelationConfig>>;
101
+ }
102
+ ```
103
+
104
+ ### Instance Methods
105
+
106
+ | Method | Description |
107
+ |--------|-------------|
108
+ | `getSchema({ type })` | Get Zod schema for validation (`SELECT`, `CREATE`, `UPDATE`) |
109
+ | `toObject()` | Convert to plain object |
110
+ | `toJSON()` | Convert to JSON string |
37
111
 
38
- export class BaseEntity<Schema extends TTableSchemaWithId = TTableSchemaWithId> extends BaseHelper {
112
+ ### Class Definition
113
+
114
+ ```typescript
115
+ export class BaseEntity<Schema extends TTableSchemaWithId = TTableSchemaWithId>
116
+ extends BaseHelper
117
+ implements IEntity<Schema>
118
+ {
119
+ // Instance properties
39
120
  name: string;
40
121
  schema: Schema;
41
- schemaFactory: ReturnType<typeof createSchemaFactory>;
42
122
 
43
- constructor(opts: { name: string; schema: Schema }) {
44
- super({ scope: opts.name });
45
- this.name = opts.name;
46
- this.schema = opts.schema;
47
- this.schemaFactory = createSchemaFactory();
123
+ // Static properties - override in subclass
124
+ static schema: TTableSchemaWithId;
125
+ static relations?: TValueOrResolver<Array<TRelationConfig>>;
126
+ static TABLE_NAME?: string; // Optional, defaults to class name
127
+
128
+ // Static singleton for schemaFactory - shared across all instances
129
+ // Performance optimization: avoids creating new factory per entity
130
+ private static _schemaFactory?: ReturnType<typeof createSchemaFactory>;
131
+ protected static get schemaFactory(): ReturnType<typeof createSchemaFactory> {
132
+ return (BaseEntity._schemaFactory ??= createSchemaFactory());
133
+ }
134
+
135
+ // Constructor supports both patterns
136
+ constructor(opts?: { name?: string; schema?: Schema }) {
137
+ const ctor = new.target as typeof BaseEntity;
138
+ // Use explicit TABLE_NAME if defined, otherwise fall back to class name
139
+ const name = opts?.name ?? ctor.TABLE_NAME ?? ctor.name;
140
+
141
+ super({ scope: name });
142
+
143
+ this.name = name;
144
+ this.schema = opts?.schema || (ctor.schema as Schema);
48
145
  }
49
146
 
50
147
  getSchema(opts: { type: TSchemaType }) {
148
+ const factory = BaseEntity.schemaFactory; // Uses static singleton
51
149
  switch (opts.type) {
52
- case SchemaTypes.CREATE: {
53
- return this.schemaFactory.createInsertSchema(this.schema);
54
- }
55
- case SchemaTypes.UPDATE: {
56
- return this.schemaFactory.createUpdateSchema(this.schema);
57
- }
58
- case SchemaTypes.SELECT: {
59
- return this.schemaFactory.createSelectSchema(this.schema);
60
- }
61
- default: {
150
+ case SchemaTypes.CREATE:
151
+ return factory.createInsertSchema(this.schema);
152
+ case SchemaTypes.UPDATE:
153
+ return factory.createUpdateSchema(this.schema);
154
+ case SchemaTypes.SELECT:
155
+ return factory.createSelectSchema(this.schema);
156
+ default:
62
157
  throw getError({
63
- message: `[getSchema] Invalid schema type | type: ${opts.type} | valid: ${[SchemaTypes.SELECT, SchemaTypes.UPDATE, SchemaTypes.CREATE]}`,
158
+ message: `[getSchema] Invalid schema type | type: ${opts.type}`,
64
159
  });
65
- }
66
160
  }
67
161
  }
162
+
163
+ toObject() {
164
+ return { ...this };
165
+ }
166
+
167
+ toJSON() {
168
+ return this.toObject();
169
+ }
68
170
  }
69
171
  ```
70
172
 
71
- When you define a model in your application, you extend `BaseEntity`, passing your Drizzle table schema to the `super` constructor.
173
+ **Performance Note:** The `schemaFactory` is implemented as a static lazy singleton, meaning it's created once and shared across all `BaseEntity` instances. This avoids the overhead of creating a new `drizzle-zod` schema factory for every entity instantiation.
72
174
 
73
175
  ## Schema Enrichers
74
176
 
@@ -107,6 +209,161 @@ export const myTable = pgTable('MyTable', {
107
209
 
108
210
  ## Detailed Enricher Reference
109
211
 
212
+ ### `generateIdColumnDefs`
213
+
214
+ Adds a primary key `id` column with support for string UUID, integer, or big integer types with full TypeScript type inference.
215
+
216
+ **File:** `packages/core/src/base/models/enrichers/id.enricher.ts`
217
+
218
+ #### Signature
219
+
220
+ ```typescript
221
+ generateIdColumnDefs<Opts extends TIdEnricherOptions | undefined>(
222
+ opts?: Opts,
223
+ ): TIdColumnDef<Opts>
224
+ ```
225
+
226
+ #### Options (`TIdEnricherOptions`)
227
+
228
+ ```typescript
229
+ type TIdEnricherOptions = {
230
+ id?: { columnName?: string } & (
231
+ | { dataType: 'string' }
232
+ | {
233
+ dataType: 'number';
234
+ sequenceOptions?: PgSequenceOptions;
235
+ }
236
+ | {
237
+ dataType: 'big-number';
238
+ numberMode: 'number' | 'bigint'; // Required for big-number
239
+ sequenceOptions?: PgSequenceOptions;
240
+ }
241
+ );
242
+ };
243
+ ```
244
+
245
+ **Default values:**
246
+ - `dataType`: `'number'` (auto-incrementing integer)
247
+ - `columnName`: `'id'`
248
+
249
+ #### Generated Columns
250
+
251
+ | Data Type | Column Type | Constraints | Description |
252
+ |-----------|------------|-------------|-------------|
253
+ | `'string'` | `uuid` | Primary Key, Default: `gen_random_uuid()` | Native PostgreSQL UUID (no extension required) |
254
+ | `'number'` | `integer` | Primary Key, `GENERATED ALWAYS AS IDENTITY` | Auto-incrementing integer |
255
+ | `'big-number'` | `bigint` | Primary Key, `GENERATED ALWAYS AS IDENTITY` | Auto-incrementing big integer (mode: 'number' or 'bigint') |
256
+
257
+ #### Type Inference
258
+
259
+ The function provides **full TypeScript type inference** based on the configuration options:
260
+
261
+ ```typescript
262
+ type TIdColumnDef<Opts extends TIdEnricherOptions | undefined> =
263
+ Opts extends { id: infer IdOpts }
264
+ ? IdOpts extends { dataType: 'string' }
265
+ ? { id: IsPrimaryKey<NotNull<HasDefault<PgUUIDBuilderInitial<'id'>>>> }
266
+ : IdOpts extends { dataType: 'number' }
267
+ ? { id: IsIdentity<IsPrimaryKey<NotNull<PgIntegerBuilderInitial<'id'>>>, 'always'> }
268
+ : IdOpts extends { dataType: 'big-number' }
269
+ ? IdOpts extends { numberMode: 'number' }
270
+ ? { id: IsIdentity<IsPrimaryKey<NotNull<PgBigInt53BuilderInitial<'id'>>>, 'always'> }
271
+ : { id: IsIdentity<IsPrimaryKey<NotNull<PgBigInt64BuilderInitial<'id'>>>, 'always'> }
272
+ : { id: IsIdentity<IsPrimaryKey<NotNull<PgIntegerBuilderInitial<'id'>>>, 'always'> }
273
+ : { id: IsIdentity<IsPrimaryKey<NotNull<PgIntegerBuilderInitial<'id'>>>, 'always'> };
274
+ ```
275
+
276
+ This ensures that TypeScript correctly infers the exact column type based on your configuration.
277
+
278
+ #### Usage Examples
279
+
280
+ **Default (auto-incrementing integer):**
281
+
282
+ ```typescript
283
+ import { pgTable, text } from 'drizzle-orm/pg-core';
284
+ import { generateIdColumnDefs } from '@venizia/ignis';
285
+
286
+ export const myTable = pgTable('MyTable', {
287
+ ...generateIdColumnDefs(),
288
+ name: text('name').notNull(),
289
+ });
290
+
291
+ // Generates: id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY
292
+ ```
293
+
294
+ **UUID-based string ID:**
295
+
296
+ ```typescript
297
+ export const myTable = pgTable('MyTable', {
298
+ ...generateIdColumnDefs({ id: { dataType: 'string' } }),
299
+ name: text('name').notNull(),
300
+ });
301
+
302
+ // Generates: id uuid PRIMARY KEY DEFAULT gen_random_uuid()
303
+ // No extension required - built into PostgreSQL 13+
304
+ ```
305
+
306
+ **Auto-incrementing integer with sequence options:**
307
+
308
+ ```typescript
309
+ export const myTable = pgTable('MyTable', {
310
+ ...generateIdColumnDefs({
311
+ id: {
312
+ dataType: 'number',
313
+ sequenceOptions: { startWith: 1000, increment: 1 },
314
+ },
315
+ }),
316
+ name: text('name').notNull(),
317
+ });
318
+
319
+ // Generates: id integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1000 INCREMENT BY 1)
320
+ ```
321
+
322
+ **Big number with JavaScript number mode (up to 2^53-1):**
323
+
324
+ ```typescript
325
+ export const myTable = pgTable('MyTable', {
326
+ ...generateIdColumnDefs({
327
+ id: {
328
+ dataType: 'big-number',
329
+ numberMode: 'number', // Required field
330
+ sequenceOptions: { startWith: 1, increment: 1 },
331
+ },
332
+ }),
333
+ name: text('name').notNull(),
334
+ });
335
+
336
+ // Generates: id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY
337
+ // Type-safe: Returns PgBigInt53BuilderInitial (safe for JavaScript numbers)
338
+ ```
339
+
340
+ **Big number with BigInt mode (for values > 2^53-1):**
341
+
342
+ ```typescript
343
+ export const myTable = pgTable('MyTable', {
344
+ ...generateIdColumnDefs({
345
+ id: {
346
+ dataType: 'big-number',
347
+ numberMode: 'bigint', // Required field
348
+ sequenceOptions: { startWith: 1, increment: 1 },
349
+ },
350
+ }),
351
+ name: text('name').notNull(),
352
+ });
353
+
354
+ // Generates: id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY
355
+ // Type-safe: Returns PgBigInt64BuilderInitial (requires BigInt in JavaScript)
356
+ ```
357
+
358
+ #### Important Notes
359
+
360
+ - **UUID Type:** When using `dataType: 'string'`, the native PostgreSQL `uuid` type is used with `gen_random_uuid()` - no extension required (built into PostgreSQL 13+). This is more efficient than `text` type (16 bytes vs 36 bytes) and provides better indexing performance.
361
+ - **Type Safety:** The return type is fully inferred based on your options, providing better autocomplete and type checking
362
+ - **Big Number Mode:** For `dataType: 'big-number'`, the `numberMode` field is required to specify whether to use JavaScript `number` (up to 2^53-1) or `bigint` (for larger values)
363
+ - **Sequence Options:** Available for `number` and `big-number` types to customize identity generation behavior
364
+
365
+ ---
366
+
110
367
  ### `generateTzColumnDefs`
111
368
 
112
369
  Adds timestamp columns for tracking entity creation, modification, and soft deletion.
@@ -124,11 +381,15 @@ generateTzColumnDefs(opts?: TTzEnricherOptions): TTzEnricherResult
124
381
  ```typescript
125
382
  type TTzEnricherOptions = {
126
383
  created?: { columnName: string; withTimezone: boolean };
127
- modified?: { enable: boolean; columnName: string; withTimezone: boolean };
128
- deleted?: { enable: boolean; columnName: string; withTimezone: boolean };
384
+ modified?: { enable: false } | { enable?: true; columnName: string; withTimezone: boolean };
385
+ deleted?: { enable: false } | { enable?: true; columnName: string; withTimezone: boolean };
129
386
  };
130
387
  ```
131
388
 
389
+ The `modified` and `deleted` options use a discriminated union pattern:
390
+ - When `enable: false`, no other properties are needed
391
+ - When `enable: true` (or omitted), `columnName` and `withTimezone` are required
392
+
132
393
  **Default values:**
133
394
  - `created`: `{ columnName: 'created_at', withTimezone: true }`
134
395
  - `modified`: `{ enable: true, columnName: 'modified_at', withTimezone: true }`
@@ -257,6 +518,115 @@ type TTzEnricherResult<ColumnDefinitions extends TColumnDefinitions = TColumnDef
257
518
 
258
519
  ---
259
520
 
521
+ ### `generateUserAuditColumnDefs`
522
+
523
+ Adds `createdBy` and `modifiedBy` columns to track which user created or modified a record.
524
+
525
+ **File:** `packages/core/src/base/models/enrichers/user-audit.enricher.ts`
526
+
527
+ #### Signature
528
+
529
+ ```typescript
530
+ generateUserAuditColumnDefs(opts?: TUserAuditEnricherOptions): {
531
+ createdBy: PgIntegerBuilderInitial | PgTextBuilderInitial;
532
+ modifiedBy: PgIntegerBuilderInitial | PgTextBuilderInitial;
533
+ }
534
+ ```
535
+
536
+ #### Options (`TUserAuditEnricherOptions`)
537
+
538
+ ```typescript
539
+ type TUserAuditColumnOpts = {
540
+ dataType: 'string' | 'number'; // Required - type of user ID
541
+ columnName: string; // Column name in database
542
+ };
543
+
544
+ type TUserAuditEnricherOptions = {
545
+ created?: TUserAuditColumnOpts;
546
+ modified?: TUserAuditColumnOpts;
547
+ };
548
+ ```
549
+
550
+ **Default values:**
551
+ - `created`: `{ dataType: 'number', columnName: 'created_by' }`
552
+ - `modified`: `{ dataType: 'number', columnName: 'modified_by' }`
553
+
554
+ #### Generated Columns
555
+
556
+ | Column | Data Type | Column Name | Description |
557
+ |--------|-----------|-------------|-------------|
558
+ | `createdBy` | `integer` or `text` | `created_by` | User ID who created the record |
559
+ | `modifiedBy` | `integer` or `text` | `modified_by` | User ID who last modified the record |
560
+
561
+ #### Validation
562
+
563
+ The enricher validates the `dataType` option and throws an error for invalid values:
564
+
565
+ ```typescript
566
+ // ✅ Valid
567
+ generateUserAuditColumnDefs({ created: { dataType: 'number', columnName: 'created_by' } });
568
+ generateUserAuditColumnDefs({ created: { dataType: 'string', columnName: 'created_by' } });
569
+
570
+ // ❌ Invalid - throws error
571
+ generateUserAuditColumnDefs({ created: { dataType: 'uuid', columnName: 'created_by' } });
572
+ // Error: [enrichUserAudit] Invalid dataType for 'createdBy' | value: uuid | valid: ['number', 'string']
573
+ ```
574
+
575
+ #### Usage Examples
576
+
577
+ **Default (integer user IDs):**
578
+
579
+ ```typescript
580
+ import { pgTable, text } from 'drizzle-orm/pg-core';
581
+ import { generateIdColumnDefs, generateUserAuditColumnDefs } from '@venizia/ignis';
582
+
583
+ export const myTable = pgTable('MyTable', {
584
+ ...generateIdColumnDefs(),
585
+ ...generateUserAuditColumnDefs(),
586
+ name: text('name').notNull(),
587
+ });
588
+
589
+ // Generates:
590
+ // createdBy: integer('created_by')
591
+ // modifiedBy: integer('modified_by')
592
+ ```
593
+
594
+ **String user IDs (UUID):**
595
+
596
+ ```typescript
597
+ export const myTable = pgTable('MyTable', {
598
+ ...generateIdColumnDefs({ id: { dataType: 'string' } }),
599
+ ...generateUserAuditColumnDefs({
600
+ created: { dataType: 'string', columnName: 'created_by' },
601
+ modified: { dataType: 'string', columnName: 'modified_by' },
602
+ }),
603
+ name: text('name').notNull(),
604
+ });
605
+
606
+ // Generates:
607
+ // createdBy: text('created_by')
608
+ // modifiedBy: text('modified_by')
609
+ ```
610
+
611
+ **Custom column names:**
612
+
613
+ ```typescript
614
+ export const myTable = pgTable('MyTable', {
615
+ ...generateIdColumnDefs(),
616
+ ...generateUserAuditColumnDefs({
617
+ created: { dataType: 'number', columnName: 'author_id' },
618
+ modified: { dataType: 'number', columnName: 'editor_id' },
619
+ }),
620
+ name: text('name').notNull(),
621
+ });
622
+
623
+ // Generates:
624
+ // createdBy: integer('author_id')
625
+ // modifiedBy: integer('editor_id')
626
+ ```
627
+
628
+ ---
629
+
260
630
  ## Schema Utilities
261
631
 
262
632
  ### `snakeToCamel`
@@ -325,7 +695,7 @@ console.log(result);
325
695
  **Use case:** API endpoint that accepts snake_case but works with camelCase internally
326
696
 
327
697
  ```typescript
328
- import { BaseController, controller, snakeToCamel } from '@venizia/ignis';
698
+ import { BaseController, controller, snakeToCamel, HTTP } from '@venizia/ignis';
329
699
  import { z } from '@hono/zod-openapi';
330
700
 
331
701
  const createUserSchema = snakeToCamel({
@@ -366,7 +736,7 @@ export class UserController extends BaseController {
366
736
  console.log(data.firstName); // ✅ TypeScript knows this exists
367
737
  console.log(data.first_name); // ❌ TypeScript error
368
738
 
369
- return ctx.json({ success: true });
739
+ return ctx.json({ success: true }, HTTP.ResultCodes.RS_2.Ok);
370
740
  },
371
741
  });
372
742
  }