mevn-orm 3.2.2 → 4.0.1

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.
@@ -0,0 +1,51 @@
1
+ import type { Knex } from 'knex';
2
+ type Row = Record<string, unknown>;
3
+ declare class Model {
4
+ #private;
5
+ [key: string]: any;
6
+ static currentTable: string;
7
+ static currentQuery: Knex.QueryBuilder<Row, Row[]> | undefined;
8
+ fillable: string[];
9
+ hidden: string[];
10
+ modelName: string;
11
+ table: string;
12
+ id?: number;
13
+ constructor(properties?: Row);
14
+ /** Inserts the current model using `fillable` attributes and reloads it from the database. */
15
+ save(): Promise<this>;
16
+ /** Updates the current row by primary key and returns a refreshed model instance. */
17
+ update(properties: Row): Promise<this>;
18
+ /** Deletes the current row by primary key. */
19
+ delete(): Promise<void>;
20
+ /** Updates rows in the model table, optionally scoped by `where()`. */
21
+ static update(properties: Row): Promise<number | undefined>;
22
+ /** Deletes rows in the model table, optionally scoped by `where()`. */
23
+ static destroy(): Promise<number | undefined>;
24
+ /** Finds a single model by primary key. */
25
+ static find(this: typeof Model, id: number | string, columns?: string | string[]): Promise<Model | null>;
26
+ /** Finds a model by primary key or throws if it does not exist. */
27
+ static findOrFail(this: typeof Model, id: number | string, columns?: string | string[]): Promise<Model>;
28
+ /** Creates and returns a single model record. */
29
+ static create(this: typeof Model, properties: Row): Promise<Model>;
30
+ /** Creates multiple model records and returns created model instances. */
31
+ static createMany(this: typeof Model, properties: Row[]): Promise<Model[]>;
32
+ /** Returns the first matching row or creates it with merged values when missing. */
33
+ static firstOrCreate(this: typeof Model, attributes: Row, values?: Row): Promise<Model>;
34
+ /** Applies a query scope used by chained static query methods. */
35
+ static where(this: typeof Model, conditions?: Row): typeof Model;
36
+ /** Returns the first model for the current scope (or table if unscoped). */
37
+ static first(this: typeof Model, columns?: string | string[]): Promise<Model | null>;
38
+ /** Returns all models for the current scope (or table if unscoped). */
39
+ static all(this: typeof Model, columns?: string | string[]): Promise<Model[]>;
40
+ /** Returns a row count for the current scope (or table if unscoped). */
41
+ static count(this: typeof Model, column?: string): Promise<number>;
42
+ /** Removes internal and hidden fields from a model instance. */
43
+ stripColumns<T extends Model>(model: T, keepInternalState?: boolean): T;
44
+ }
45
+ interface Model {
46
+ hasOne(Related: typeof Model, localKey?: number | string, foreignKey?: string): Promise<Model | null>;
47
+ hasMany(Related: typeof Model, localKey?: number | string, foreignKey?: string): Promise<Model[]>;
48
+ belongsTo(Related: typeof Model, foreignKey?: string, ownerKey?: string): Promise<Model | null>;
49
+ }
50
+ export { Model };
51
+ export { DB, getDB, configure, createKnexConfig, configureDatabase, setMigrationConfig, getMigrationConfig, makeMigration, migrateLatest, migrateRollback, migrateCurrentVersion, migrateList, } from './config.js';
@@ -0,0 +1,243 @@
1
+ import pluralize from 'pluralize';
2
+ import { getDB } from './config.js';
3
+ import { createRelationshipMethods } from './relationships.js';
4
+ const toError = (error) => {
5
+ if (error instanceof Error) {
6
+ return error;
7
+ }
8
+ return new Error(String(error));
9
+ };
10
+ class Model {
11
+ #private;
12
+ static currentTable = pluralize(this.name.toLowerCase());
13
+ // `where()` stores a static scoped query consumed by `first()`.
14
+ static currentQuery;
15
+ fillable;
16
+ hidden;
17
+ modelName;
18
+ table;
19
+ id;
20
+ constructor(properties = {}) {
21
+ Object.assign(this, properties);
22
+ this.fillable = [];
23
+ this.hidden = [];
24
+ this.#private = ['fillable', 'hidden'];
25
+ this.modelName = this.constructor.name.toLowerCase();
26
+ this.table = pluralize(this.constructor.name.toLowerCase());
27
+ }
28
+ /** Inserts the current model using `fillable` attributes and reloads it from the database. */
29
+ async save() {
30
+ try {
31
+ const rows = {};
32
+ for (const field of this.fillable) {
33
+ rows[field] = this[field];
34
+ }
35
+ const inserted = await getDB()(this.table).insert(rows);
36
+ const idValue = Array.isArray(inserted) ? inserted[0] : inserted;
37
+ const id = typeof idValue === 'bigint' ? Number(idValue) : Number(idValue);
38
+ const fields = await getDB()(this.table).where({ id }).first();
39
+ if (!fields) {
40
+ throw new Error(`Failed to load inserted record for table "${this.table}"`);
41
+ }
42
+ Object.assign(this, fields);
43
+ this.id = id;
44
+ return this.stripColumns(this, true);
45
+ }
46
+ catch (error) {
47
+ throw toError(error);
48
+ }
49
+ }
50
+ /** Updates the current row by primary key and returns a refreshed model instance. */
51
+ async update(properties) {
52
+ if (this.id === undefined) {
53
+ throw new Error('Cannot update model without id');
54
+ }
55
+ try {
56
+ await getDB()(this.table).where({ id: this.id }).update(properties);
57
+ const fields = await getDB()(this.table).where({ id: this.id }).first();
58
+ if (!fields) {
59
+ throw new Error(`Failed to load updated record for table "${this.table}"`);
60
+ }
61
+ const next = new this.constructor(fields);
62
+ return this.stripColumns(next);
63
+ }
64
+ catch (error) {
65
+ throw toError(error);
66
+ }
67
+ }
68
+ /** Deletes the current row by primary key. */
69
+ async delete() {
70
+ if (this.id === undefined) {
71
+ throw new Error('Cannot delete model without id');
72
+ }
73
+ try {
74
+ await getDB()(this.table).where({ id: this.id }).del();
75
+ }
76
+ catch (error) {
77
+ throw toError(error);
78
+ }
79
+ }
80
+ /** Updates rows in the model table, optionally scoped by `where()`. */
81
+ static async update(properties) {
82
+ try {
83
+ const table = pluralize(this.name.toLowerCase());
84
+ const query = this.currentQuery ?? getDB()(table);
85
+ return await query.update(properties);
86
+ }
87
+ catch (error) {
88
+ throw toError(error);
89
+ }
90
+ finally {
91
+ this.currentQuery = undefined;
92
+ }
93
+ }
94
+ /** Deletes rows in the model table, optionally scoped by `where()`. */
95
+ static async destroy() {
96
+ try {
97
+ const table = pluralize(this.name.toLowerCase());
98
+ const query = this.currentQuery ?? getDB()(table);
99
+ return await query.delete();
100
+ }
101
+ catch (error) {
102
+ throw toError(error);
103
+ }
104
+ finally {
105
+ this.currentQuery = undefined;
106
+ }
107
+ }
108
+ /** Finds a single model by primary key. */
109
+ static async find(id, columns = '*') {
110
+ const table = pluralize(this.name.toLowerCase());
111
+ try {
112
+ const fields = await getDB()(table).where({ id }).first(columns);
113
+ return fields ? new this(fields) : null;
114
+ }
115
+ catch (error) {
116
+ throw toError(error);
117
+ }
118
+ }
119
+ /** Finds a model by primary key or throws if it does not exist. */
120
+ static async findOrFail(id, columns = '*') {
121
+ const found = await this.find(id, columns);
122
+ if (!found) {
123
+ throw new Error(`${this.name} with id "${id}" not found`);
124
+ }
125
+ return found;
126
+ }
127
+ /** Creates and returns a single model record. */
128
+ static async create(properties) {
129
+ const table = pluralize(this.name.toLowerCase());
130
+ try {
131
+ const inserted = await getDB()(table).insert(properties);
132
+ const idValue = Array.isArray(inserted) ? inserted[0] : inserted;
133
+ const id = typeof idValue === 'bigint' ? Number(idValue) : Number(idValue);
134
+ const record = await getDB()(table).where({ id }).first();
135
+ if (!record) {
136
+ throw new Error(`Failed to load created record for table "${table}"`);
137
+ }
138
+ const model = new this(record);
139
+ return model.stripColumns(model);
140
+ }
141
+ catch (error) {
142
+ throw toError(error);
143
+ }
144
+ }
145
+ /** Creates multiple model records and returns created model instances. */
146
+ static async createMany(properties) {
147
+ if (properties.length === 0) {
148
+ return [];
149
+ }
150
+ try {
151
+ const records = [];
152
+ for (const property of properties) {
153
+ records.push(await this.create(property));
154
+ }
155
+ return records;
156
+ }
157
+ catch (error) {
158
+ throw toError(error);
159
+ }
160
+ }
161
+ /** Returns the first matching row or creates it with merged values when missing. */
162
+ static async firstOrCreate(attributes, values = {}) {
163
+ const table = pluralize(this.name.toLowerCase());
164
+ try {
165
+ const record = await getDB()(table).where(attributes).first();
166
+ if (record) {
167
+ const model = new this(record);
168
+ return model.stripColumns(model);
169
+ }
170
+ return this.create({ ...attributes, ...values });
171
+ }
172
+ catch (error) {
173
+ throw toError(error);
174
+ }
175
+ }
176
+ /** Applies a query scope used by chained static query methods. */
177
+ static where(conditions = {}) {
178
+ const table = pluralize(this.name.toLowerCase());
179
+ this.currentQuery = getDB()(table).where(conditions);
180
+ return this;
181
+ }
182
+ /** Returns the first model for the current scope (or table if unscoped). */
183
+ static async first(columns = '*') {
184
+ try {
185
+ const table = pluralize(this.name.toLowerCase());
186
+ const query = this.currentQuery ?? getDB()(table);
187
+ const rows = await query.first(columns);
188
+ return rows ? new this(rows) : null;
189
+ }
190
+ catch (error) {
191
+ throw toError(error);
192
+ }
193
+ finally {
194
+ this.currentQuery = undefined;
195
+ }
196
+ }
197
+ /** Returns all models for the current scope (or table if unscoped). */
198
+ static async all(columns = '*') {
199
+ try {
200
+ const table = pluralize(this.name.toLowerCase());
201
+ const query = this.currentQuery ?? getDB()(table);
202
+ const rows = await query.select(columns);
203
+ return rows.map((row) => new this(row));
204
+ }
205
+ catch (error) {
206
+ throw toError(error);
207
+ }
208
+ finally {
209
+ this.currentQuery = undefined;
210
+ }
211
+ }
212
+ /** Returns a row count for the current scope (or table if unscoped). */
213
+ static async count(column = '*') {
214
+ try {
215
+ const table = pluralize(this.name.toLowerCase());
216
+ const query = this.currentQuery ?? getDB()(table);
217
+ const result = await query.count({ count: column }).first();
218
+ if (!result) {
219
+ return 0;
220
+ }
221
+ return Number(result.count);
222
+ }
223
+ catch (error) {
224
+ throw toError(error);
225
+ }
226
+ finally {
227
+ this.currentQuery = undefined;
228
+ }
229
+ }
230
+ /** Removes internal and hidden fields from a model instance. */
231
+ stripColumns(model, keepInternalState = false) {
232
+ // Hide internal ORM fields and caller-defined hidden attributes.
233
+ const privateKeys = keepInternalState ? [] : this.#private;
234
+ const hiddenKeys = Array.isArray(this.hidden) ? this.hidden : [];
235
+ for (const key of [...privateKeys, ...hiddenKeys]) {
236
+ delete model[key];
237
+ }
238
+ return model;
239
+ }
240
+ }
241
+ Object.assign(Model.prototype, createRelationshipMethods(getDB));
242
+ export { Model };
243
+ export { DB, getDB, configure, createKnexConfig, configureDatabase, setMigrationConfig, getMigrationConfig, makeMigration, migrateLatest, migrateRollback, migrateCurrentVersion, migrateList, } from './config.js';
@@ -0,0 +1,18 @@
1
+ import type { Knex } from 'knex';
2
+ type Row = Record<string, unknown>;
3
+ interface RelationshipModel {
4
+ [key: string]: unknown;
5
+ table: string;
6
+ modelName: string;
7
+ id?: number | string;
8
+ stripColumns<T extends RelationshipModel>(model: T, keepInternalState?: boolean): T;
9
+ }
10
+ type RelatedModelCtor = new (properties?: Row) => RelationshipModel;
11
+ interface RelationshipMethods {
12
+ hasOne(this: RelationshipModel, Related: RelatedModelCtor, localKey?: number | string, foreignKey?: string): Promise<RelationshipModel | null>;
13
+ hasMany(this: RelationshipModel, Related: RelatedModelCtor, localKey?: number | string, foreignKey?: string): Promise<RelationshipModel[]>;
14
+ belongsTo(this: RelationshipModel, Related: RelatedModelCtor, foreignKey?: string, ownerKey?: string): Promise<RelationshipModel | null>;
15
+ }
16
+ /** Builds relationship methods that run against the active Knex instance. */
17
+ declare const createRelationshipMethods: (getDB: () => Knex) => RelationshipMethods;
18
+ export { createRelationshipMethods };
@@ -0,0 +1,50 @@
1
+ /** Builds relationship methods that run against the active Knex instance. */
2
+ const createRelationshipMethods = (getDB) => ({
3
+ async hasOne(Related, localKey, foreignKey) {
4
+ const table = new Related().table;
5
+ const relation = {};
6
+ const keyValue = localKey ?? this.id;
7
+ const relationKey = foreignKey ?? `${this.modelName}_id`;
8
+ if (keyValue !== undefined) {
9
+ relation[relationKey] = keyValue;
10
+ const result = await getDB()(table).where(relation).first();
11
+ if (result) {
12
+ const related = new Related(result);
13
+ return related.stripColumns(related);
14
+ }
15
+ }
16
+ return null;
17
+ },
18
+ async hasMany(Related, localKey, foreignKey) {
19
+ const table = new Related().table;
20
+ const relation = {};
21
+ const keyValue = localKey ?? this.id;
22
+ const relationKey = foreignKey ?? `${this.modelName}_id`;
23
+ if (keyValue === undefined) {
24
+ return [];
25
+ }
26
+ relation[relationKey] = keyValue;
27
+ const rows = await getDB()(table).where(relation).select('*');
28
+ return rows.map((row) => {
29
+ const related = new Related(row);
30
+ return related.stripColumns(related);
31
+ });
32
+ },
33
+ async belongsTo(Related, foreignKey, ownerKey = 'id') {
34
+ const table = new Related().table;
35
+ const relation = {};
36
+ const relationKey = foreignKey ?? `${new Related().modelName}_id`;
37
+ const relationValue = this[relationKey];
38
+ if (relationValue === undefined || relationValue === null) {
39
+ return null;
40
+ }
41
+ relation[ownerKey] = relationValue;
42
+ const row = await getDB()(table).where(relation).first();
43
+ if (!row) {
44
+ return null;
45
+ }
46
+ const related = new Related(row);
47
+ return related.stripColumns(related);
48
+ },
49
+ });
50
+ export { createRelationshipMethods };
package/package.json CHANGED
@@ -1,17 +1,13 @@
1
1
  {
2
2
  "name": "mevn-orm",
3
- "version": "3.2.2",
3
+ "version": "4.0.1",
4
4
  "description": "simple ORM for express js",
5
- "type": "commonjs",
5
+ "type": "module",
6
6
  "peerDependencies": {
7
- "dotenv": "^17.0.1",
8
7
  "knex": "^3.0.0",
9
8
  "mysql2": "^3.9.3"
10
9
  },
11
10
  "peerDependenciesMeta": {
12
- "dotenv": {
13
- "optional": false
14
- },
15
11
  "knex": {
16
12
  "optional": false
17
13
  }
@@ -39,16 +35,18 @@
39
35
  "@babel/core": "^7.24.5",
40
36
  "@babel/eslint-parser": "^7.24.3",
41
37
  "@babel/eslint-plugin": "^7.24.0",
38
+ "@types/node": "^24.6.0",
42
39
  "@faker-js/faker": "^10.0.0",
43
- "chai": "^6.2.0",
44
40
  "dotenv": "^17.0.1",
45
41
  "knex": "^3.0.0",
46
- "mocha": "^11.7.4",
42
+ "tsx": "^4.20.6",
43
+ "typescript": "^5.9.3",
44
+ "vitest": "^4.0.16",
47
45
  "mysql": "^2.18.1",
48
46
  "sqlite3": "^5.1.7"
49
47
  },
50
48
  "directories": {
51
- "lib": "lib",
49
+ "src": "src",
52
50
  "test": "test"
53
51
  },
54
52
  "private": false,
@@ -58,12 +56,29 @@
58
56
  "email": "stanleymasinde1@gmail.com"
59
57
  },
