@jazim/test 2.0.3 → 2.0.4

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.
package/README.md CHANGED
@@ -1,143 +1,488 @@
1
- # TypeORM Adapter for Better-Auth
1
+ # @jazim/typeorm-better-auth
2
2
 
3
- A TypeORM database adapter for [Better-Auth](https://github.com/better-auth/better-auth), providing seamless authentication with TypeORM.
3
+ A TypeORM adapter for [Better Auth](https://www.better-auth.com/) that provides seamless integration between TypeORM and Better Auth's authentication system.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@jazim/typeorm-better-auth.svg)](https://www.npmjs.com/package/@jazim/typeorm-better-auth)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
7
 
5
8
  ## Features
6
9
 
7
- - Full TypeORM integration
8
- - TypeScript support with full type safety
9
- - Schema generation via Better-Auth CLI
10
- - Configurable table names (singular/plural)
11
- - Transaction support
12
- - Supports all major databases (PostgreSQL, MySQL, SQLite, SQL Server, Oracle, MongoDB)
10
+ - 🔌 **Seamless Integration** - Drop-in TypeORM adapter for Better Auth
11
+ - 🗄️ **Multi-Database Support** - PostgreSQL, MySQL, and SQLite
12
+ - 🔄 **Auto Generation** - Automatic entity and migration generation
13
+ - 🎯 **Type Safe** - Full TypeScript support
14
+ - 🛠️ **Customizable** - Configure entity names and paths
15
+ - 💪 **Transaction Support** - Built-in transaction handling
16
+ - 🔍 **Advanced Queries** - Support for complex where clauses and operators
13
17
 
14
18
  ## Installation
15
19
 
16
20
  ```bash
17
- npm install typeorm-adapter-betterauth typeorm better-auth
18
- # or
19
- pnpm add typeorm-adapter-betterauth typeorm better-auth
20
- # or
21
- yarn add typeorm-adapter-betterauth typeorm better-auth
21
+ npm install @jazim/typeorm-better-auth
22
22
  ```
23
23
 
24
- ## Quick Start
24
+ or with pnpm:
25
25
 
26
- ### 1. Generate TypeORM Entities and Migrations
26
+ ```bash
27
+ pnpm add @jazim/typeorm-better-auth
28
+ ```
27
29
 
28
- Run the Better-Auth CLI to generate TypeORM entity and migration files:
30
+ or with yarn:
29
31
 
30
32
  ```bash
31
- npx @better-auth/cli@latest generate
33
+ yarn add @jazim/typeorm-better-auth
32
34
  ```
33
35
 
34
- This will create:
35
- - **Entity file** (e.g., `auth-schema.ts`) with TypeORM decorators for all Better-Auth tables
36
- - **Migration file** (e.g., `migrations/1234567890-InitialSchema.ts`) for creating tables in production
36
+ ### Peer Dependencies
37
37
 
38
- ### 2. Set Up TypeORM DataSource
38
+ This package requires the following peer dependencies:
39
39
 
40
- Import the generated entities and create your DataSource:
40
+ ```bash
41
+ npm install better-auth typeorm
42
+ ```
43
+
44
+ ## Quick Start
45
+
46
+ ### 1. Setup TypeORM DataSource
47
+
48
+ Create a TypeORM DataSource configuration:
41
49
 
42
50
  ```typescript
43
- import { DataSource } from \"typeorm\";
44
- import { User, Session, Account, Verification } from \"./auth-schema\"; // generated file
51
+ import { DataSource } from "typeorm";
45
52
 
46
- const dataSource = new DataSource({
47
- type: \"postgres\", // or \"mysql\", \"sqlite\", etc.
48
- host: \"localhost\",
53
+ export const dataSource = new DataSource({
54
+ type: "postgres", // or "mysql" or "sqlite"
55
+ host: "localhost",
49
56
  port: 5432,
50
- username: \"user\",
51
- password: \"password\",
52
- database: \"myapp\",
53
- entities: [User, Session, Account, Verification],
54
- migrations: [\"./migrations/*.ts\"], // Include generated migrations
55
- synchronize: false, // Use migrations in production
57
+ username: "your_username",
58
+ password: "your_password",
59
+ database: "your_database",
60
+ entities: ["./entities/**/*.ts"],
61
+ migrations: ["./migrations/**/*.ts"],
62
+ synchronize: false, // Set to false in production
56
63
  });
64
+ ```
65
+
66
+ ### 2. Initialize the Adapter
67
+
68
+ ```typescript
69
+ import { betterAuth } from "better-auth";
70
+ import { typeormAdapter } from "@jazim/typeorm-better-auth";
71
+ import { dataSource } from "./data-source";
57
72
 
73
+ // Initialize the datasource
58
74
  await dataSource.initialize();
75
+
76
+ export const auth = betterAuth({
77
+ database: typeormAdapter(dataSource, {
78
+ provider: "postgres",
79
+ entitiesPath: "./entities",
80
+ migrationsPath: "./migrations",
81
+ }),
82
+ // ... other Better Auth options
83
+ });
59
84
  ```
60
85
 
61
- ### 3. Run Migrations
86
+ ### 3. Generate Entities and Migrations
62
87
 
63
- For production, run migrations instead of using `synchronize: true`:
88
+ The adapter will automatically generate TypeORM entities and migrations based on your Better Auth configuration. The generated files will be saved to the paths specified in the configuration.
64
89
 
65
- ```bash
66
- # Run migrations
67
- npx typeorm migration:run -d ./data-source.ts
90
+ ## Configuration
68
91
 
69
- # Revert last migration
70
- npx typeorm migration:revert -d ./data-source.ts
92
+ ### TypeOrmAdapterConfig
93
+
94
+ The adapter accepts a configuration object with the following options:
95
+
96
+ ```typescript
97
+ interface TypeOrmAdapterConfig {
98
+ /**
99
+ * Database provider
100
+ * @default "postgres"
101
+ */
102
+ provider?: "mysql" | "postgres" | "sqlite";
103
+
104
+ /**
105
+ * Custom entity names for the adapter models
106
+ * @default { user: "User", account: "Account", session: "Session", verification: "Verification" }
107
+ */
108
+ entities?: {
109
+ user?: string;
110
+ account?: string;
111
+ session?: string;
112
+ verification?: string;
113
+ };
114
+
115
+ /**
116
+ * Generate TypeORM entity files
117
+ * @default true
118
+ */
119
+ generateEntities?: boolean;
120
+
121
+ /**
122
+ * Generate migration files
123
+ * @default true
124
+ */
125
+ generateMigrations?: boolean;
126
+
127
+ /**
128
+ * Path to save generated entities
129
+ * @default "./entities"
130
+ */
131
+ entitiesPath?: string;
132
+
133
+ /**
134
+ * Path to save generated migrations
135
+ * @default "./migrations"
136
+ */
137
+ migrationsPath?: string;
138
+
139
+ /**
140
+ * Enable transaction support
141
+ * @default false
142
+ */
143
+ transaction?: boolean;
144
+ }
71
145
  ```
72
146
 
73
- ### 4. Initialize Better-Auth with TypeORM Adapter
147
+ ## Usage Examples
148
+
149
+ ### Basic Setup with PostgreSQL
74
150
 
75
151
  ```typescript
76
- import { betterAuth } from \"better-auth\";
77
- import { typeormAdapter } from \"typeorm-adapter-betterauth\";
152
+ import { DataSource } from "typeorm";
153
+ import { betterAuth } from "better-auth";
154
+ import { typeormAdapter } from "@jazim/typeorm-better-auth";
78
155
 
79
- const auth = betterAuth({
156
+ const dataSource = new DataSource({
157
+ type: "postgres",
158
+ host: process.env.DB_HOST,
159
+ port: parseInt(process.env.DB_PORT || "5432"),
160
+ username: process.env.DB_USER,
161
+ password: process.env.DB_PASSWORD,
162
+ database: process.env.DB_NAME,
163
+ entities: ["./entities/**/*.ts"],
164
+ migrations: ["./migrations/**/*.ts"],
165
+ });
166
+
167
+ await dataSource.initialize();
168
+
169
+ export const auth = betterAuth({
80
170
  database: typeormAdapter(dataSource, {
81
- provider: \"postgres\", // must match your DataSource type
171
+ provider: "postgres",
172
+ entitiesPath: "./entities",
173
+ migrationsPath: "./migrations",
82
174
  }),
83
- // ... other better-auth config
175
+ emailAndPassword: {
176
+ enabled: true,
177
+ },
84
178
  });
85
179
  ```
86
180
 
87
- ## Configuration
181
+ ### Custom Entity Names
88
182
 
89
- ### Adapter Options
183
+ ```typescript
184
+ export const auth = betterAuth({
185
+ database: typeormAdapter(dataSource, {
186
+ provider: "postgres",
187
+ entities: {
188
+ user: "CustomUser",
189
+ account: "CustomAccount",
190
+ session: "CustomSession",
191
+ verification: "CustomVerification",
192
+ },
193
+ entitiesPath: "./src/entities",
194
+ migrationsPath: "./src/migrations",
195
+ }),
196
+ });
197
+ ```
198
+
199
+ ### With Better Auth Model Names
200
+
201
+ If you're using custom model names in Better Auth, the adapter will respect them:
90
202
 
91
203
  ```typescript
92
- typeormAdapter(dataSource, {
93
- provider: \"postgres\", // Required: \"postgres\" | \"mysql\" | \"sqlite\" | \"mssql\" | \"oracle\" | \"mongodb\"
94
- usePlural: false, // Use plural table names (users, sessions, etc.)
95
- debugLogs: false, // Enable debug logs
96
- transaction: false, // Enable transaction support
204
+ export const auth = betterAuth({
205
+ database: typeormAdapter(dataSource, {
206
+ provider: "postgres",
207
+ entitiesPath: "./entities",
208
+ migrationsPath: "./migrations",
209
+ }),
210
+ user: {
211
+ modelName: "users", // Custom model name
212
+ },
213
+ session: {
214
+ modelName: "user_sessions",
215
+ },
97
216
  });
98
217
  ```
99
218
 
100
- ## Complete Example
219
+ ### SQLite Configuration
101
220
 
102
221
  ```typescript
103
- import { betterAuth } from \"better-auth\";
104
- import { typeormAdapter } from \"typeorm-adapter-betterauth\";
105
- import { DataSource } from \"typeorm\";
106
- import { User, Session, Account, Verification } from \"./auth-schema\";
222
+ import { DataSource } from "typeorm";
223
+ import { typeormAdapter } from "@jazim/typeorm-better-auth";
107
224
 
108
- // 1. Create DataSource
109
225
  const dataSource = new DataSource({
110
- type: \"postgres\",
111
- host: process.env.DB_HOST,
112
- port: parseInt(process.env.DB_PORT || \"5432\"),
113
- username: process.env.DB_USER,
114
- password: process.env.DB_PASSWORD,
115
- database: process.env.DB_NAME,
116
- entities: [User, Session, Account, Verification],
117
- migrations: [\"./migrations/*.ts\"],
118
- synchronize: false, // Use migrations in production
119
- logging: process.env.NODE_ENV !== \"production\",
226
+ type: "better-sqlite3",
227
+ database: "./database.sqlite",
228
+ entities: ["./entities/**/*.ts"],
120
229
  });
121
230
 
122
231
  await dataSource.initialize();
123
232
 
124
- // Run migrations in production
125
- if (process.env.NODE_ENV === \"production\") {
126
- await dataSource.runMigrations();
127
- }
233
+ export const auth = betterAuth({
234
+ database: typeormAdapter(dataSource, {
235
+ provider: "sqlite",
236
+ }),
237
+ });
238
+ ```
239
+
240
+ ### MySQL Configuration
241
+
242
+ ```typescript
243
+ const dataSource = new DataSource({
244
+ type: "mysql",
245
+ host: "localhost",
246
+ port: 3306,
247
+ username: "root",
248
+ password: "password",
249
+ database: "myapp",
250
+ entities: ["./entities/**/*.ts"],
251
+ });
252
+
253
+ await dataSource.initialize();
128
254
 
129
- // 2. Create Better-Auth instance
130
255
  export const auth = betterAuth({
131
256
  database: typeormAdapter(dataSource, {
132
- provider: \"postgres\",
133
- transaction: true,
257
+ provider: "mysql",
134
258
  }),
135
- emailAndPassword: {
136
- enabled: true,
137
- },
138
259
  });
139
260
  ```
140
261
 
262
+ ### Transaction Support
263
+
264
+ Enable transaction support for better data consistency:
265
+
266
+ ```typescript
267
+ export const auth = betterAuth({
268
+ database: typeormAdapter(dataSource, {
269
+ provider: "postgres",
270
+ transaction: true, // Enable transactions
271
+ }),
272
+ });
273
+ ```
274
+
275
+ ### Disable Auto-Generation
276
+
277
+ If you want to manage entities and migrations manually:
278
+
279
+ ```typescript
280
+ export const auth = betterAuth({
281
+ database: typeormAdapter(dataSource, {
282
+ provider: "postgres",
283
+ generateEntities: false,
284
+ generateMigrations: false,
285
+ }),
286
+ });
287
+ ```
288
+
289
+ ## Generated Files
290
+
291
+ ### Entity Files
292
+
293
+ The adapter generates TypeORM entity files based on your Better Auth schema. Example generated entity:
294
+
295
+ ```typescript
296
+ import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
297
+
298
+ @Entity("user")
299
+ export class User {
300
+ @PrimaryGeneratedColumn("uuid")
301
+ id!: string;
302
+
303
+ @Column("varchar")
304
+ email!: string;
305
+
306
+ @Column("varchar")
307
+ name!: string;
308
+
309
+ @Column("varchar", { nullable: true })
310
+ emailVerified?: string | null;
311
+
312
+ @Column("varchar", { nullable: true })
313
+ image?: string | null;
314
+
315
+ @Column("timestamp")
316
+ createdAt!: Date;
317
+
318
+ @Column("timestamp")
319
+ updatedAt!: Date;
320
+ }
321
+ ```
322
+
323
+ ### Migration Files
324
+
325
+ Migration files are generated with timestamps and include both `up` and `down` methods:
326
+
327
+ ```typescript
328
+ import { MigrationInterface, QueryRunner, Table } from "typeorm";
329
+
330
+ export class BetterAuthMigration1234567890 implements MigrationInterface {
331
+ public async up(queryRunner: QueryRunner): Promise<void> {
332
+ await queryRunner.createTable(
333
+ new Table({
334
+ name: "user",
335
+ columns: [
336
+ {
337
+ name: "id",
338
+ type: "uuid",
339
+ isPrimary: true,
340
+ isGenerated: true,
341
+ generationStrategy: "uuid",
342
+ },
343
+ // ... more columns
344
+ ],
345
+ })
346
+ );
347
+ }
348
+
349
+ public async down(queryRunner: QueryRunner): Promise<void> {
350
+ await queryRunner.dropTable("user");
351
+ }
352
+ }
353
+ ```
354
+
355
+ ## Advanced Features
356
+
357
+ ### Query Operators
358
+
359
+ The adapter supports various query operators:
360
+
361
+ - `eq` - Equal
362
+ - `ne` - Not equal
363
+ - `lt` - Less than
364
+ - `lte` - Less than or equal
365
+ - `gt` - Greater than
366
+ - `gte` - Greater than or equal
367
+ - `in` - In array
368
+ - `not_in` - Not in array
369
+ - `contains` - String contains
370
+ - `starts_with` - String starts with
371
+ - `ends_with` - String ends with
372
+
373
+ ### Error Handling
374
+
375
+ The adapter provides detailed error messages wrapped in `BetterAuthError` for easier debugging:
376
+
377
+ ```typescript
378
+ try {
379
+ await auth.api.signInEmail({
380
+ email: "user@example.com",
381
+ password: "password",
382
+ });
383
+ } catch (error) {
384
+ console.error(error.message); // Detailed error from the adapter
385
+ }
386
+ ```
387
+
388
+ ## TypeORM Integration
389
+
390
+ ### Running Migrations
391
+
392
+ You can use TypeORM CLI to run migrations:
393
+
394
+ ```bash
395
+ # Run migrations
396
+ npx typeorm migration:run -d ./data-source.ts
397
+
398
+ # Revert migrations
399
+ npx typeorm migration:revert -d ./data-source.ts
400
+
401
+ # Show migrations
402
+ npx typeorm migration:show -d ./data-source.ts
403
+ ```
404
+
405
+ ### Accessing Entities
406
+
407
+ You can access the generated entities in your application:
408
+
409
+ ```typescript
410
+ import { User } from "./entities/auth";
411
+ import { dataSource } from "./data-source";
412
+
413
+ const userRepository = dataSource.getRepository(User);
414
+ const users = await userRepository.find();
415
+ ```
416
+
417
+ ## Database Schema
418
+
419
+ The adapter creates the following tables (default names):
420
+
421
+ - **user** - User accounts
422
+ - **account** - OAuth accounts linked to users
423
+ - **session** - User sessions
424
+ - **verification** - Email verification tokens
425
+
426
+ Each table is fully compatible with Better Auth's requirements and supports all authentication features.
427
+
428
+ ## Best Practices
429
+
430
+ 1. **Production Setup**: Always set `synchronize: false` in production and use migrations
431
+ 2. **Environment Variables**: Store database credentials in environment variables
432
+ 3. **Connection Pooling**: Configure appropriate connection pool settings for your database
433
+ 4. **Migrations**: Review generated migrations before running them in production
434
+ 5. **Custom Entities**: If using custom entity names, ensure consistency across your application
435
+ 6. **Transaction Support**: Enable transactions for critical operations
436
+
437
+ ## Troubleshooting
438
+
439
+ ### Entities Not Found
440
+
441
+ Make sure your TypeORM configuration includes the correct entity paths:
442
+
443
+ ```typescript
444
+ entities: ["./entities/**/*.ts"], // Development
445
+ // or
446
+ entities: ["./dist/entities/**/*.js"], // Production
447
+ ```
448
+
449
+ ### Migration Errors
450
+
451
+ If migrations fail:
452
+
453
+ 1. Check database connection
454
+ 2. Verify the provider setting matches your database type
455
+ 3. Ensure migrations directory exists
456
+ 4. Check for conflicts with existing tables
457
+
458
+ ### Type Errors
459
+
460
+ Ensure you're using compatible versions:
461
+
462
+ - `better-auth` >= 1.4.0
463
+ - `typeorm` >= 0.3.2
464
+
465
+ ## Contributing
466
+
467
+ Contributions are welcome! Please feel free to submit a Pull Request.
468
+
141
469
  ## License
142
470
 
143
471
  MIT
472
+
473
+ ## Support
474
+
475
+ For issues and questions:
476
+
477
+ - [GitHub Issues](https://github.com/jazimabbas/typeorm-better-auth/issues)
478
+ - [Better Auth Documentation](https://www.better-auth.com/docs)
479
+ - [TypeORM Documentation](https://typeorm.io/)
480
+
481
+ ## Acknowledgments
482
+
483
+ - [Better Auth](https://www.better-auth.com/) - Modern authentication framework
484
+ - [TypeORM](https://typeorm.io/) - ORM for TypeScript and JavaScript
485
+
486
+ ---
487
+
488
+ Made with ❤️ for the Better Auth community
package/dist/index.d.mts CHANGED
@@ -4,7 +4,7 @@ import { DataSource } from 'typeorm';
4
4
  import { AdapterFactoryConfig } from 'better-auth/adapters';
5
5
 
6
6
  type Provider = "mysql" | "postgres" | "sqlite";
7
- interface TypeOrmAdapterConfig extends Pick<AdapterFactoryConfig, "debugLogs" | "usePlural" | "transaction"> {
7
+ interface TypeOrmAdapterConfig extends Pick<AdapterFactoryConfig, "transaction" | "debugLogs"> {
8
8
  /**
9
9
  * Database provider.
10
10
  *
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { DataSource } from 'typeorm';
4
4
  import { AdapterFactoryConfig } from 'better-auth/adapters';
5
5
 
6
6
  type Provider = "mysql" | "postgres" | "sqlite";
7
- interface TypeOrmAdapterConfig extends Pick<AdapterFactoryConfig, "debugLogs" | "usePlural" | "transaction"> {
7
+ interface TypeOrmAdapterConfig extends Pick<AdapterFactoryConfig, "transaction" | "debugLogs"> {
8
8
  /**
9
9
  * Database provider.
10
10
  *