mevn-orm 4.0.0 → 4.0.2

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,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,6 +1,6 @@
1
1
  {
2
2
  "name": "mevn-orm",
3
- "version": "4.0.0",
3
+ "version": "4.0.2",
4
4
  "description": "simple ORM for express js",
5
5
  "type": "module",
6
6
  "peerDependencies": {
@@ -56,7 +56,18 @@
56
56
  "email": "stanleymasinde1@gmail.com"
57
57
  },
58
58
  "homepage": "https://github.com/StanleyMasinde/mevn-orm#readme",
59
- "main": "index.ts",
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
+ ],
60
71
  "scripts": {
61
72
  "pretest": "node --import tsx initDb.ts",
62
73
  "test": "vitest run",
@@ -67,6 +78,7 @@
67
78
  "migrate:rollback": "node --import tsx scripts/migrate.ts rollback",
68
79
  "migrate:list": "node --import tsx scripts/migrate.ts list",
69
80
  "migrate:version": "node --import tsx scripts/migrate.ts version",
70
- "lint": "eslint --ext .js,.ts ./"
81
+ "lint": "eslint --ext .js,.ts ./",
82
+ "build": "tsc -p tsconfig.build.json"
71
83
  }
72
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
package/changelog.md DELETED
@@ -1,135 +0,0 @@
1
- ## [unreleased]
2
-
3
- ### 💼 Other
4
-
5
- - Use Node 16 until I figure out what is going on
6
- ## [3.2.0] - 2025-09-29
7
-
8
- ### 🐛 Bug Fixes
9
-
10
- - *(deps)* Bump actions/checkout from 4 to 5
11
- - *(deps)* Bump actions/setup-node from 4 to 5
12
-
13
- ### 💼 Other
14
-
15
- - Support the latest versions of node
16
- - Only use Node 20 for tests
17
-
18
- ### ⚙️ Miscellaneous Tasks
19
-
20
- - Upgrade deps
21
- ## [3.0.0] - 2025-07-02
22
-
23
- ### 🐛 Bug Fixes
24
-
25
- - *(deps)* Bump actions/checkout from 3 to 4
26
- - *(deps)* Bump actions/setup-node from 3 to 4
27
-
28
- ### ⚙️ Miscellaneous Tasks
29
-
30
- - Upgrade deps
31
- ## [2.4.7-1] - 2023-03-08
32
-
33
- ### ⚙️ Miscellaneous Tasks
34
-
35
- - Update the default peer dep
36
- ## [2.4.6] - 2023-03-08
37
-
38
- ### ⚙️ Miscellaneous Tasks
39
-
40
- - Add auto publish to npm
41
- ## [2.4.5] - 2023-03-06
42
-
43
- ### 💼 Other
44
-
45
- - Update npm dependencies
46
-
47
- ### ⚙️ Miscellaneous Tasks
48
-
49
- - *(ci)* Drop support for node 14
50
- - *(version)* Release patch version 2.4.5
51
- ## [2.4.4] - 2023-01-04
52
-
53
- ### ⚙️ Miscellaneous Tasks
54
-
55
- - *(version)* Release patch version 2.4.4
56
- ## [2.4.3] - 2023-01-04
57
-
58
- ### ⚙️ Miscellaneous Tasks
59
-
60
- - *(version)* Release patch version 2.4.3
61
- ## [2.4.2] - 2023-01-03
62
-
63
- ### 🐛 Bug Fixes
64
-
65
- - *(deps)* Bump actions/checkout from 2 to 3 (#60)
66
-
67
- ### ⚙️ Miscellaneous Tasks
68
-
69
- - *(version)* Release patch version 2.4.2
70
- ## [2.4.1] - 2022-07-21
71
-
72
- ### ⚙️ Miscellaneous Tasks
73
-
74
- - *(version)* Release patch version 2.4.1
75
- ## [2.4.0] - 2022-07-20
76
-
77
- ### ⚙️ Miscellaneous Tasks
78
-
79
- - *(version)* Release minor version 2.4.0
80
- ## [2.3.7] - 2022-07-20
81
-
82
- ### 🐛 Bug Fixes
83
-
84
- - *(deps)* Bump actions/setup-node from 2 to 3 (#59)
85
- - *(dev)* Throwing error in the init db command that is used for setup
86
-
87
- ### ⚙️ Miscellaneous Tasks
88
-
89
- - *(dev)* The default database in .env.example is now mysql
90
- - *(dev)* Using sqlite 3 instead of @vscode/sqlite3
91
- - *(version)* Release patch version 2.3.7
92
- ## [2.3.6] - 2022-02-03
93
-
94
- ### 🐛 Bug Fixes
95
-
96
- - *(config)* Error when reolving config from the user defined config. file not found
97
- - *(knexfile)* The path of the knex file was still not updated to use either of the 2 .js or .cjs
98
-
99
- ### ⚙️ Miscellaneous Tasks
100
-
101
- - *(version)* Release patch version 2.3.2
102
- - *(version)* Release patch version 2.3.3
103
- - *(version)* Release patch version 2.3.4
104
- - *(version)* Release patch version 2.3.5
105
- - *(version)* Release patch version 2.3.6
106
- ## [2.3.1] - 2022-02-01
107
-
108
- ### ⚙️ Miscellaneous Tasks
109
-
110
- - *(version)* Release minor version 2.3.1
111
- ## [2.3.0] - 2022-02-01
112
-
113
- ### 🚀 Features
114
-
115
- - *(find)* Added the static find method
116
- - *(model)* Added the create method
117
- - *(update)* Added the instance update method
118
- - *(delete)* Added a delete method
119
-
120
- ### 🐛 Bug Fixes
121
-
122
- - *(deps)* Bump knex from 0.21.17 to 0.95.11 (#12)
123
- - *(exports)* Breaking changes were pushed with the previous change. the changes has been fixed
124
- - *(tableName)* Not hiding the table by default
125
- - *(first)* Fixed the first method
126
- - *(knexfile)* Loading knexfile from the current working dir instead of the root of the package
127
- - *(deps)* The latest knex version removed as a peer dep.
128
-
129
- ### ⚙️ Miscellaneous Tasks
130
-
131
- - *(package)* Updated package.json
132
- - *(es6)* Using .cjs for knexfile
133
- - *(version)* Release 2.2.13
134
- - *(version)* Release minor version 2.2.14
135
- - *(version)* Release minor version 2.3.0
package/index.ts DELETED
@@ -1,31 +0,0 @@
1
- import {
2
- Model,
3
- DB,
4
- getDB,
5
- configure,
6
- createKnexConfig,
7
- configureDatabase,
8
- setMigrationConfig,
9
- getMigrationConfig,
10
- makeMigration,
11
- migrateLatest,
12
- migrateRollback,
13
- migrateCurrentVersion,
14
- migrateList,
15
- } from './src/model.js'
16
-
17
- export {
18
- Model,
19
- DB,
20
- getDB,
21
- configure,
22
- createKnexConfig,
23
- configureDatabase,
24
- setMigrationConfig,
25
- getMigrationConfig,
26
- makeMigration,
27
- migrateLatest,
28
- migrateRollback,
29
- migrateCurrentVersion,
30
- migrateList,
31
- }