60
58
  "homepage": "https://github.com/StanleyMasinde/mevn-orm#readme",
61
- "main": "index.js",
59
+ "main": "dist/index.js",
60
+ "types": "dist/index.d.ts",
61
+ "exports": {
62
+ ".": {
63
+ "types": "./dist/index.d.ts",
64
+ "import": "./dist/index.js",
65
+ "default": "./dist/index.js"
66
+ }
67
+ },
68
+ "files": [
69
+ "dist"
70
+ ],
62
71
  "scripts": {
63
- "pretest": "node initDb",
64
- "test": "mocha --exit",
65
- "init:db": "node initDb",
66
- "migrate": "knex migrate:latest",
67
- "lint": "eslint --ext .js ./"
72
+ "pretest": "node --import tsx initDb.ts",
73
+ "test": "vitest run",
74
+ "init:db": "node --import tsx initDb.ts",
75
+ "typecheck": "tsc --noEmit",
76
+ "migrate": "node --import tsx scripts/migrate.ts latest",
77
+ "migrate:make": "node --import tsx scripts/migrate.ts make",
78
+ "migrate:rollback": "node --import tsx scripts/migrate.ts rollback",
79
+ "migrate:list": "node --import tsx scripts/migrate.ts list",
80
+ "migrate:version": "node --import tsx scripts/migrate.ts version",
81
+ "lint": "eslint --ext .js,.ts ./",
82
+ "build": "tsc -p tsconfig.build.json"
68
83
  }
