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.
- package/README.md +78 -170
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/src/config.d.ts +46 -0
- package/dist/src/config.js +196 -0
- package/dist/src/model.d.ts +51 -0
- package/dist/src/model.js +243 -0
- package/dist/src/relationships.d.ts +18 -0
- package/dist/src/relationships.js +50 -0
- package/package.json +15 -3
- package/.env.example +0 -9
- package/.eslintrc.json +0 -36
- package/.gitattributes +0 -8
- package/CODE_OF_CONDUCT.md +0 -76
- package/changelog.md +0 -135
- package/index.ts +0 -31
- package/initDb.ts +0 -112
- package/knexfile.ts +0 -46
- package/pnpm-workspace.yaml +0 -9
- package/scripts/migrate.ts +0 -97
- package/src/config.ts +0 -270
- package/src/model.ts +0 -301
- package/src/relationships.ts +0 -93
- package/tsconfig.json +0 -27
- package/types/pluralize.d.ts +0 -4
package/src/model.ts
DELETED
|
@@ -1,301 +0,0 @@
|
|
|
1
|
-
import type { Knex } from 'knex'
|
|
2
|
-
import pluralize from 'pluralize'
|
|
3
|
-
import { getDB } from './config.js'
|
|
4
|
-
import { createRelationshipMethods } from './relationships.js'
|
|
5
|
-
|
|
6
|
-
type Row = Record<string, unknown>
|
|
7
|
-
|
|
8
|
-
const toError = (error: unknown): Error => {
|
|
9
|
-
if (error instanceof Error) {
|
|
10
|
-
return error
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
return new Error(String(error))
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
class Model {
|
|
17
|
-
[key: string]: any
|
|
18
|
-
|
|
19
|
-
#private: string[]
|
|
20
|
-
|
|
21
|
-
static currentTable: string = pluralize(this.name.toLowerCase())
|
|
22
|
-
// `where()` stores a static scoped query consumed by `first()`.
|
|
23
|
-
static currentQuery: Knex.QueryBuilder<Row, Row[]> | undefined
|
|
24
|
-
|
|
25
|
-
fillable: string[]
|
|
26
|
-
hidden: string[]
|
|
27
|
-
modelName: string
|
|
28
|
-
table: string
|
|
29
|
-
id?: number
|
|
30
|
-
|
|
31
|
-
constructor(properties: Row = {}) {
|
|
32
|
-
Object.assign(this, properties)
|
|
33
|
-
this.fillable = []
|
|
34
|
-
this.hidden = []
|
|
35
|
-
this.#private = ['fillable', 'hidden']
|
|
36
|
-
this.modelName = this.constructor.name.toLowerCase()
|
|
37
|
-
this.table = pluralize(this.constructor.name.toLowerCase())
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/** Inserts the current model using `fillable` attributes and reloads it from the database. */
|
|
41
|
-
async save(): Promise<this> {
|
|
42
|
-
try {
|
|
43
|
-
const rows: Row = {}
|
|
44
|
-
for (const field of this.fillable) {
|
|
45
|
-
rows[field] = this[field]
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
const inserted = await getDB()(this.table).insert(rows)
|
|
49
|
-
const idValue = Array.isArray(inserted) ? inserted[0] : inserted
|
|
50
|
-
const id = typeof idValue === 'bigint' ? Number(idValue) : Number(idValue)
|
|
51
|
-
const fields = await getDB()(this.table).where({ id }).first<Row>()
|
|
52
|
-
|
|
53
|
-
if (!fields) {
|
|
54
|
-
throw new Error(`Failed to load inserted record for table "${this.table}"`)
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
Object.assign(this, fields)
|
|
58
|
-
this.id = id
|
|
59
|
-
return this.stripColumns(this, true)
|
|
60
|
-
} catch (error) {
|
|
61
|
-
throw toError(error)
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/** Updates the current row by primary key and returns a refreshed model instance. */
|
|
66
|
-
async update(properties: Row): Promise<this> {
|
|
67
|
-
if (this.id === undefined) {
|
|
68
|
-
throw new Error('Cannot update model without id')
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
try {
|
|
72
|
-
await getDB()(this.table).where({ id: this.id }).update(properties)
|
|
73
|
-
const fields = await getDB()(this.table).where({ id: this.id }).first<Row>()
|
|
74
|
-
|
|
75
|
-
if (!fields) {
|
|
76
|
-
throw new Error(`Failed to load updated record for table "${this.table}"`)
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const next = new (this.constructor as new (props: Row) => this)(fields)
|
|
80
|
-
return this.stripColumns(next)
|
|
81
|
-
} catch (error) {
|
|
82
|
-
throw toError(error)
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** Deletes the current row by primary key. */
|
|
87
|
-
async delete(): Promise<void> {
|
|
88
|
-
if (this.id === undefined) {
|
|
89
|
-
throw new Error('Cannot delete model without id')
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
try {
|
|
93
|
-
await getDB()(this.table).where({ id: this.id }).del()
|
|
94
|
-
} catch (error) {
|
|
95
|
-
throw toError(error)
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** Updates rows in the model table, optionally scoped by `where()`. */
|
|
100
|
-
static async update(properties: Row): Promise<number | undefined> {
|
|
101
|
-
try {
|
|
102
|
-
const table = pluralize(this.name.toLowerCase())
|
|
103
|
-
const query = this.currentQuery ?? getDB()(table)
|
|
104
|
-
return await query.update(properties)
|
|
105
|
-
} catch (error) {
|
|
106
|
-
throw toError(error)
|
|
107
|
-
} finally {
|
|
108
|
-
this.currentQuery = undefined
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** Deletes rows in the model table, optionally scoped by `where()`. */
|
|
113
|
-
static async destroy(): Promise<number | undefined> {
|
|
114
|
-
try {
|
|
115
|
-
const table = pluralize(this.name.toLowerCase())
|
|
116
|
-
const query = this.currentQuery ?? getDB()(table)
|
|
117
|
-
return await query.delete()
|
|
118
|
-
} catch (error) {
|
|
119
|
-
throw toError(error)
|
|
120
|
-
} finally {
|
|
121
|
-
this.currentQuery = undefined
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/** Finds a single model by primary key. */
|
|
126
|
-
static async find(this: typeof Model, id: number | string, columns: string | string[] = '*'): Promise<Model | null> {
|
|
127
|
-
const table = pluralize(this.name.toLowerCase())
|
|
128
|
-
|
|
129
|
-
try {
|
|
130
|
-
const fields = await getDB()(table).where({ id }).first<Row>(columns as never)
|
|
131
|
-
return fields ? new this(fields) : null
|
|
132
|
-
} catch (error) {
|
|
133
|
-
throw toError(error)
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/** Finds a model by primary key or throws if it does not exist. */
|
|
138
|
-
static async findOrFail(this: typeof Model, id: number | string, columns: string | string[] = '*'): Promise<Model> {
|
|
139
|
-
const found = await this.find(id, columns)
|
|
140
|
-
if (!found) {
|
|
141
|
-
throw new Error(`${this.name} with id "${id}" not found`)
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
return found
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/** Creates and returns a single model record. */
|
|
148
|
-
static async create(this: typeof Model, properties: Row): Promise<Model> {
|
|
149
|
-
const table = pluralize(this.name.toLowerCase())
|
|
150
|
-
|
|
151
|
-
try {
|
|
152
|
-
const inserted = await getDB()(table).insert(properties)
|
|
153
|
-
const idValue = Array.isArray(inserted) ? inserted[0] : inserted
|
|
154
|
-
const id = typeof idValue === 'bigint' ? Number(idValue) : Number(idValue)
|
|
155
|
-
const record = await getDB()(table).where({ id }).first<Row>()
|
|
156
|
-
|
|
157
|
-
if (!record) {
|
|
158
|
-
throw new Error(`Failed to load created record for table "${table}"`)
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
const model = new this(record)
|
|
162
|
-
return model.stripColumns(model)
|
|
163
|
-
} catch (error) {
|
|
164
|
-
throw toError(error)
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/** Creates multiple model records and returns created model instances. */
|
|
169
|
-
static async createMany(this: typeof Model, properties: Row[]): Promise<Model[]> {
|
|
170
|
-
if (properties.length === 0) {
|
|
171
|
-
return []
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
try {
|
|
175
|
-
const records: Model[] = []
|
|
176
|
-
for (const property of properties) {
|
|
177
|
-
records.push(await this.create(property))
|
|
178
|
-
}
|
|
179
|
-
return records
|
|
180
|
-
} catch (error) {
|
|
181
|
-
throw toError(error)
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** Returns the first matching row or creates it with merged values when missing. */
|
|
186
|
-
static async firstOrCreate(this: typeof Model, attributes: Row, values: Row = {}): Promise<Model> {
|
|
187
|
-
const table = pluralize(this.name.toLowerCase())
|
|
188
|
-
try {
|
|
189
|
-
const record = await getDB()(table).where(attributes).first<Row>()
|
|
190
|
-
if (record) {
|
|
191
|
-
const model = new this(record)
|
|
192
|
-
return model.stripColumns(model)
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
return this.create({ ...attributes, ...values })
|
|
196
|
-
} catch (error) {
|
|
197
|
-
throw toError(error)
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/** Applies a query scope used by chained static query methods. */
|
|
202
|
-
static where(this: typeof Model, conditions: Row = {}): typeof Model {
|
|
203
|
-
const table = pluralize(this.name.toLowerCase())
|
|
204
|
-
this.currentQuery = getDB()(table).where(conditions) as Knex.QueryBuilder<Row, Row[]>
|
|
205
|
-
return this
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
/** Returns the first model for the current scope (or table if unscoped). */
|
|
209
|
-
static async first(this: typeof Model, columns: string | string[] = '*'): Promise<Model | null> {
|
|
210
|
-
try {
|
|
211
|
-
const table = pluralize(this.name.toLowerCase())
|
|
212
|
-
const query = this.currentQuery ?? getDB()(table)
|
|
213
|
-
const rows = await query.first<Row>(columns as never)
|
|
214
|
-
return rows ? new this(rows) : null
|
|
215
|
-
} catch (error) {
|
|
216
|
-
throw toError(error)
|
|
217
|
-
} finally {
|
|
218
|
-
this.currentQuery = undefined
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/** Returns all models for the current scope (or table if unscoped). */
|
|
223
|
-
static async all(this: typeof Model, columns: string | string[] = '*'): Promise<Model[]> {
|
|
224
|
-
try {
|
|
225
|
-
const table = pluralize(this.name.toLowerCase())
|
|
226
|
-
const query = this.currentQuery ?? getDB()(table)
|
|
227
|
-
const rows = await query.select<Row[]>(columns as never)
|
|
228
|
-
return rows.map((row) => new this(row))
|
|
229
|
-
} catch (error) {
|
|
230
|
-
throw toError(error)
|
|
231
|
-
} finally {
|
|
232
|
-
this.currentQuery = undefined
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
/** Returns a row count for the current scope (or table if unscoped). */
|
|
237
|
-
static async count(this: typeof Model, column = '*'): Promise<number> {
|
|
238
|
-
try {
|
|
239
|
-
const table = pluralize(this.name.toLowerCase())
|
|
240
|
-
const query = this.currentQuery ?? getDB()(table)
|
|
241
|
-
const result = await query.count<{ count: string | number }>({ count: column }).first()
|
|
242
|
-
if (!result) {
|
|
243
|
-
return 0
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
return Number(result.count)
|
|
247
|
-
} catch (error) {
|
|
248
|
-
throw toError(error)
|
|
249
|
-
} finally {
|
|
250
|
-
this.currentQuery = undefined
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/** Removes internal and hidden fields from a model instance. */
|
|
255
|
-
stripColumns<T extends Model>(model: T, keepInternalState = false): T {
|
|
256
|
-
// Hide internal ORM fields and caller-defined hidden attributes.
|
|
257
|
-
const privateKeys = keepInternalState ? [] : this.#private
|
|
258
|
-
const hiddenKeys = Array.isArray(this.hidden) ? this.hidden : []
|
|
259
|
-
for (const key of [...privateKeys, ...hiddenKeys]) {
|
|
260
|
-
delete model[key]
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
return model
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
interface Model {
|
|
268
|
-
hasOne(
|
|
269
|
-
Related: typeof Model,
|
|
270
|
-
localKey?: number | string,
|
|
271
|
-
foreignKey?: string,
|
|
272
|
-
): Promise<Model | null>
|
|
273
|
-
hasMany(
|
|
274
|
-
Related: typeof Model,
|
|
275
|
-
localKey?: number | string,
|
|
276
|
-
foreignKey?: string,
|
|
277
|
-
): Promise<Model[]>
|
|
278
|
-
belongsTo(
|
|
279
|
-
Related: typeof Model,
|
|
280
|
-
foreignKey?: string,
|
|
281
|
-
ownerKey?: string,
|
|
282
|
-
): Promise<Model | null>
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
Object.assign(Model.prototype, createRelationshipMethods(getDB) as Pick<Model, 'hasOne' | 'hasMany' | 'belongsTo'>)
|
|
286
|
-
|
|
287
|
-
export { Model }
|
|
288
|
-
export {
|
|
289
|
-
DB,
|
|
290
|
-
getDB,
|
|
291
|
-
configure,
|
|
292
|
-
createKnexConfig,
|
|
293
|
-
configureDatabase,
|
|
294
|
-
setMigrationConfig,
|
|
295
|
-
getMigrationConfig,
|
|
296
|
-
makeMigration,
|
|
297
|
-
migrateLatest,
|
|
298
|
-
migrateRollback,
|
|
299
|
-
migrateCurrentVersion,
|
|
300
|
-
migrateList,
|
|
301
|
-
} from './config.js'
|
package/src/relationships.ts
DELETED
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import type { Knex } from 'knex'
|
|
2
|
-
|
|
3
|
-
type Row = Record<string, unknown>
|
|
4
|
-
|
|
5
|
-
interface RelationshipModel {
|
|
6
|
-
[key: string]: unknown
|
|
7
|
-
table: string
|
|
8
|
-
modelName: string
|
|
9
|
-
id?: number | string
|
|
10
|
-
stripColumns<T extends RelationshipModel>(model: T, keepInternalState?: boolean): T
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
type RelatedModelCtor = new (properties?: Row) => RelationshipModel
|
|
14
|
-
|
|
15
|
-
interface RelationshipMethods {
|
|
16
|
-
hasOne(
|
|
17
|
-
this: RelationshipModel,
|
|
18
|
-
Related: RelatedModelCtor,
|
|
19
|
-
localKey?: number | string,
|
|
20
|
-
foreignKey?: string,
|
|
21
|
-
): Promise<RelationshipModel | null>
|
|
22
|
-
hasMany(
|
|
23
|
-
this: RelationshipModel,
|
|
24
|
-
Related: RelatedModelCtor,
|
|
25
|
-
localKey?: number | string,
|
|
26
|
-
foreignKey?: string,
|
|
27
|
-
): Promise<RelationshipModel[]>
|
|
28
|
-
belongsTo(
|
|
29
|
-
this: RelationshipModel,
|
|
30
|
-
Related: RelatedModelCtor,
|
|
31
|
-
foreignKey?: string,
|
|
32
|
-
ownerKey?: string,
|
|
33
|
-
): Promise<RelationshipModel | null>
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Builds relationship methods that run against the active Knex instance. */
|
|
37
|
-
const createRelationshipMethods = (getDB: () => Knex): RelationshipMethods => ({
|
|
38
|
-
async hasOne(this: RelationshipModel, Related: RelatedModelCtor, localKey?: number | string, foreignKey?: string) {
|
|
39
|
-
const table = new Related().table
|
|
40
|
-
const relation: Row = {}
|
|
41
|
-
const keyValue = localKey ?? this.id
|
|
42
|
-
const relationKey = foreignKey ?? `${this.modelName}_id`
|
|
43
|
-
|
|
44
|
-
if (keyValue !== undefined) {
|
|
45
|
-
relation[relationKey] = keyValue
|
|
46
|
-
const result = await getDB()(table).where(relation).first<Row>()
|
|
47
|
-
if (result) {
|
|
48
|
-
const related = new Related(result)
|
|
49
|
-
return related.stripColumns(related)
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
return null
|
|
54
|
-
},
|
|
55
|
-
async hasMany(this: RelationshipModel, Related: RelatedModelCtor, localKey?: number | string, foreignKey?: string) {
|
|
56
|
-
const table = new Related().table
|
|
57
|
-
const relation: Row = {}
|
|
58
|
-
const keyValue = localKey ?? this.id
|
|
59
|
-
const relationKey = foreignKey ?? `${this.modelName}_id`
|
|
60
|
-
|
|
61
|
-
if (keyValue === undefined) {
|
|
62
|
-
return []
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
relation[relationKey] = keyValue
|
|
66
|
-
const rows = await getDB()(table).where(relation).select<Row[]>('*')
|
|
67
|
-
return rows.map((row) => {
|
|
68
|
-
const related = new Related(row)
|
|
69
|
-
return related.stripColumns(related)
|
|
70
|
-
})
|
|
71
|
-
},
|
|
72
|
-
async belongsTo(this: RelationshipModel, Related: RelatedModelCtor, foreignKey?: string, ownerKey = 'id') {
|
|
73
|
-
const table = new Related().table
|
|
74
|
-
const relation: Row = {}
|
|
75
|
-
const relationKey = foreignKey ?? `${new Related().modelName}_id`
|
|
76
|
-
const relationValue = this[relationKey]
|
|
77
|
-
|
|
78
|
-
if (relationValue === undefined || relationValue === null) {
|
|
79
|
-
return null
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
relation[ownerKey] = relationValue
|
|
83
|
-
const row = await getDB()(table).where(relation).first<Row>()
|
|
84
|
-
if (!row) {
|
|
85
|
-
return null
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const related = new Related(row)
|
|
89
|
-
return related.stripColumns(related)
|
|
90
|
-
},
|
|
91
|
-
})
|
|
92
|
-
|
|
93
|
-
export { createRelationshipMethods }
|
package/tsconfig.json
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "ES2022",
|
|
4
|
-
"module": "NodeNext",
|
|
5
|
-
"moduleResolution": "NodeNext",
|
|
6
|
-
"strict": true,
|
|
7
|
-
"noImplicitOverride": true,
|
|
8
|
-
"noUncheckedIndexedAccess": true,
|
|
9
|
-
"exactOptionalPropertyTypes": true,
|
|
10
|
-
"useUnknownInCatchVariables": true,
|
|
11
|
-
"noEmit": true,
|
|
12
|
-
"skipLibCheck": false,
|
|
13
|
-
"esModuleInterop": false,
|
|
14
|
-
"forceConsistentCasingInFileNames": true,
|
|
15
|
-
"types": [
|
|
16
|
-
"node",
|
|
17
|
-
"vitest/globals"
|
|
18
|
-
]
|
|
19
|
-
},
|
|
20
|
-
"include": [
|
|
21
|
-
"**/*.ts",
|
|
22
|
-
"**/*.d.ts"
|
|
23
|
-
],
|
|
24
|
-
"exclude": [
|
|
25
|
-
"node_modules"
|
|
26
|
-
]
|
|
27
|
-
}
|
package/types/pluralize.d.ts
DELETED