@elysiumjs/core 0.6.0 → 0.7.0

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.
@@ -1,175 +0,0 @@
1
- import type { PgColumnBuilderBase } from 'drizzle-orm/pg-core';
2
- import type { Class } from 'type-fest';
3
- import type { DatabaseConnection } from './database';
4
- import type { ModelClass } from './model';
5
- /**
6
- * Database's primary column type.
7
- * @author Axel Nana <axel.nana@workbud.com>
8
- */
9
- export type IdType = number | string;
10
- /**
11
- * Interface of a repository.
12
- * @author Axel Nana <axel.nana@workbud.com>
13
- * @template TModel The type of the model class wrapped by the repository.
14
- * @template TId The primary column type.
15
- * @template TColumnsMap The table columns config.
16
- */
17
- export interface RepositoryInterface<TModel extends ModelClass<TTableName, TColumnsMap>, TId extends IdType = string, TTableName extends string = TModel extends ModelClass<infer TTableName, infer _> ? TTableName : string, TColumnsMap extends Record<string, PgColumnBuilderBase> = TModel extends ModelClass<TTableName, infer TColumnsMap> ? TColumnsMap : Record<string, PgColumnBuilderBase>> {
18
- /**
19
- * Retrieves all the records in the database.
20
- * @returns All the records in the database.
21
- */
22
- all(): Promise<TModel['$inferSelect'][]>;
23
- /**
24
- * Retrieves a record by its id.
25
- * @param id The id of the record to retrieve.
26
- * @returns The record with the given id.
27
- */
28
- find(id: TId): Promise<TModel['$inferSelect'] | null>;
29
- /**
30
- * Inserts a new record in the database.
31
- * @param data The data to insert.
32
- * @returns The inserted record.
33
- */
34
- insert(data: TModel['$inferInsert']): Promise<TModel['$inferSelect']>;
35
- /**
36
- * Updates a record in the database.
37
- * @param id The id of the record to update.
38
- * @param data The data to update.
39
- * @returns The updated record.
40
- */
41
- update(id: TId, data: TModel['$inferUpdate']): Promise<TModel['$inferSelect']>;
42
- /**
43
- * Updates all the records in the database.
44
- * @param data The data to update.
45
- * @returns The updated records.
46
- */
47
- updateAll(data: TModel['$inferUpdate']): Promise<TModel['$inferSelect'][]>;
48
- /**
49
- * Deletes a record from the database.
50
- * @param id The ID of the record to delete.
51
- * @returns The deleted record.
52
- */
53
- delete(id: TId): Promise<TModel['$inferSelect']>;
54
- /**
55
- * Deletes all the records from the database.
56
- * @returns All the records in the database.
57
- */
58
- deleteAll(): Promise<TModel['$inferSelect'][]>;
59
- /**
60
- * Checks if a record exists in the database.
61
- * @param id The ID of the record to check.
62
- * @returns True if the record exists, false otherwise.
63
- */
64
- exists(id: TId): Promise<boolean>;
65
- }
66
- /**
67
- * Type of a repository class.
68
- * @author Axel Nana <axel.nana@workbud.com>
69
- * @template TModel The type of the model class wrapped by the repository.
70
- * @template TId The primary column type.
71
- * @template TColumnsMap The table columns config.
72
- */
73
- export type RepositoryClass<TModel extends ModelClass<TTableName, TColumnsMap>, TId extends IdType = string, TTableName extends string = TModel extends ModelClass<infer TTableName, infer _> ? TTableName : string, TColumnsMap extends Record<string, PgColumnBuilderBase> = TModel extends ModelClass<TTableName, infer TColumnsMap> ? TColumnsMap : Record<string, PgColumnBuilderBase>> = Class<RepositoryInterface<TModel, TId, TTableName, TColumnsMap>> & {
74
- /**
75
- * The drizzle's table schema wrapped by the repository.
76
- */
77
- readonly Model: TModel;
78
- /**
79
- * The database connection name to use in the repository.
80
- *
81
- * Update this value to change the database connection used by this repository.
82
- */
83
- readonly connection: string;
84
- };
85
- /**
86
- * Mixin used to create a new repository class over a model.
87
- * @author Axel Nana <axel.nana@workbud.com>
88
- * @template TModel The type of the model class wrapped by the repository.
89
- * @template TId The primary column type.
90
- * @template TColumnsMap The table columns config.
91
- * @template model The model class wrapped by the repository.
92
- */
93
- export declare const Repository: <TModel extends ModelClass<TTableName, TColumnsMap>, TId extends IdType = string, TTableName extends string = TModel extends ModelClass<infer TTableName_1, infer _> ? TTableName_1 : string, TColumnsMap extends Record<string, PgColumnBuilderBase> = TModel extends ModelClass<TTableName, infer TColumnsMap_1> ? TColumnsMap_1 : Record<string, PgColumnBuilderBase>>(model: TModel) => {
94
- new (): {
95
- /**
96
- * The database connection used by this repository.
97
- */
98
- get db(): DatabaseConnection;
99
- /**
100
- * Retrieves all the records in the database.
101
- * @returns All the records in the database.
102
- */
103
- all(): Promise<TModel["$inferSelect"][]>;
104
- /**
105
- * Get a paginated subset of the records in the database.
106
- * @param page The page number to retrieve.
107
- * @param count The number of records to retrieve per page.
108
- * @returns A paginated response containing the records and the total number of records.
109
- */
110
- paginate(count: number, page?: number): Promise<{
111
- page: number;
112
- data: TModel["$inferSelect"][];
113
- total: number;
114
- }>;
115
- /**
116
- * Retrieves a record by its id.
117
- * @param id The id of the record to retrieve.
118
- * @returns The record with the given id.
119
- */
120
- find(id: TId): Promise<TModel["$inferSelect"] | null>;
121
- /**
122
- * Finds the first record with a column matching the given value.
123
- * @param column The column to filter by.
124
- * @param value The value the column should match.
125
- * @returns The first record with a column matching the given value.
126
- */
127
- findBy<TKey extends keyof TModel["$inferSelect"]>(column: TKey, value: TModel["$inferSelect"][TKey]): Promise<TModel["$inferSelect"] | null>;
128
- /**
129
- * Inserts a new record in the database.
130
- * @param data The data to insert.
131
- * @returns The inserted record.
132
- */
133
- insert(data: TModel["$inferInsert"]): Promise<TModel["$inferSelect"]>;
134
- /**
135
- * Updates a record in the database.
136
- * @param id The id of the record to update.
137
- * @param data The data to update.
138
- * @returns The updated record.
139
- */
140
- update(id: TId, data: TModel["$inferUpdate"]): Promise<TModel["$inferSelect"]>;
141
- /**
142
- * Updates all the records in the database.
143
- * @param data The data to update.
144
- * @returns The updated records.
145
- */
146
- updateAll(data: TModel["$inferUpdate"]): Promise<TModel["$inferSelect"][]>;
147
- /**
148
- * Deletes a record from the database.
149
- * @param id The ID of the record to delete.
150
- * @returns The deleted record.
151
- */
152
- delete(id: TId): Promise<TModel["$inferSelect"]>;
153
- /**
154
- * Deletes all the records from the database.
155
- * @returns All the records in the database.
156
- */
157
- deleteAll(): Promise<TModel["$inferSelect"][]>;
158
- /**
159
- * Checks if a record exists in the database.
160
- * @param id The ID of the record to check.
161
- * @returns True if the record exists, false otherwise.
162
- */
163
- exists(id: TId): Promise<boolean>;
164
- };
165
- /**
166
- * The drizzle's table schema wrapped by this repository.
167
- */
168
- readonly Model: TModel;
169
- /**
170
- * The database connection name to use.
171
- *
172
- * Update this value to change the database connection used by this repository.
173
- */
174
- readonly connection: string;
175
- };
package/dist/tenancy.d.ts DELETED
@@ -1,244 +0,0 @@
1
- import type { PgColumnBuilderBase, PgSchema, PgTable, PgTransaction } from 'drizzle-orm/pg-core';
2
- import type { Context } from './http';
3
- import { Middleware } from './middleware';
4
- /**
5
- * The tenancy mode for the application.
6
- * - `schema`: Each tenant has their own Postgres schema.
7
- * - `rls`: Row-Level Security with a shared schema and a tenant column.
8
- * @author Axel Nana <axel.nana@workbud.com>
9
- */
10
- export type TenancyMode = 'schema' | 'rls';
11
- /**
12
- * Global tenancy configuration for the application.
13
- * @author Axel Nana <axel.nana@workbud.com>
14
- */
15
- export interface TenancyConfig {
16
- /**
17
- * The tenancy mode to use.
18
- */
19
- mode: TenancyMode;
20
- /**
21
- * Configuration specific to RLS mode.
22
- */
23
- rls?: {
24
- /**
25
- * The PostgreSQL session variable used to store the current tenant.
26
- * @default 'app.current_tenant'
27
- */
28
- sessionVariable?: string;
29
- /**
30
- * The default column name used for tenant isolation in RLS policies.
31
- * @default 'tenant_id'
32
- */
33
- defaultColumn?: string;
34
- };
35
- /**
36
- * Configuration specific to schema-based tenancy.
37
- */
38
- schema?: {
39
- /**
40
- * Whether to automatically create tenant schemas on first use.
41
- */
42
- autoCreate?: boolean;
43
- };
44
- }
45
- /**
46
- * Per-model tenancy configuration, used to control how a specific model
47
- * interacts with the tenancy system.
48
- * @author Axel Nana <axel.nana@workbud.com>
49
- */
50
- export interface ModelTenancyConfig {
51
- /**
52
- * Whether tenancy is enabled for this model.
53
- */
54
- enabled: boolean;
55
- /**
56
- * Override the global tenancy mode for this model.
57
- */
58
- mode?: TenancyMode;
59
- /**
60
- * The column name used for RLS tenant isolation in this model.
61
- */
62
- column?: string;
63
- /**
64
- * Custom RLS policy name for this model.
65
- */
66
- policyName?: string;
67
- }
68
- /**
69
- * Sets the global tenancy configuration.
70
- * @author Axel Nana <axel.nana@workbud.com>
71
- * @param config The tenancy configuration to apply.
72
- */
73
- export declare const configure: (config: TenancyConfig) => void;
74
- /**
75
- * Gets the current global tenancy configuration.
76
- * @author Axel Nana <axel.nana@workbud.com>
77
- * @returns The current tenancy configuration.
78
- */
79
- export declare const getConfig: () => TenancyConfig;
80
- /**
81
- * Gets the current tenant from the async context.
82
- * @author Axel Nana <axel.nana@workbud.com>
83
- * @returns The current tenant identifier, or `null` if not set.
84
- */
85
- export declare const getCurrentTenant: () => string | null;
86
- /**
87
- * Runs a callback within the context of a specific tenant.
88
- * @author Axel Nana <axel.nana@workbud.com>
89
- * @param tenant The tenant identifier to set.
90
- * @param callback The function to execute within the tenant context.
91
- * @returns The return value of the callback.
92
- */
93
- export declare const withTenant: <T>(tenant: string, callback: () => T) => T;
94
- /**
95
- * Gets the Drizzle `PgSchema` for the given tenant.
96
- * Creates and registers the schema if it doesn't exist yet.
97
- * @author Axel Nana <axel.nana@workbud.com>
98
- * @param tenant The name of the tenant.
99
- * @returns The Postgres schema for the tenant.
100
- */
101
- export declare const getTenantSchema: (tenant: string) => PgSchema;
102
- /**
103
- * Registers a new Postgres schema for a tenant.
104
- * If the schema is already registered, returns the existing one.
105
- * @author Axel Nana <axel.nana@workbud.com>
106
- * @param tenant The name of the tenant.
107
- * @returns The newly created or existing tenant schema.
108
- */
109
- export declare const registerTenantSchema: (tenant: string) => PgSchema;
110
- /**
111
- * Wraps a table definition within a tenant's Postgres schema.
112
- * For the `public` tenant, returns a standard `pgTable`.
113
- * Results are cached for performance.
114
- * @author Axel Nana <axel.nana@workbud.com>
115
- * @param tenant The tenant identifier.
116
- * @param tableName The name of the table.
117
- * @param columns The table columns definition.
118
- * @returns A `PgTable` scoped to the tenant's schema.
119
- */
120
- export declare const wrapTenantSchema: <TTableName extends string, TColumnsMap extends Record<string, PgColumnBuilderBase>>(tenant: string, tableName: TTableName, columns: TColumnsMap) => PgTable;
121
- /**
122
- * Execute a callback within a transaction that has the tenant context set
123
- * via PostgreSQL session variable.
124
- *
125
- * Uses `set_config(varName, value, true)` which:
126
- * - Sets the variable value as a proper GUC parameter (not an identifier)
127
- * - The `true` flag makes it transaction-local (reverts on commit/rollback)
128
- *
129
- * The transaction handle (`tx`) is passed to the callback so all
130
- * queries execute within the same transaction where `set_config` was called.
131
- *
132
- * @author Axel Nana <axel.nana@workbud.com>
133
- * @param tenant The tenant identifier, or `null` for the public tenant.
134
- * @param callback A function receiving the transaction handle.
135
- * @param connectionName The database connection to use.
136
- * @returns The return value of the callback.
137
- */
138
- export declare const withRLS: <T>(tenant: string | null, callback: (tx: PgTransaction<any, any, any>) => Promise<T>, connectionName?: string) => Promise<T>;
139
- /**
140
- * Sets the tenant for the current database connection (session-level, not transaction-local).
141
- * Useful for long-lived connections or connection pools.
142
- * @author Axel Nana <axel.nana@workbud.com>
143
- * @param tenant The tenant identifier, or `null` for the public tenant.
144
- * @param connectionName The database connection to use.
145
- */
146
- export declare const setConnectionTenant: (tenant: string | null, connectionName?: string) => Promise<void>;
147
- /**
148
- * Reads the current tenant from the PostgreSQL session variable.
149
- * @author Axel Nana <axel.nana@workbud.com>
150
- * @param connectionName The database connection to use.
151
- * @returns The current tenant identifier, or `null` if not set.
152
- */
153
- export declare const getSessionTenant: (connectionName?: string) => Promise<string | null>;
154
- /**
155
- * Create an RLS policy for tenant isolation.
156
- *
157
- * Always specifies `for` and `to` for deterministic behavior:
158
- * - `for: 'all'` — policy applies to SELECT, INSERT, UPDATE, DELETE
159
- * - `to: 'public'` — policy applies to all roles
160
- *
161
- * @author Axel Nana <axel.nana@workbud.com>
162
- * @param tableName The name of the table to create the policy for.
163
- * @param columnName The column that holds the tenant identifier. Defaults to the global config.
164
- * @param policyName Custom name for the policy. Defaults to `{tableName}_tenant_isolation`.
165
- * @returns A Drizzle `pgPolicy` definition.
166
- */
167
- export declare const createRLSPolicy: (tableName: string, columnName?: string, policyName?: string) => import("drizzle-orm/pg-core").PgPolicy;
168
- /**
169
- * Base class for tenant-aware middleware.
170
- *
171
- * The middleware extracts the tenant identifier from an HTTP header and
172
- * sets `ctx.tenant`. For RLS mode, route handlers should use `withRLS()`
173
- * to wrap their queries in a tenant-scoped transaction.
174
- *
175
- * @example
176
- * ```typescript
177
- * class OrganizationMiddleware extends TenantMiddleware {
178
- * protected header = 'x-organization-id';
179
- * protected allowPublic = false;
180
- *
181
- * protected async validateTenant(orgId: string): Promise<boolean> {
182
- * return Organization.exists(orgId);
183
- * }
184
- * }
185
- * ```
186
- *
187
- * @author Axel Nana <axel.nana@workbud.com>
188
- */
189
- export declare abstract class TenantMiddleware extends Middleware {
190
- /**
191
- * The HTTP header name from which the tenant ID is read.
192
- */
193
- protected header: string;
194
- /**
195
- * Whether requests without a tenant ID are allowed (defaulting to 'public').
196
- */
197
- protected allowPublic: boolean;
198
- /**
199
- * The database connection name used for tenant operations.
200
- */
201
- protected connectionName: string;
202
- /**
203
- * Validates that a tenant identifier is legitimate.
204
- * Override this to check against your data store.
205
- * @author Axel Nana <axel.nana@workbud.com>
206
- * @param _tenant The tenant identifier to validate.
207
- * @returns `true` if the tenant is valid, `false` otherwise.
208
- */
209
- protected validateTenant(_tenant: string): Promise<boolean>;
210
- /**
211
- * Hook called after a tenant has been successfully resolved.
212
- * @author Axel Nana <axel.nana@workbud.com>
213
- * @param _tenant The resolved tenant identifier.
214
- * @param _ctx The request context.
215
- */
216
- protected onTenantResolved(_tenant: string, _ctx: Context): Promise<void>;
217
- /**
218
- * Called when the tenant cannot be determined or is invalid.
219
- * Throws an appropriate error by default.
220
- * @author Axel Nana <axel.nana@workbud.com>
221
- * @param reason Whether the tenant is 'missing' or 'invalid'.
222
- * @param _ctx The request context.
223
- */
224
- protected onTenantError(reason: 'missing' | 'invalid', _ctx: Context): never;
225
- /**
226
- * Extracts and validates the tenant from the incoming request.
227
- * @author Axel Nana <axel.nana@workbud.com>
228
- * @param ctx The request context.
229
- */
230
- onRequest(ctx: Context): Promise<any>;
231
- }
232
- /**
233
- * A simple tenant middleware that allows public access by default.
234
- * @author Axel Nana <axel.nana@workbud.com>
235
- */
236
- export declare class SimpleTenantMiddleware extends TenantMiddleware {
237
- }
238
- /**
239
- * A strict tenant middleware that rejects requests without a tenant ID.
240
- * @author Axel Nana <axel.nana@workbud.com>
241
- */
242
- export declare class StrictTenantMiddleware extends TenantMiddleware {
243
- protected allowPublic: boolean;
244
- }