69
84
  }
package/.env.example DELETED
@@ -1,9 +0,0 @@
1
- NODE_ENV=testing
2
-
3
- DB_HOST=localhost
4
- DB_USER=root
5
- DB_PASSWORD=
6
- DB_DATABASE=mevn_orm
7
- DB_CLIENT=mysql2
8
-
9
- TESTING_DB=sqlite3
package/.eslintrc.json DELETED
@@ -1,36 +0,0 @@
1
- {
2
- "env": {
3
- "commonjs": true,
4
- "es2021": true,
5
- "node": true
6
- },
7
- "extends": "eslint:recommended",
8
- "plugins": ["@babel"],
9
- "parser": "@babel/eslint-parser",
10
- "parserOptions": {
11
- "ecmaVersion": 12
12
- },
13
- "rules": {
14
- "no-console":"warn",
15
- "constructor-super":"off",
16
- "no-this-before-super":"off",
17
- "arrow-parens":"error",
18
- "class-methods-use-this":"error",
19
- "indent": [
20
- "error",
21
- "tab"
22
- ],
23
- "linebreak-style": [
24
- "error",
25
- "unix"
26
- ],
27
- "quotes": [
28
- "error",
29
- "single"
30
- ],
31
- "semi": [
32
- "error",
33
- "never"
34
- ]
35
- }
36
- }
package/.gitattributes DELETED
@@ -1,8 +0,0 @@
1
- .github export-ignore
2
- _config.yml export-ignore
3
- .gitignore export-ignore
4
- CODE_OF_CONDUCT.md export-ignore
5
- SECURITY.md export-ignore
6
- test export-ignore
7
- test.sh export-ignore
8
- initDb export-ignore
@@ -1,76 +0,0 @@
1
- # Contributor Covenant Code of Conduct
2
-
3
- ## Our Pledge
4
-
5
- In the interest of fostering an open and welcoming environment, we as
6
- contributors and maintainers pledge to making participation in our project and
7
- our community a harassment-free experience for everyone, regardless of age, body
8
- size, disability, ethnicity, sex characteristics, gender identity and expression,
9
- level of experience, education, socio-economic status, nationality, personal
10
- appearance, race, religion, or sexual identity and orientation.
11
-
12
- ## Our Standards
13
-
14
- Examples of behavior that contributes to creating a positive environment
15
- include:
16
-
17
- * Using welcoming and inclusive language
18
- * Being respectful of differing viewpoints and experiences
19
- * Gracefully accepting constructive criticism
20
- * Focusing on what is best for the community
21
- * Showing empathy towards other community members
22
-
23
- Examples of unacceptable behavior by participants include:
24
-
25
- * The use of sexualized language or imagery and unwelcome sexual attention or
26
- advances
27
- * Trolling, insulting/derogatory comments, and personal or political attacks
28
- * Public or private harassment
29
- * Publishing others' private information, such as a physical or electronic
30
- address, without explicit permission
31
- * Other conduct which could reasonably be considered inappropriate in a
32
- professional setting
33
-
34
- ## Our Responsibilities
35
-
36
- Project maintainers are responsible for clarifying the standards of acceptable
37
- behavior and are expected to take appropriate and fair corrective action in
38
- response to any instances of unacceptable behavior.
39
-
40
- Project maintainers have the right and responsibility to remove, edit, or
41
- reject comments, commits, code, wiki edits, issues, and other contributions
42
- that are not aligned to this Code of Conduct, or to ban temporarily or
43
- permanently any contributor for other behaviors that they deem inappropriate,
44
- threatening, offensive, or harmful.
45
-
46
- ## Scope
47
-
48
- This Code of Conduct applies both within project spaces and in public spaces
49
- when an individual is representing the project or its community. Examples of
50
- representing a project or community include using an official project e-mail
51
- address, posting via an official social media account, or acting as an appointed
52
- representative at an online or offline event. Representation of a project may be
53
- further defined and clarified by project maintainers.
54
-
55
- ## Enforcement
56
-
57
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
- reported by contacting the project team at stanleyoren@gmail.com. All
59
- complaints will be reviewed and investigated and will result in a response that
60
- is deemed necessary and appropriate to the circumstances. The project team is
61
- obligated to maintain confidentiality with regard to the reporter of an incident.
62
- Further details of specific enforcement policies may be posted separately.
63
-
64
- Project maintainers who do not follow or enforce the Code of Conduct in good
65
- faith may face temporary or permanent repercussions as determined by other
66
- members of the project's leadership.
67
-
68
- ## Attribution
69
-
70
- This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
- available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
-
73
- [homepage]: https://www.contributor-covenant.org
74
-
75
- For answers to common questions about this code of conduct, see
76
- https://www.contributor-covenant.org/faq