@zuzjs/orm 0.1.1 → 0.1.3

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/dist/bin.js CHANGED
@@ -4,36 +4,23 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- const path_1 = __importDefault(require("path"));
8
- const picocolors_1 = __importDefault(require("picocolors"));
9
7
  const commander_1 = require("commander");
10
- // import fs, { readdirSync } from "fs";
11
- // import { fileURLToPath } from "url";
12
- const index_js_1 = require("./drivers/mysql/index.js");
13
- const index_js_2 = require("./core/index.js");
8
+ const cli_js_1 = require("./core/cli.js");
9
+ const picocolors_1 = __importDefault(require("picocolors"));
10
+ commander_1.program
11
+ .name("zorm")
12
+ .description("ZuzORM is a lightweight ORM wrapper around TypeORM with support for MySQL.");
13
+ /**Version */
14
14
  commander_1.program
15
15
  .option(`-v, --version`)
16
- .option(`-c, --connection <VALUE>`, `Database Connection String`)
17
- .option(`-p, --dist`);
18
- commander_1.program.parse();
19
- const { version, connection, dist: destination } = commander_1.program.opts();
20
- if (version) {
21
- console.log(`ZuzORM v0.1.1`);
16
+ .description("Displays current version of ZuzORM")
17
+ .action(() => {
18
+ const packageJson = require("../package.json");
19
+ console.log(picocolors_1.default.cyan(`ZuzORM v${packageJson.version}`));
22
20
  process.exit(1);
23
- }
24
- if (connection) {
25
- const dist = destination || path_1.default.join(`src`, `zorm`);
26
- const _checkDist = (0, index_js_2.checkDirectory)(path_1.default.join(process.cwd(), dist), true);
27
- if (!_checkDist.access) {
28
- console.log(picocolors_1.default.red(`○ ${_checkDist.message}`));
29
- process.exit(1);
30
- }
31
- if (connection.startsWith(`mysql`)) {
32
- const driver = new index_js_1.MySqlDriver(decodeURIComponent(connection), dist);
33
- driver.generate();
34
- }
35
- else {
36
- console.log(`Only MySQL is supported for now`);
37
- process.exit(1);
38
- }
39
- }
21
+ });
22
+ commander_1.program
23
+ .command(`pull`)
24
+ .description(`Pull using DATABASE_URL from .env in project directory`)
25
+ .action(cli_js_1.Pull);
26
+ commander_1.program.parse();
@@ -0,0 +1,5 @@
1
+ export declare const buildEntities: (connection: string, dist?: string) => void;
2
+ /**
3
+ * Pull using DATABASE_URL from .env in project directory
4
+ **/
5
+ export declare const Pull: () => void;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.Pull = exports.buildEntities = void 0;
40
+ const fs_1 = __importStar(require("fs"));
41
+ const path_1 = __importDefault(require("path"));
42
+ const picocolors_1 = __importDefault(require("picocolors"));
43
+ const index_js_1 = require("./index.js");
44
+ const mysql_1 = require("../drivers/mysql");
45
+ const buildEntities = (connection, dist) => {
46
+ dist = dist || path_1.default.join(`src`, `zorm`);
47
+ const _checkDist = (0, index_js_1.checkDirectory)(path_1.default.join(process.cwd(), dist), true);
48
+ if (!_checkDist.access) {
49
+ console.log(picocolors_1.default.red(`○ ${_checkDist.message}`));
50
+ process.exit(1);
51
+ }
52
+ if (connection.startsWith(`mysql`)) {
53
+ const driver = new mysql_1.MySqlDriver(decodeURIComponent(connection), dist);
54
+ driver.generate();
55
+ }
56
+ else {
57
+ console.log(`○ Only MySQL is supported for now`);
58
+ process.exit(1);
59
+ }
60
+ };
61
+ exports.buildEntities = buildEntities;
62
+ /**
63
+ * Pull using DATABASE_URL from .env in project directory
64
+ **/
65
+ const Pull = () => {
66
+ const env = path_1.default.join(process.cwd(), `.env`);
67
+ if (!(0, fs_1.existsSync)(env)) {
68
+ console.log(picocolors_1.default.red(`○ ".env" not exists. Create .env and add DATABASE_URL="connection_string"`));
69
+ return;
70
+ }
71
+ const raw = fs_1.default.readFileSync(env, `utf8`).split(`\n`).filter((line) => line.startsWith(`DATABASE_URL`));
72
+ if (raw.length == 0) {
73
+ console.log(picocolors_1.default.red(`○ DATABASE_URL not found in ".env". Add DATABASE_URL="connection_string"`));
74
+ return;
75
+ }
76
+ (0, exports.buildEntities)(raw[0].trim().replace(/DATABASE_URL=|"|"/g, ``));
77
+ };
78
+ exports.Pull = Pull;
@@ -144,10 +144,15 @@ class MySqlDriver {
144
144
  // Get table structure
145
145
  const [columns] = await self.pool.execute(`DESCRIBE ${tableName}`);
146
146
  const entityCode = [
147
- `import { Entity, PrimaryColumn, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm";\n`,
147
+ `/**`,
148
+ `* AutoGenerated by @zuzjs/orm.`,
149
+ `* @ ${new Date().toString().split(` GMT`)[0].trim()}`,
150
+ `*/`,
151
+ `import { Entity, PrimaryColumn, PrimaryGeneratedColumn, Column, BaseEntity } from "@zuzjs/orm";\n`,
148
152
  `@Entity({ name: "${tableName}" })`,
149
153
  `export class ${(0, index_js_1.toPascalCase)(tableName)} extends BaseEntity {\n`
150
154
  ];
155
+ let hasPrimary = false;
151
156
  for (const column of columns) {
152
157
  // const { Field, Type, Key } = column;
153
158
  const { Field, Type, Key, Null, Default, Extra } = column;
@@ -155,6 +160,7 @@ class MySqlDriver {
155
160
  // Handle primary key
156
161
  if (Key === "PRI") {
157
162
  entityCode.push(Extra.includes("auto_increment") ? `\t@PrimaryGeneratedColumn()` : `\t@PrimaryColumn()`);
163
+ hasPrimary = true;
158
164
  }
159
165
  else {
160
166
  let columnDecorator = `\t@Column({ type: "${columnType}"`;
@@ -170,12 +176,14 @@ class MySqlDriver {
170
176
  entityCode.push(`\t${Field}!: ${tsType};\n`);
171
177
  }
172
178
  entityCode.push(`}`);
179
+ if (!hasPrimary) {
180
+ console.log(picocolors_1.default.bgRed(picocolors_1.default.whiteBright(` WARNING `)), picocolors_1.default.yellow(`○ "${tableName}" does not have a primary column. Primary column is required.`));
181
+ }
173
182
  // Write entity file
174
183
  fs_1.default.writeFileSync(path_1.default.join(this.dist, `${tableName}.ts`), entityCode.join(`\n`));
175
184
  }
176
185
  await self.pool.end();
177
186
  console.log(picocolors_1.default.green(`✓ ${tables.length} Tables Processed.`));
178
- process.exit(1);
179
187
  }
180
188
  }
181
189
  exports.MySqlDriver = MySqlDriver;
@@ -16,27 +16,118 @@ declare class ZormQueryBuilder<T extends ObjectLiteral, R = QueryResult> extends
16
16
  _update(): this;
17
17
  _delete(): this;
18
18
  _getRawQuery(): [string, any[]];
19
+ /**
20
+ * Sets the values for an insert or update query.
21
+ * @param data - The data to be inserted or updated.
22
+ * @returns The current instance of ZormQueryBuilder.
23
+ */
19
24
  with(data: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T[]>): this;
25
+ /**
26
+ * Specifies the fields to be selected in a select query.
27
+ * @param fields - The fields to be selected.
28
+ * @returns The current instance of ZormQueryBuilder.
29
+ */
20
30
  select(fields: (keyof T)[]): this;
21
- where(condition: FindOptionsWhere<T>): this;
31
+ /**
32
+ * Adds a WHERE condition to the query.
33
+ * @param condition - The condition to be added.
34
+ * @returns The current instance of ZormQueryBuilder.
35
+ */
36
+ where(condition: Partial<Record<keyof T, any>>): this;
37
+ /**
38
+ * Adds an OR condition to the query.
39
+ * @param condition - The condition to be added.
40
+ * @returns The current instance of ZormQueryBuilder.
41
+ */
22
42
  or(condition: FindOptionsWhere<T>): this;
43
+ /**
44
+ * Adds an ORDER BY clause to the query.
45
+ * @param field - The field to order by.
46
+ * @param direction - The direction of the order (ASC or DESC).
47
+ * @returns The current instance of ZormQueryBuilder.
48
+ */
23
49
  orderBy(field: keyof T, direction?: "ASC" | "DESC"): this;
50
+ /**
51
+ * Adds a LIMIT clause to the query.
52
+ * @param n - The maximum number of records to return.
53
+ * @returns The current instance of ZormQueryBuilder.
54
+ */
24
55
  limit(n: number): this;
56
+ /**
57
+ * Adds an OFFSET clause to the query.
58
+ * @param n - The number of records to skip.
59
+ * @returns The current instance of ZormQueryBuilder.
60
+ */
25
61
  offset(n: number): this;
62
+ /**
63
+ * Adds relations to be included in the query.
64
+ * @param relations - The relations to be included.
65
+ * @returns The current instance of ZormQueryBuilder.
66
+ */
26
67
  relations(relations: string[]): this;
68
+ /**
69
+ * Adds an INNER JOIN clause to the query.
70
+ * @param relation - The relation to join.
71
+ * @param alias - The alias for the joined relation.
72
+ * @param condition - Optional condition for the join.
73
+ * @returns The current instance of ZormQueryBuilder.
74
+ */
27
75
  innerJoin(relation: string, alias: string, condition?: string): this;
76
+ /**
77
+ * Adds a LEFT JOIN clause to the query.
78
+ * @param relation - The relation to join.
79
+ * @param alias - The alias for the joined relation.
80
+ * @param condition - Optional condition for the join.
81
+ * @returns The current instance of ZormQueryBuilder.
82
+ */
28
83
  leftJoin(relation: string, alias: string, condition?: string): this;
84
+ /**
85
+ * Adds a GROUP BY clause to the query.
86
+ * @param field - The field to group by.
87
+ * @returns The current instance of ZormQueryBuilder.
88
+ */
29
89
  groupBy(field: keyof T): this;
90
+ /**
91
+ * Adds a HAVING clause to the query.
92
+ * @param condition - The condition for the HAVING clause.
93
+ * @returns The current instance of ZormQueryBuilder.
94
+ */
30
95
  having(condition: string): this;
96
+ /**
97
+ * Adds an IN clause to the query.
98
+ * @param field - The field to check.
99
+ * @param values - The values for the IN clause.
100
+ * @returns The current instance of ZormQueryBuilder.
101
+ */
31
102
  in(field: keyof T, values: any[]): this;
103
+ /**
104
+ * Adds a DISTINCT clause to the query.
105
+ * @returns The current instance of ZormQueryBuilder.
106
+ */
32
107
  distinct(): this;
33
108
  count(): Promise<number>;
34
109
  sum(field: keyof T): Promise<number>;
35
110
  avg(field: keyof T): Promise<number>;
36
111
  min(field: keyof T): Promise<number>;
37
112
  max(field: keyof T): Promise<number>;
113
+ /**
114
+ * Executes a raw SQL query.
115
+ * @param sql - The raw SQL query.
116
+ * @param params - Optional parameters for the query.
117
+ * @returns A promise that resolves with the query result.
118
+ */
38
119
  rawQuery(sql: string, params?: any): Promise<any>;
120
+ /**
121
+ * Executes the query and returns the result.
122
+ * @returns A promise that resolves with the query result.
123
+ */
39
124
  execute(): Promise<R>;
125
+ /**
126
+ * Handles the fulfillment and rejection of the promise.
127
+ * @param onfulfilled - The callback to execute when the promise is fulfilled.
128
+ * @param onrejected - The callback to execute when the promise is rejected.
129
+ * @returns A promise that resolves with the result of the callback.
130
+ */
40
131
  then<TResult1 = R, TResult2 = never>(onfulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
41
132
  }
42
133
  export default ZormQueryBuilder;
@@ -63,40 +63,104 @@ class ZormQueryBuilder extends Promise {
63
63
  _getRawQuery() {
64
64
  return this.queryBuilder.getQueryAndParameters();
65
65
  }
66
+ /**
67
+ * Sets the values for an insert or update query.
68
+ * @param data - The data to be inserted or updated.
69
+ * @returns The current instance of ZormQueryBuilder.
70
+ */
66
71
  with(data) {
67
72
  this.queryValues = data;
68
73
  return this;
69
74
  }
75
+ /**
76
+ * Specifies the fields to be selected in a select query.
77
+ * @param fields - The fields to be selected.
78
+ * @returns The current instance of ZormQueryBuilder.
79
+ */
70
80
  select(fields) {
71
81
  this.queryBuilder
72
82
  .select(fields.map(field => `${this.entityAlias}.${String(field)}`));
73
83
  return this;
74
84
  }
85
+ /**
86
+ * Adds a WHERE condition to the query.
87
+ * @param condition - The condition to be added.
88
+ * @returns The current instance of ZormQueryBuilder.
89
+ */
75
90
  where(condition) {
76
- this.queryBuilder.where(condition);
91
+ const qb = this.queryBuilder;
92
+ Object.entries(condition).forEach(([key, value]) => {
93
+ if (typeof value === "string" && value.startsWith("!")) {
94
+ qb.andWhere(`${this.entityAlias}.${key} != :${key}`, { [key]: value.slice(1) });
95
+ }
96
+ else if (typeof value === "boolean" || typeof value === "number") {
97
+ qb.andWhere(`${this.entityAlias}.${key} = :${key}`, { [key]: value });
98
+ }
99
+ else {
100
+ qb.andWhere(`${this.entityAlias}.${key} = :${key}`, { [key]: value });
101
+ }
102
+ });
77
103
  this.whereCount++;
78
104
  return this;
79
105
  }
106
+ // where(condition: FindOptionsWhere<T>): this {
107
+ // (this.queryBuilder as SelectQueryBuilder<T> | UpdateQueryBuilder<T>).where(condition);
108
+ // this.whereCount++
109
+ // return this;
110
+ // }
111
+ /**
112
+ * Adds an OR condition to the query.
113
+ * @param condition - The condition to be added.
114
+ * @returns The current instance of ZormQueryBuilder.
115
+ */
80
116
  or(condition) {
81
117
  this.queryBuilder.orWhere(condition);
82
118
  return this;
83
119
  }
120
+ /**
121
+ * Adds an ORDER BY clause to the query.
122
+ * @param field - The field to order by.
123
+ * @param direction - The direction of the order (ASC or DESC).
124
+ * @returns The current instance of ZormQueryBuilder.
125
+ */
84
126
  orderBy(field, direction = "ASC") {
85
127
  this.queryBuilder.orderBy(`${this.entityAlias}.${String(field)}`, direction);
86
128
  return this;
87
129
  }
130
+ /**
131
+ * Adds a LIMIT clause to the query.
132
+ * @param n - The maximum number of records to return.
133
+ * @returns The current instance of ZormQueryBuilder.
134
+ */
88
135
  limit(n) {
89
136
  this.queryBuilder.limit(n);
90
137
  return this;
91
138
  }
139
+ /**
140
+ * Adds an OFFSET clause to the query.
141
+ * @param n - The number of records to skip.
142
+ * @returns The current instance of ZormQueryBuilder.
143
+ */
92
144
  offset(n) {
93
145
  this.queryBuilder.offset(n);
94
146
  return this;
95
147
  }
148
+ /**
149
+ * Adds relations to be included in the query.
150
+ * @param relations - The relations to be included.
151
+ * @returns The current instance of ZormQueryBuilder.
152
+ */
96
153
  relations(relations) {
97
154
  relations.forEach(relation => this.queryBuilder.leftJoinAndSelect(`${this.entityAlias}.${relation}`, relation));
98
155
  return this;
99
156
  }
157
+ /**
158
+ * Adds an INNER JOIN clause to the query.
159
+ * @param relation - The relation to join.
160
+ * @param alias - The alias for the joined relation.
161
+ * @param condition - Optional condition for the join.
162
+ * @returns The current instance of ZormQueryBuilder.
163
+ */
100
164
  innerJoin(relation, alias, condition) {
101
165
  if (condition) {
102
166
  this.queryBuilder.innerJoin(`${this.entityAlias}.${relation}`, alias, condition);
@@ -106,6 +170,13 @@ class ZormQueryBuilder extends Promise {
106
170
  }
107
171
  return this;
108
172
  }
173
+ /**
174
+ * Adds a LEFT JOIN clause to the query.
175
+ * @param relation - The relation to join.
176
+ * @param alias - The alias for the joined relation.
177
+ * @param condition - Optional condition for the join.
178
+ * @returns The current instance of ZormQueryBuilder.
179
+ */
109
180
  leftJoin(relation, alias, condition) {
110
181
  if (condition) {
111
182
  this.queryBuilder.leftJoin(`${this.entityAlias}.${relation}`, alias, condition);
@@ -115,18 +186,38 @@ class ZormQueryBuilder extends Promise {
115
186
  }
116
187
  return this;
117
188
  }
189
+ /**
190
+ * Adds a GROUP BY clause to the query.
191
+ * @param field - The field to group by.
192
+ * @returns The current instance of ZormQueryBuilder.
193
+ */
118
194
  groupBy(field) {
119
195
  this.queryBuilder.groupBy(`${this.entityAlias}.${String(field)}`);
120
196
  return this;
121
197
  }
198
+ /**
199
+ * Adds a HAVING clause to the query.
200
+ * @param condition - The condition for the HAVING clause.
201
+ * @returns The current instance of ZormQueryBuilder.
202
+ */
122
203
  having(condition) {
123
204
  this.queryBuilder.having(condition);
124
205
  return this;
125
206
  }
207
+ /**
208
+ * Adds an IN clause to the query.
209
+ * @param field - The field to check.
210
+ * @param values - The values for the IN clause.
211
+ * @returns The current instance of ZormQueryBuilder.
212
+ */
126
213
  in(field, values) {
127
214
  this.queryBuilder.andWhere(`${this.entityAlias}.${String(field)} IN (:...values)`, { values });
128
215
  return this;
129
216
  }
217
+ /**
218
+ * Adds a DISTINCT clause to the query.
219
+ * @returns The current instance of ZormQueryBuilder.
220
+ */
130
221
  distinct() {
131
222
  this.queryBuilder.distinct(true);
132
223
  return this;
@@ -150,10 +241,27 @@ class ZormQueryBuilder extends Promise {
150
241
  const result = await this.queryBuilder.select(`MAX(${this.entityAlias}.${String(field)})`, "max").getRawOne();
151
242
  return result.max || 0;
152
243
  }
244
+ /**
245
+ * Executes a raw SQL query.
246
+ * @param sql - The raw SQL query.
247
+ * @param params - Optional parameters for the query.
248
+ * @returns A promise that resolves with the query result.
249
+ */
153
250
  async rawQuery(sql, params) {
154
251
  return await this.repository.query(sql, params);
155
252
  }
253
+ /**
254
+ * Executes the query and returns the result.
255
+ * @returns A promise that resolves with the query result.
256
+ */
156
257
  async execute() {
258
+ const removedMethods = {};
259
+ Object.keys(Object.prototype).forEach((method) => {
260
+ if (Object.prototype.hasOwnProperty.call(Object.prototype, method)) {
261
+ removedMethods[method] = Object.prototype[method];
262
+ delete Object.prototype[method];
263
+ }
264
+ });
157
265
  try {
158
266
  switch (this.action) {
159
267
  case "upsert":
@@ -169,9 +277,18 @@ class ZormQueryBuilder extends Promise {
169
277
  };
170
278
  case "update":
171
279
  this._update();
172
- const _update = await this.queryBuilder.execute();
173
- // console.log(`updated`, _update)
174
- return { updated: true };
280
+ const _updateQuery = this.queryBuilder;
281
+ const _update = await _updateQuery.execute();
282
+ const whereQuery = _updateQuery.getQuery().split("WHERE")[1]?.trim(); // Get the WHERE clause
283
+ const _get = this.repository
284
+ .createQueryBuilder(this.entityAlias)
285
+ .where(whereQuery, _updateQuery.getParameters()); // Use the same parameters
286
+ const _updated = await _get.getMany();
287
+ return {
288
+ updated: true,
289
+ record: _updated[0],
290
+ records: _updated.length > 1 ? _updated : null
291
+ };
175
292
  case "delete":
176
293
  this._delete();
177
294
  const _delete = await this.queryBuilder.execute();
@@ -180,9 +297,9 @@ class ZormQueryBuilder extends Promise {
180
297
  default:
181
298
  const _select = await this.queryBuilder.getMany();
182
299
  return {
183
- hasRows: true,
300
+ hasRows: _select.length > 0,
184
301
  count: _select.length,
185
- row: _select[0],
302
+ row: _select.length > 0 ? _select[0] : null,
186
303
  rows: _select
187
304
  };
188
305
  }
@@ -216,7 +333,18 @@ class ZormQueryBuilder extends Promise {
216
333
  return this.usePromise ? Promise.reject(_s) : _s;
217
334
  }
218
335
  }
336
+ finally {
337
+ Object.entries(removedMethods).forEach(([method, fn]) => {
338
+ Object.prototype[method] = fn;
339
+ });
340
+ }
219
341
  }
342
+ /**
343
+ * Handles the fulfillment and rejection of the promise.
344
+ * @param onfulfilled - The callback to execute when the promise is fulfilled.
345
+ * @param onrejected - The callback to execute when the promise is rejected.
346
+ * @returns A promise that resolves with the result of the callback.
347
+ */
220
348
  then(onfulfilled, onrejected) {
221
349
  return this.execute().then(onfulfilled, onrejected);
222
350
  }
package/dist/index.d.ts CHANGED
@@ -1,25 +1,91 @@
1
1
  import { EntitySchema, EntityTarget, MixedList, ObjectLiteral, Repository } from "typeorm";
2
2
  import ZormQueryBuilder from "./drivers/queryBuilder.js";
3
3
  import { InsertQueryResult, SelectQueryResult, UpdateQueryResult } from "./types.js";
4
+ import "reflect-metadata";
5
+ /**
6
+ * Zorm is a lightweight ORM wrapper around TypeORM with support for MySQL.
7
+ */
4
8
  declare class Zorm {
9
+ /**
10
+ * Singleton instance of Zorm.
11
+ * @private
12
+ */
5
13
  private static instance;
14
+ /**
15
+ * TypeORM DataSource instance.
16
+ * @private
17
+ */
6
18
  private dataSource;
19
+ /**
20
+ * Flag to track if the connection is initialized.
21
+ * @private
22
+ */
7
23
  private initialized;
24
+ /**
25
+ * Determines whether to use Promises for queries.
26
+ * @private
27
+ */
8
28
  private usePromise;
29
+ /**
30
+ * Private constructor to enforce singleton pattern.
31
+ * @param {string} connectionString - The database connection string.
32
+ * @param {string | null} [entitiesPath] - Path to the entities directory.
33
+ * @param {boolean} [usePromise] - Whether to use Promises for queries.
34
+ * @private
35
+ */
9
36
  private constructor();
37
+ /**
38
+ * Returns the singleton instance of Zorm.
39
+ * @param {string} connectionString - The database connection string.
40
+ * @param {string | null} [entitiesPath] - Path to the entities directory.
41
+ * @param {boolean} [usePromise] - Whether to use Promises for queries.
42
+ * @returns {Zorm} The singleton instance of Zorm.
43
+ */
10
44
  static get(connectionString: string, entitiesPath?: string | null, usePromise?: boolean): Zorm;
45
+ /**
46
+ * Connects to the database and initializes entities.
47
+ * @param {MixedList<string | Function | EntitySchema<any>>} entities - List of entity schemas.
48
+ * @returns {Promise<void>} Resolves when the connection is initialized.
49
+ */
11
50
  connect(entities: MixedList<string | Function | EntitySchema<any>>): Promise<void>;
12
51
  /**
13
52
  * Returns the appropriate QueryBuilder based on the database type.
53
+ * @param {EntityTarget<T>} entity - The entity target.
54
+ * @param {QueryAction} action - The query action type.
55
+ * @returns {ZormQueryBuilder<T, R>} Query builder instance.
56
+ * @private
14
57
  */
15
58
  private getQueryBuilder;
16
59
  /**
17
- * Get a repository for a specific entity
60
+ * Retrieves the repository for a given entity.
61
+ * @param {EntityTarget<T>} entity - The entity target.
62
+ * @returns {Repository<T>} The repository instance.
18
63
  */
19
64
  getRepository<T extends ObjectLiteral>(entity: EntityTarget<T>): Repository<T>;
65
+ /**
66
+ * Creates a new record in the database.
67
+ * @param {EntityTarget<T>} entity - The entity target.
68
+ * @returns {ZormQueryBuilder<T, InsertQueryResult>} The query builder instance.
69
+ */
20
70
  create<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, InsertQueryResult>;
71
+ /**
72
+ * Finds records in the database.
73
+ * @param {EntityTarget<T>} entity - The entity target.
74
+ * @returns {ZormQueryBuilder<T, SelectQueryResult>} The query builder instance.
75
+ */
21
76
  find<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, SelectQueryResult>;
77
+ /**
78
+ * Updates records in the database.
79
+ * @param {EntityTarget<T>} entity - The entity target.
80
+ * @returns {ZormQueryBuilder<T, UpdateQueryResult>} The query builder instance.
81
+ */
22
82
  update<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, UpdateQueryResult>;
83
+ /**
84
+ * Deletes records from the database.
85
+ * @param {EntityTarget<T>} entity - The entity target.
86
+ * @returns {ZormQueryBuilder<T, DeleteQueryResult>} The query builder instance.
87
+ */
23
88
  delete<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, UpdateQueryResult>;
24
89
  }
25
90
  export default Zorm;
91
+ export * from "./types.js";
package/dist/index.js CHANGED
@@ -1,4 +1,18 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
18
  };
@@ -9,11 +23,38 @@ const index_js_1 = require("./core/index.js");
9
23
  const picocolors_1 = __importDefault(require("picocolors"));
10
24
  const index_js_2 = require("./drivers/mysql/index.js");
11
25
  const queryBuilder_js_1 = __importDefault(require("./drivers/queryBuilder.js"));
26
+ require("reflect-metadata");
27
+ /**
28
+ * Zorm is a lightweight ORM wrapper around TypeORM with support for MySQL.
29
+ */
12
30
  class Zorm {
31
+ /**
32
+ * Singleton instance of Zorm.
33
+ * @private
34
+ */
13
35
  static instance;
36
+ /**
37
+ * TypeORM DataSource instance.
38
+ * @private
39
+ */
14
40
  dataSource;
41
+ /**
42
+ * Flag to track if the connection is initialized.
43
+ * @private
44
+ */
15
45
  initialized = false;
46
+ /**
47
+ * Determines whether to use Promises for queries.
48
+ * @private
49
+ */
16
50
  usePromise = false;
51
+ /**
52
+ * Private constructor to enforce singleton pattern.
53
+ * @param {string} connectionString - The database connection string.
54
+ * @param {string | null} [entitiesPath] - Path to the entities directory.
55
+ * @param {boolean} [usePromise] - Whether to use Promises for queries.
56
+ * @private
57
+ */
17
58
  constructor(connectionString, entitiesPath, usePromise) {
18
59
  const _dist = entitiesPath || path_1.default.join(`src`, `zorm`);
19
60
  const dist = path_1.default.join(process.cwd(), _dist);
@@ -40,12 +81,24 @@ class Zorm {
40
81
  process.exit(1);
41
82
  }
42
83
  }
84
+ /**
85
+ * Returns the singleton instance of Zorm.
86
+ * @param {string} connectionString - The database connection string.
87
+ * @param {string | null} [entitiesPath] - Path to the entities directory.
88
+ * @param {boolean} [usePromise] - Whether to use Promises for queries.
89
+ * @returns {Zorm} The singleton instance of Zorm.
90
+ */
43
91
  static get(connectionString, entitiesPath, usePromise) {
44
92
  if (!Zorm.instance) {
45
93
  Zorm.instance = new Zorm(connectionString, entitiesPath, usePromise);
46
94
  }
47
95
  return Zorm.instance;
48
96
  }
97
+ /**
98
+ * Connects to the database and initializes entities.
99
+ * @param {MixedList<string | Function | EntitySchema<any>>} entities - List of entity schemas.
100
+ * @returns {Promise<void>} Resolves when the connection is initialized.
101
+ */
49
102
  async connect(entities) {
50
103
  if (!this.initialized) {
51
104
  try {
@@ -61,6 +114,10 @@ class Zorm {
61
114
  }
62
115
  /**
63
116
  * Returns the appropriate QueryBuilder based on the database type.
117
+ * @param {EntityTarget<T>} entity - The entity target.
118
+ * @param {QueryAction} action - The query action type.
119
+ * @returns {ZormQueryBuilder<T, R>} Query builder instance.
120
+ * @private
64
121
  */
65
122
  getQueryBuilder(entity, action) {
66
123
  const repository = this.getRepository(entity);
@@ -79,25 +136,48 @@ class Zorm {
79
136
  }
80
137
  }
81
138
  /**
82
- * Get a repository for a specific entity
139
+ * Retrieves the repository for a given entity.
140
+ * @param {EntityTarget<T>} entity - The entity target.
141
+ * @returns {Repository<T>} The repository instance.
83
142
  */
84
143
  getRepository(entity) {
85
144
  return this.dataSource.getRepository(entity);
86
145
  }
146
+ /**
147
+ * Creates a new record in the database.
148
+ * @param {EntityTarget<T>} entity - The entity target.
149
+ * @returns {ZormQueryBuilder<T, InsertQueryResult>} The query builder instance.
150
+ */
87
151
  create(entity) {
88
152
  return this.getQueryBuilder(entity, "create");
89
153
  }
154
+ /**
155
+ * Finds records in the database.
156
+ * @param {EntityTarget<T>} entity - The entity target.
157
+ * @returns {ZormQueryBuilder<T, SelectQueryResult>} The query builder instance.
158
+ */
90
159
  find(entity) {
91
160
  return this.getQueryBuilder(entity, "select");
92
161
  }
93
162
  // upsert<T extends ObjectLiteral>(entity: EntityTarget<T>): ZormQueryBuilder<T, InsertQueryResult> {
94
163
  // return this.getQueryBuilder(entity, "upsert");
95
164
  // }
165
+ /**
166
+ * Updates records in the database.
167
+ * @param {EntityTarget<T>} entity - The entity target.
168
+ * @returns {ZormQueryBuilder<T, UpdateQueryResult>} The query builder instance.
169
+ */
96
170
  update(entity) {
97
171
  return this.getQueryBuilder(entity, "update");
98
172
  }
173
+ /**
174
+ * Deletes records from the database.
175
+ * @param {EntityTarget<T>} entity - The entity target.
176
+ * @returns {ZormQueryBuilder<T, DeleteQueryResult>} The query builder instance.
177
+ */
99
178
  delete(entity) {
100
179
  return this.getQueryBuilder(entity, "delete");
101
180
  }
102
181
  }
103
182
  exports.default = Zorm;
183
+ __exportStar(require("./types.js"), exports);
package/dist/types.d.ts CHANGED
@@ -39,6 +39,8 @@ export type SelectQueryResult = {
39
39
  };
40
40
  export type UpdateQueryResult = {
41
41
  updated: boolean;
42
+ record?: ObjectLiteral;
43
+ records?: ObjectLiteral[];
42
44
  error?: QueryError;
43
45
  };
44
46
  export type DeleteQueryResult = {
@@ -46,3 +48,4 @@ export type DeleteQueryResult = {
46
48
  count: number;
47
49
  error?: QueryError;
48
50
  };
51
+ export { Entity, PrimaryColumn, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm";
package/dist/types.js CHANGED
@@ -1,2 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseEntity = exports.Column = exports.PrimaryGeneratedColumn = exports.PrimaryColumn = exports.Entity = void 0;
4
+ var typeorm_1 = require("typeorm");
5
+ Object.defineProperty(exports, "Entity", { enumerable: true, get: function () { return typeorm_1.Entity; } });
6
+ Object.defineProperty(exports, "PrimaryColumn", { enumerable: true, get: function () { return typeorm_1.PrimaryColumn; } });
7
+ Object.defineProperty(exports, "PrimaryGeneratedColumn", { enumerable: true, get: function () { return typeorm_1.PrimaryGeneratedColumn; } });
8
+ Object.defineProperty(exports, "Column", { enumerable: true, get: function () { return typeorm_1.Column; } });
9
+ Object.defineProperty(exports, "BaseEntity", { enumerable: true, get: function () { return typeorm_1.BaseEntity; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuzjs/orm",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "keywords": [
5
5
  "orm",
6
6
  "zuz",
@@ -28,6 +28,7 @@
28
28
  "engines": {
29
29
  "node": ">=18.17.0"
30
30
  },
31
+ "sideEffects": ["reflect-metadata"],
31
32
  "dependencies": {
32
33
  "@types/md5": "^2.3.5",
33
34
  "commander": "^13.1.0",