Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fe0b4d6d8f | |||
| ce1d22ff44 | |||
| b7bfb3e153 | |||
| e57819d318 | |||
| 0a9dd30909 | |||
| d92c8b5409 | |||
| 589cb7d579 | |||
| 3680ad1914 |
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@extollo/lib",
|
"name": "@extollo/lib",
|
||||||
"version": "0.5.7",
|
"version": "0.5.10",
|
||||||
"description": "The framework library that lifts up your code.",
|
"description": "The framework library that lifts up your code.",
|
||||||
"main": "lib/index.js",
|
"main": "lib/index.js",
|
||||||
"types": "lib/index.d.ts",
|
"types": "lib/index.d.ts",
|
||||||
|
|||||||
3
src/auth/external/oauth2/OAuth2Repository.ts
vendored
3
src/auth/external/oauth2/OAuth2Repository.ts
vendored
@@ -1,7 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
Authenticatable,
|
Authenticatable,
|
||||||
AuthenticatableCredentials,
|
AuthenticatableCredentials,
|
||||||
AuthenticatableIdentifier,
|
|
||||||
AuthenticatableRepository,
|
AuthenticatableRepository,
|
||||||
} from '../../types'
|
} from '../../types'
|
||||||
import {Inject, Injectable} from '../../../di'
|
import {Inject, Injectable} from '../../../di'
|
||||||
@@ -46,7 +45,7 @@ export class OAuth2Repository implements AuthenticatableRepository {
|
|||||||
return this.getAuthenticatableFromBearer(credentials.credential)
|
return this.getAuthenticatableFromBearer(credentials.credential)
|
||||||
}
|
}
|
||||||
|
|
||||||
getByIdentifier(id: AuthenticatableIdentifier): Awaitable<Maybe<Authenticatable>> {
|
getByIdentifier(): Awaitable<Maybe<Authenticatable>> {
|
||||||
return undefined
|
return undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
37
src/di/InjectionAware.ts
Normal file
37
src/di/InjectionAware.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import {Container} from './Container'
|
||||||
|
import {TypedDependencyKey} from './types'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for Injection-aware classes that automatically
|
||||||
|
* pass along their configured container to instances created
|
||||||
|
* via their `make` method.
|
||||||
|
*/
|
||||||
|
export class InjectionAware {
|
||||||
|
private ci: Container
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.ci = Container.getContainer()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set the container for this instance. */
|
||||||
|
public setContainer(ci: Container): this {
|
||||||
|
this.ci = ci
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the container for this instance. */
|
||||||
|
public getContainer(): Container {
|
||||||
|
return this.ci
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Instantiate a new injectable using the container. */
|
||||||
|
public make<T>(target: TypedDependencyKey<T>, ...parameters: any[]): T {
|
||||||
|
const inst = this.ci.make<T>(target, ...parameters)
|
||||||
|
|
||||||
|
if ( inst instanceof InjectionAware ) {
|
||||||
|
inst.setContainer(this.ci)
|
||||||
|
}
|
||||||
|
|
||||||
|
return inst
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,3 +13,4 @@ export * from './ScopedContainer'
|
|||||||
export * from './types'
|
export * from './types'
|
||||||
|
|
||||||
export * from './decorator/injection'
|
export * from './decorator/injection'
|
||||||
|
export * from './InjectionAware'
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import {Application} from './Application'
|
import {Application} from './Application'
|
||||||
import {Container, DependencyKey, Injectable} from '../di'
|
import {Container, Injectable, TypedDependencyKey} from '../di'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base type for a class that supports binding methods by string.
|
* Base type for a class that supports binding methods by string.
|
||||||
@@ -43,7 +43,7 @@ export class AppClass {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Call the `make()` method on the global container. */
|
/** Call the `make()` method on the global container. */
|
||||||
protected make<T>(target: DependencyKey, ...parameters: any[]): T {
|
protected make<T>(target: TypedDependencyKey<T>, ...parameters: any[]): T {
|
||||||
return this.container().make<T>(target, ...parameters)
|
return this.container().make<T>(target, ...parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -69,6 +69,13 @@ export abstract class AbstractBuilder<T> extends AppClass {
|
|||||||
*/
|
*/
|
||||||
public abstract getResultIterable(): AbstractResultIterable<T>
|
public abstract getResultIterable(): AbstractResultIterable<T>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a copy of this builder with its values finalized.
|
||||||
|
*/
|
||||||
|
public finalize(): AbstractBuilder<T> {
|
||||||
|
return this.clone()
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Clone the current query to a new AbstractBuilder instance with the same properties.
|
* Clone the current query to a new AbstractBuilder instance with the same properties.
|
||||||
*/
|
*/
|
||||||
@@ -489,7 +496,7 @@ export abstract class AbstractBuilder<T> extends AppClass {
|
|||||||
throw new ErrorWithContext(`No connection specified to execute update query.`)
|
throw new ErrorWithContext(`No connection specified to execute update query.`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const query = this.registeredConnection.dialect().renderUpdate(this, data)
|
const query = this.registeredConnection.dialect().renderUpdate(this.finalize(), data)
|
||||||
return this.registeredConnection.query(query)
|
return this.registeredConnection.query(query)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -515,7 +522,7 @@ export abstract class AbstractBuilder<T> extends AppClass {
|
|||||||
throw new ErrorWithContext(`No connection specified to execute update query.`)
|
throw new ErrorWithContext(`No connection specified to execute update query.`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const query = this.registeredConnection.dialect().renderDelete(this)
|
const query = this.registeredConnection.dialect().renderDelete(this.finalize())
|
||||||
return this.registeredConnection.query(query)
|
return this.registeredConnection.query(query)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -548,7 +555,7 @@ export abstract class AbstractBuilder<T> extends AppClass {
|
|||||||
throw new ErrorWithContext(`No connection specified to execute update query.`)
|
throw new ErrorWithContext(`No connection specified to execute update query.`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const query = this.registeredConnection.dialect().renderInsert(this, rowOrRows)
|
const query = this.registeredConnection.dialect().renderInsert(this.finalize(), rowOrRows)
|
||||||
return this.registeredConnection.query(query)
|
return this.registeredConnection.query(query)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -560,7 +567,7 @@ export abstract class AbstractBuilder<T> extends AppClass {
|
|||||||
throw new ErrorWithContext(`No connection specified to execute update query.`)
|
throw new ErrorWithContext(`No connection specified to execute update query.`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const query = this.registeredConnection.dialect().renderExistential(this)
|
const query = this.registeredConnection.dialect().renderExistential(this.finalize())
|
||||||
const result = await this.registeredConnection.query(query)
|
const result = await this.registeredConnection.query(query)
|
||||||
return Boolean(result.rows.first())
|
return Boolean(result.rows.first())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,6 @@ export class Builder extends AbstractBuilder<QueryRow> {
|
|||||||
throw new ErrorWithContext(`No connection specified to fetch iterator for query.`)
|
throw new ErrorWithContext(`No connection specified to fetch iterator for query.`)
|
||||||
}
|
}
|
||||||
|
|
||||||
return Container.getContainer().make<ResultIterable>(ResultIterable, this, this.registeredConnection)
|
return Container.getContainer().make<ResultIterable>(ResultIterable, this.finalize(), this.registeredConnection)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,16 @@ export * from './model/ModelResultIterable'
|
|||||||
export * from './model/events'
|
export * from './model/events'
|
||||||
export * from './model/Model'
|
export * from './model/Model'
|
||||||
|
|
||||||
|
export * from './model/relation/RelationBuilder'
|
||||||
|
export * from './model/relation/Relation'
|
||||||
|
export * from './model/relation/HasOneOrMany'
|
||||||
|
export * from './model/relation/HasOne'
|
||||||
|
export * from './model/relation/HasMany'
|
||||||
|
export * from './model/relation/decorators'
|
||||||
|
|
||||||
|
export * from './model/scope/Scope'
|
||||||
|
export * from './model/scope/ActiveScope'
|
||||||
|
|
||||||
export * from './support/SessionModel'
|
export * from './support/SessionModel'
|
||||||
export * from './support/ORMSession'
|
export * from './support/ORMSession'
|
||||||
export * from './support/CacheModel'
|
export * from './support/CacheModel'
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import {ModelKey, QueryRow, QuerySource} from '../types'
|
import {ModelKey, QueryRow, QuerySource} from '../types'
|
||||||
import {Container, Inject, Instantiable, StaticClass} from '../../di'
|
import {Container, Inject, Instantiable, isInstantiable, StaticClass} from '../../di'
|
||||||
import {DatabaseService} from '../DatabaseService'
|
import {DatabaseService} from '../DatabaseService'
|
||||||
import {ModelBuilder} from './ModelBuilder'
|
import {ModelBuilder} from './ModelBuilder'
|
||||||
import {getFieldsMeta, ModelField} from './Field'
|
import {getFieldsMeta, ModelField} from './Field'
|
||||||
import {deepCopy, Pipe, Collection, Awaitable, uuid4} from '../../util'
|
import {deepCopy, Pipe, Collection, Awaitable, uuid4, isKeyof} from '../../util'
|
||||||
import {EscapeValueObject} from '../dialect/SQLDialect'
|
import {EscapeValueObject} from '../dialect/SQLDialect'
|
||||||
import {AppClass} from '../../lifecycle/AppClass'
|
import {AppClass} from '../../lifecycle/AppClass'
|
||||||
import {Logging} from '../../service/Logging'
|
import {Logging} from '../../service/Logging'
|
||||||
@@ -17,6 +17,11 @@ import {ModelUpdatedEvent} from './events/ModelUpdatedEvent'
|
|||||||
import {ModelCreatingEvent} from './events/ModelCreatingEvent'
|
import {ModelCreatingEvent} from './events/ModelCreatingEvent'
|
||||||
import {ModelCreatedEvent} from './events/ModelCreatedEvent'
|
import {ModelCreatedEvent} from './events/ModelCreatedEvent'
|
||||||
import {EventBus} from '../../event/EventBus'
|
import {EventBus} from '../../event/EventBus'
|
||||||
|
import {Relation, RelationValue} from './relation/Relation'
|
||||||
|
import {HasOne} from './relation/HasOne'
|
||||||
|
import {HasMany} from './relation/HasMany'
|
||||||
|
import {HasOneOrMany} from './relation/HasOneOrMany'
|
||||||
|
import {Scope, ScopeClosure} from './scope/Scope'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base for classes that are mapped to tables in a database.
|
* Base for classes that are mapped to tables in a database.
|
||||||
@@ -83,6 +88,12 @@ export abstract class Model<T extends Model<T>> extends AppClass implements Bus
|
|||||||
*/
|
*/
|
||||||
protected static masks: string[] = []
|
protected static masks: string[] = []
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relations that should be eager-loaded by default.
|
||||||
|
* @protected
|
||||||
|
*/
|
||||||
|
protected with: (keyof T)[] = []
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The original row fetched from the database.
|
* The original row fetched from the database.
|
||||||
* @protected
|
* @protected
|
||||||
@@ -95,6 +106,14 @@ export abstract class Model<T extends Model<T>> extends AppClass implements Bus
|
|||||||
*/
|
*/
|
||||||
protected modelEventBusSubscribers: Collection<EventSubscriberEntry<any>> = new Collection<EventSubscriberEntry<any>>()
|
protected modelEventBusSubscribers: Collection<EventSubscriberEntry<any>> = new Collection<EventSubscriberEntry<any>>()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache of relation instances by property accessor.
|
||||||
|
* This is used by the `@Relation()` decorator to cache Relation instances.
|
||||||
|
*/
|
||||||
|
public relationCache: Collection<{ accessor: string | symbol, relation: Relation<T, any, any> }> = new Collection<{accessor: string | symbol; relation: Relation<T, any, any>}>()
|
||||||
|
|
||||||
|
protected scopes: Collection<{ accessor: string | Instantiable<Scope>, scope: ScopeClosure }> = new Collection<{accessor: string | Instantiable<Scope>; scope: ScopeClosure}>()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the table name for this model.
|
* Get the table name for this model.
|
||||||
*/
|
*/
|
||||||
@@ -155,6 +174,28 @@ export abstract class Model<T extends Model<T>> extends AppClass implements Bus
|
|||||||
builder.field(field.databaseKey)
|
builder.field(field.databaseKey)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if ( Array.isArray(this.prototype.with) ) {
|
||||||
|
// Try to get the eager-loaded relations statically, if possible
|
||||||
|
for (const relation of this.prototype.with) {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore
|
||||||
|
builder.with(relation)
|
||||||
|
}
|
||||||
|
} else if ( this.constructor.length < 1 ) {
|
||||||
|
// Otherwise, if we can instantiate the model without any arguments,
|
||||||
|
// do that and get the eager-loaded relations directly.
|
||||||
|
const inst = Container.getContainer().make<Model<any>>(this)
|
||||||
|
if ( Array.isArray(inst.with) ) {
|
||||||
|
for (const relation of inst.with) {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore
|
||||||
|
builder.with(relation)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.withScopes(this.prototype.scopes)
|
||||||
|
|
||||||
return builder
|
return builder
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,6 +348,12 @@ export abstract class Model<T extends Model<T>> extends AppClass implements Bus
|
|||||||
builder.field(field.databaseKey)
|
builder.field(field.databaseKey)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
for ( const relation of this.with ) {
|
||||||
|
builder.with(relation)
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.withScopes(this.scopes)
|
||||||
|
|
||||||
return builder
|
return builder
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -627,7 +674,7 @@ export abstract class Model<T extends Model<T>> extends AppClass implements Bus
|
|||||||
|
|
||||||
const data = result.rows.first()
|
const data = result.rows.first()
|
||||||
if ( data ) {
|
if ( data ) {
|
||||||
await this.assumeFromSource(result)
|
await this.assumeFromSource(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.dispatch(new ModelCreatedEvent<T>(this as any))
|
await this.dispatch(new ModelCreatedEvent<T>(this as any))
|
||||||
@@ -871,4 +918,208 @@ export abstract class Model<T extends Model<T>> extends AppClass implements Bus
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new one-to-one relation instance. Should be called from a method on the model:
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* class MyModel extends Model<MyModel> {
|
||||||
|
* @Related()
|
||||||
|
* public otherModel() {
|
||||||
|
* return this.hasOne(MyOtherModel)
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param related
|
||||||
|
* @param foreignKeyOverride
|
||||||
|
* @param localKeyOverride
|
||||||
|
*/
|
||||||
|
public hasOne<T2 extends Model<T2>>(related: Instantiable<T2>, foreignKeyOverride?: keyof T & string, localKeyOverride?: keyof T2 & string): HasOne<T, T2> {
|
||||||
|
return new HasOne<T, T2>(this as unknown as T, this.make(related), foreignKeyOverride, localKeyOverride)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new one-to-one relation instance. Should be called from a method on the model:
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* class MyModel extends Model<MyModel> {
|
||||||
|
* @Related()
|
||||||
|
* public otherModels() {
|
||||||
|
* return this.hasMany(MyOtherModel)
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param related
|
||||||
|
* @param foreignKeyOverride
|
||||||
|
* @param localKeyOverride
|
||||||
|
*/
|
||||||
|
public hasMany<T2 extends Model<T2>>(related: Instantiable<T2>, foreignKeyOverride?: keyof T & string, localKeyOverride?: keyof T2 & string): HasMany<T, T2> {
|
||||||
|
return new HasMany<T, T2>(this as unknown as T, this.make(related), foreignKeyOverride, localKeyOverride)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the inverse of a one-to-one relation. Should be called from a method on the model:
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* class MyModel extends Model<MyModel> {
|
||||||
|
* @Related()
|
||||||
|
* public otherModel() {
|
||||||
|
* return this.hasOne(MyOtherModel)
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* class MyOtherModel extends Model<MyOtherModel> {
|
||||||
|
* @Related()
|
||||||
|
* public myModel() {
|
||||||
|
* return this.belongsToOne(MyModel, 'otherModel')
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param related
|
||||||
|
* @param relationName
|
||||||
|
*/
|
||||||
|
public belongsToOne<T2 extends Model<T2>>(related: Instantiable<T>, relationName: keyof T2): HasOne<T, T2> {
|
||||||
|
const relatedInst = this.make(related) as T2
|
||||||
|
const relation = relatedInst.getRelation(relationName)
|
||||||
|
|
||||||
|
if ( !(relation instanceof HasOneOrMany) ) {
|
||||||
|
throw new TypeError(`Cannot create belongs to one relation. Inverse relation must be HasOneOrMany.`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const localKey = relation.localKey
|
||||||
|
const foreignKey = relation.foreignKey
|
||||||
|
|
||||||
|
if ( !isKeyof(localKey, this as unknown as T) || !isKeyof(foreignKey, relatedInst) ) {
|
||||||
|
throw new TypeError('Local or foreign keys do not exist on the base model.')
|
||||||
|
}
|
||||||
|
|
||||||
|
return new HasOne<T, T2>(this as unknown as T, relatedInst, localKey, foreignKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the inverse of a one-to-many relation. Should be called from a method on the model:
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* class MyModel extends Model<MyModel> {
|
||||||
|
* @Related()
|
||||||
|
* public otherModels() {
|
||||||
|
* return this.hasMany(MyOtherModel)
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* class MyOtherModel extends Model<MyOtherModel> {
|
||||||
|
* @Related()
|
||||||
|
* public myModels() {
|
||||||
|
* return this.belongsToMany(MyModel, 'otherModels')
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param related
|
||||||
|
* @param relationName
|
||||||
|
*/
|
||||||
|
public belongsToMany<T2 extends Model<T2>>(related: Instantiable<T>, relationName: keyof T2): HasMany<T, T2> {
|
||||||
|
const relatedInst = this.make(related) as T2
|
||||||
|
const relation = relatedInst.getRelation(relationName)
|
||||||
|
|
||||||
|
if ( !(relation instanceof HasOneOrMany) ) {
|
||||||
|
throw new TypeError(`Cannot create belongs to one relation. Inverse relation must be HasOneOrMany.`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const localKey = relation.localKey
|
||||||
|
const foreignKey = relation.foreignKey
|
||||||
|
|
||||||
|
if ( !isKeyof(localKey, this as unknown as T) || !isKeyof(foreignKey, relatedInst) ) {
|
||||||
|
throw new TypeError('Local or foreign keys do not exist on the base model.')
|
||||||
|
}
|
||||||
|
|
||||||
|
return new HasMany<T, T2>(this as unknown as T, relatedInst, localKey, foreignKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the relation instance returned by a method on this model.
|
||||||
|
* @param name
|
||||||
|
* @protected
|
||||||
|
*/
|
||||||
|
public getRelation<T2 extends Model<T2>>(name: keyof this): Relation<T, T2, RelationValue<T2>> {
|
||||||
|
const relFn = this[name]
|
||||||
|
|
||||||
|
if ( relFn instanceof Relation ) {
|
||||||
|
return relFn
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( typeof relFn === 'function' ) {
|
||||||
|
const rel = relFn.apply(relFn, this)
|
||||||
|
if ( rel instanceof Relation ) {
|
||||||
|
return rel
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new TypeError(`Cannot get relation of name: ${name}. Method does not return a Relation.`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a scope on the model.
|
||||||
|
* @param scope
|
||||||
|
* @protected
|
||||||
|
*/
|
||||||
|
protected scope(scope: Instantiable<Scope> | ScopeClosure): this {
|
||||||
|
if ( isInstantiable(scope) ) {
|
||||||
|
if ( !this.hasScope(scope) ) {
|
||||||
|
this.scopes.push({
|
||||||
|
accessor: scope,
|
||||||
|
scope: builder => (this.make<Scope>(scope)).apply(builder),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.scopes.push({
|
||||||
|
accessor: uuid4(),
|
||||||
|
scope,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a scope on the model with a specific name.
|
||||||
|
* @param name
|
||||||
|
* @param scope
|
||||||
|
* @protected
|
||||||
|
*/
|
||||||
|
protected namedScope(name: string, scope: Instantiable<Scope> | ScopeClosure): this {
|
||||||
|
if ( isInstantiable(scope) ) {
|
||||||
|
if ( !this.hasScope(scope) ) {
|
||||||
|
this.scopes.push({
|
||||||
|
accessor: name,
|
||||||
|
scope: builder => (this.make<Scope>(scope)).apply(builder),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.scopes.push({
|
||||||
|
accessor: name,
|
||||||
|
scope,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if the current model has a scope with the given identifier.
|
||||||
|
* @param name
|
||||||
|
* @protected
|
||||||
|
*/
|
||||||
|
protected hasScope(name: string | Instantiable<Scope>): boolean {
|
||||||
|
return Boolean(this.scopes.firstWhere('accessor', '=', name))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,11 +6,16 @@ import {ModelResultIterable} from './ModelResultIterable'
|
|||||||
import {Collection} from '../../util'
|
import {Collection} from '../../util'
|
||||||
import {ConstraintOperator, ModelKey, ModelKeys} from '../types'
|
import {ConstraintOperator, ModelKey, ModelKeys} from '../types'
|
||||||
import {EscapeValue} from '../dialect/SQLDialect'
|
import {EscapeValue} from '../dialect/SQLDialect'
|
||||||
|
import {Scope, ScopeClosure} from './scope/Scope'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementation of the abstract builder whose results yield instances of a given Model, `T`.
|
* Implementation of the abstract builder whose results yield instances of a given Model, `T`.
|
||||||
*/
|
*/
|
||||||
export class ModelBuilder<T extends Model<T>> extends AbstractBuilder<T> {
|
export class ModelBuilder<T extends Model<T>> extends AbstractBuilder<T> {
|
||||||
|
protected eagerLoadRelations: (keyof T)[] = []
|
||||||
|
|
||||||
|
protected appliedScopes: Collection<{ accessor: string | Instantiable<Scope>, scope: ScopeClosure }> = new Collection<{accessor: string | Instantiable<Scope>; scope: ScopeClosure}>()
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
/** The model class that is created for results of this query. */
|
/** The model class that is created for results of this query. */
|
||||||
protected readonly ModelClass: StaticClass<T, typeof Model> & Instantiable<T>,
|
protected readonly ModelClass: StaticClass<T, typeof Model> & Instantiable<T>,
|
||||||
@@ -18,12 +23,27 @@ export class ModelBuilder<T extends Model<T>> extends AbstractBuilder<T> {
|
|||||||
super()
|
super()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public withScopes(scopes: Collection<{ accessor: string | Instantiable<Scope>, scope: ScopeClosure }>): this {
|
||||||
|
this.appliedScopes = scopes.clone()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
public getNewInstance(): AbstractBuilder<T> {
|
public getNewInstance(): AbstractBuilder<T> {
|
||||||
return this.app().make<ModelBuilder<T>>(ModelBuilder)
|
return this.app().make<ModelBuilder<T>>(ModelBuilder, this.ModelClass)
|
||||||
}
|
}
|
||||||
|
|
||||||
public getResultIterable(): AbstractResultIterable<T> {
|
public getResultIterable(): AbstractResultIterable<T> {
|
||||||
return this.app().make<ModelResultIterable<T>>(ModelResultIterable, this, this.registeredConnection, this.ModelClass)
|
return this.app().make<ModelResultIterable<T>>(ModelResultIterable, this.finalize(), this.registeredConnection, this.ModelClass)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a copy of this builder with all of its values finalized.
|
||||||
|
* @override to apply scopes
|
||||||
|
*/
|
||||||
|
public finalize(): AbstractBuilder<T> {
|
||||||
|
const inst = super.finalize()
|
||||||
|
this.appliedScopes.each(rec => rec.scope(inst))
|
||||||
|
return inst
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -52,6 +72,42 @@ export class ModelBuilder<T extends Model<T>> extends AbstractBuilder<T> {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark a relation to be eager-loaded.
|
||||||
|
* @param relationName
|
||||||
|
*/
|
||||||
|
public with(relationName: keyof T): this {
|
||||||
|
if ( !this.eagerLoadRelations.includes(relationName) ) {
|
||||||
|
// Try to load the Relation so we fail if the name is invalid
|
||||||
|
this.make<T>(this.ModelClass).getRelation(relationName)
|
||||||
|
this.eagerLoadRelations.push(relationName)
|
||||||
|
}
|
||||||
|
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove all global scopes from this query.
|
||||||
|
*/
|
||||||
|
public withoutGlobalScopes(): this {
|
||||||
|
this.appliedScopes = new Collection<{accessor: string | Instantiable<Scope>; scope: ScopeClosure}>()
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a specific scope from this query by its identifier.
|
||||||
|
* @param name
|
||||||
|
*/
|
||||||
|
public withoutGlobalScope(name: string | Instantiable<Scope>): this {
|
||||||
|
this.appliedScopes = this.appliedScopes.where('accessor', '=', name)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the list of relations to eager-load. */
|
||||||
|
public getEagerLoadedRelations(): (keyof T)[] {
|
||||||
|
return [...this.eagerLoadRelations]
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Given some format of keys of the model, try to normalize them to a flat array.
|
* Given some format of keys of the model, try to normalize them to a flat array.
|
||||||
* @param keys
|
* @param keys
|
||||||
@@ -66,4 +122,15 @@ export class ModelBuilder<T extends Model<T>> extends AbstractBuilder<T> {
|
|||||||
|
|
||||||
return [keys]
|
return [keys]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a copy of this builder.
|
||||||
|
* @override to add implementation-specific pass-alongs.
|
||||||
|
*/
|
||||||
|
public clone(): ModelBuilder<T> {
|
||||||
|
const inst = super.clone() as ModelBuilder<T>
|
||||||
|
inst.eagerLoadRelations = [...this.eagerLoadRelations]
|
||||||
|
inst.appliedScopes = this.appliedScopes.clone()
|
||||||
|
return inst
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import {Connection} from '../connection/Connection'
|
|||||||
import {ModelBuilder} from './ModelBuilder'
|
import {ModelBuilder} from './ModelBuilder'
|
||||||
import {Container, Instantiable} from '../../di'
|
import {Container, Instantiable} from '../../di'
|
||||||
import {QueryRow} from '../types'
|
import {QueryRow} from '../types'
|
||||||
import {Collection} from '../../util'
|
import {collect, Collection} from '../../util'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementation of the result iterable that returns query results as instances of the defined model.
|
* Implementation of the result iterable that returns query results as instances of the defined model.
|
||||||
@@ -28,13 +28,17 @@ export class ModelResultIterable<T extends Model<T>> extends AbstractResultItera
|
|||||||
const row = (await this.connection.query(query)).rows.first()
|
const row = (await this.connection.query(query)).rows.first()
|
||||||
|
|
||||||
if ( row ) {
|
if ( row ) {
|
||||||
return this.inflateRow(row)
|
const inflated = await this.inflateRow(row)
|
||||||
|
await this.processEagerLoads(collect([inflated]))
|
||||||
|
return inflated
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async range(start: number, end: number): Promise<Collection<T>> {
|
async range(start: number, end: number): Promise<Collection<T>> {
|
||||||
const query = this.connection.dialect().renderRangedSelect(this.selectSQL, start, end)
|
const query = this.connection.dialect().renderRangedSelect(this.selectSQL, start, end)
|
||||||
return (await this.connection.query(query)).rows.promiseMap<T>(row => this.inflateRow(row))
|
const inflated = await (await this.connection.query(query)).rows.promiseMap<T>(row => this.inflateRow(row))
|
||||||
|
await this.processEagerLoads(inflated)
|
||||||
|
return inflated
|
||||||
}
|
}
|
||||||
|
|
||||||
async count(): Promise<number> {
|
async count(): Promise<number> {
|
||||||
@@ -45,7 +49,9 @@ export class ModelResultIterable<T extends Model<T>> extends AbstractResultItera
|
|||||||
|
|
||||||
async all(): Promise<Collection<T>> {
|
async all(): Promise<Collection<T>> {
|
||||||
const result = await this.connection.query(this.selectSQL)
|
const result = await this.connection.query(this.selectSQL)
|
||||||
return result.rows.promiseMap<T>(row => this.inflateRow(row))
|
const inflated = await result.rows.promiseMap<T>(row => this.inflateRow(row))
|
||||||
|
await this.processEagerLoads(inflated)
|
||||||
|
return inflated
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -58,6 +64,30 @@ export class ModelResultIterable<T extends Model<T>> extends AbstractResultItera
|
|||||||
.assumeFromSource(row)
|
.assumeFromSource(row)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Eager-load eager-loaded relations for the models in the query result.
|
||||||
|
* @param results
|
||||||
|
* @protected
|
||||||
|
*/
|
||||||
|
protected async processEagerLoads(results: Collection<T>): Promise<void> {
|
||||||
|
const eagers = this.builder.getEagerLoadedRelations()
|
||||||
|
const model = this.make<T>(this.ModelClass)
|
||||||
|
|
||||||
|
for ( const name of eagers ) {
|
||||||
|
// TODO support nested eager loads?
|
||||||
|
|
||||||
|
const relation = model.getRelation(name)
|
||||||
|
const select = relation.buildEagerQuery(this.builder, results)
|
||||||
|
|
||||||
|
const allRelated = await select.get().collect()
|
||||||
|
allRelated.each(result => {
|
||||||
|
const resultRelation = result.getRelation(name as any)
|
||||||
|
const resultRelated = resultRelation.matchResults(allRelated as any)
|
||||||
|
resultRelation.setValue(resultRelated as any)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
clone(): ModelResultIterable<T> {
|
clone(): ModelResultIterable<T> {
|
||||||
return new ModelResultIterable(this.builder, this.connection, this.ModelClass)
|
return new ModelResultIterable(this.builder, this.connection, this.ModelClass)
|
||||||
}
|
}
|
||||||
|
|||||||
47
src/orm/model/relation/HasMany.ts
Normal file
47
src/orm/model/relation/HasMany.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import {Model} from '../Model'
|
||||||
|
import {HasOneOrMany} from './HasOneOrMany'
|
||||||
|
import {Collection} from '../../../util'
|
||||||
|
import {RelationNotLoadedError} from './Relation'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One-to-many relation implementation.
|
||||||
|
*/
|
||||||
|
export class HasMany<T extends Model<T>, T2 extends Model<T2>> extends HasOneOrMany<T, T2, Collection<T2>> {
|
||||||
|
protected cachedValue?: Collection<T2>
|
||||||
|
|
||||||
|
protected cachedLoaded = false
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
parent: T,
|
||||||
|
related: T2,
|
||||||
|
foreignKeyOverride?: keyof T & string,
|
||||||
|
localKeyOverride?: keyof T2 & string,
|
||||||
|
) {
|
||||||
|
super(parent, related, foreignKeyOverride, localKeyOverride)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve the result of this relation. */
|
||||||
|
public get(): Promise<Collection<T2>> {
|
||||||
|
return this.fetch().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set the value of this relation. */
|
||||||
|
public setValue(related: Collection<T2>): void {
|
||||||
|
this.cachedValue = related.clone()
|
||||||
|
this.cachedLoaded = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the value of this relation. */
|
||||||
|
public getValue(): Collection<T2> {
|
||||||
|
if ( !this.cachedValue ) {
|
||||||
|
throw new RelationNotLoadedError()
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.cachedValue
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns true if the relation has been loaded. */
|
||||||
|
public isLoaded(): boolean {
|
||||||
|
return this.cachedLoaded
|
||||||
|
}
|
||||||
|
}
|
||||||
47
src/orm/model/relation/HasOne.ts
Normal file
47
src/orm/model/relation/HasOne.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
import {Model} from '../Model'
|
||||||
|
import {HasOneOrMany} from './HasOneOrMany'
|
||||||
|
import {RelationNotLoadedError} from './Relation'
|
||||||
|
import {Maybe} from '../../../util'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One-to-one relation implementation.
|
||||||
|
*/
|
||||||
|
export class HasOne<T extends Model<T>, T2 extends Model<T2>> extends HasOneOrMany<T, T2, Maybe<T2>> {
|
||||||
|
protected cachedValue?: T2
|
||||||
|
|
||||||
|
protected cachedLoaded = false
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
parent: T,
|
||||||
|
related: T2,
|
||||||
|
foreignKeyOverride?: keyof T & string,
|
||||||
|
localKeyOverride?: keyof T2 & string,
|
||||||
|
) {
|
||||||
|
super(parent, related, foreignKeyOverride, localKeyOverride)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve the result of this relation. */
|
||||||
|
async get(): Promise<Maybe<T2>> {
|
||||||
|
return this.fetch().first()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set the value of this relation. */
|
||||||
|
public setValue(related: T2): void {
|
||||||
|
this.cachedValue = related
|
||||||
|
this.cachedLoaded = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the value of this relation. */
|
||||||
|
public getValue(): Maybe<T2> {
|
||||||
|
if ( !this.cachedLoaded ) {
|
||||||
|
throw new RelationNotLoadedError()
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.cachedValue
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns true if the relation has been loaded. */
|
||||||
|
public isLoaded(): boolean {
|
||||||
|
return this.cachedLoaded
|
||||||
|
}
|
||||||
|
}
|
||||||
80
src/orm/model/relation/HasOneOrMany.ts
Normal file
80
src/orm/model/relation/HasOneOrMany.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import {Model} from '../Model'
|
||||||
|
import {Relation, RelationValue} from './Relation'
|
||||||
|
import {RelationBuilder} from './RelationBuilder'
|
||||||
|
import {raw} from '../../dialect/SQLDialect'
|
||||||
|
import {AbstractBuilder} from '../../builder/AbstractBuilder'
|
||||||
|
import {ModelBuilder} from '../ModelBuilder'
|
||||||
|
import {Collection, toString} from '../../../util'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for 1:1 and 1:M relations.
|
||||||
|
*/
|
||||||
|
export abstract class HasOneOrMany<T extends Model<T>, T2 extends Model<T2>, V extends RelationValue<T2>> extends Relation<T, T2, V> {
|
||||||
|
protected constructor(
|
||||||
|
parent: T,
|
||||||
|
related: T2,
|
||||||
|
|
||||||
|
/** Override the foreign key property. */
|
||||||
|
protected foreignKeyOverride?: keyof T & string,
|
||||||
|
|
||||||
|
/** Override the local key property. */
|
||||||
|
protected localKeyOverride?: keyof T2 & string,
|
||||||
|
) {
|
||||||
|
super(parent, related)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the name of the foreign key for this relation. */
|
||||||
|
public get foreignKey(): string {
|
||||||
|
return this.foreignKeyOverride || this.parent.keyName()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the name of the local key for this relation. */
|
||||||
|
public get localKey(): string {
|
||||||
|
return this.localKeyOverride || this.foreignKey
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the fully-qualified name of the foreign key. */
|
||||||
|
public get qualifiedForeignKey(): string {
|
||||||
|
return this.related.qualify(this.foreignKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the fully-qualified name of the local key. */
|
||||||
|
public get qualifiedLocalKey(): string {
|
||||||
|
return this.related.qualify(this.localKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the value of the pivot for this relation from the parent model. */
|
||||||
|
public get parentValue(): any {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore
|
||||||
|
return this.parent[this.localKey]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create a new query for this relation. */
|
||||||
|
public query(): RelationBuilder<T2> {
|
||||||
|
return this.builder().select(raw('*'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Apply the relation's constraints on a model query. */
|
||||||
|
public applyScope(where: AbstractBuilder<T2>): void {
|
||||||
|
where.where(subq => {
|
||||||
|
subq.where(this.qualifiedForeignKey, '=', this.parentValue)
|
||||||
|
.whereRaw(this.qualifiedForeignKey, 'IS NOT', 'NULL')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create an eager-load query matching this relation's models. */
|
||||||
|
public buildEagerQuery(parentQuery: ModelBuilder<T>, result: Collection<T>): ModelBuilder<T2> {
|
||||||
|
const keys = result.pluck(this.localKey as keyof T)
|
||||||
|
.map(toString)
|
||||||
|
.all()
|
||||||
|
|
||||||
|
return this.related.query()
|
||||||
|
.whereIn(this.foreignKey, keys)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Given a collection of results, filter out those that are relevant to this relation. */
|
||||||
|
public matchResults(possiblyRelated: Collection<T>): Collection<T> {
|
||||||
|
return possiblyRelated.where(this.foreignKey as keyof T, '=', this.parentValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
111
src/orm/model/relation/Relation.ts
Normal file
111
src/orm/model/relation/Relation.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import {Model} from '../Model'
|
||||||
|
import {ModelBuilder} from '../ModelBuilder'
|
||||||
|
import {AbstractBuilder} from '../../builder/AbstractBuilder'
|
||||||
|
import {ResultCollection} from '../../builder/result/ResultCollection'
|
||||||
|
import {Collection, ErrorWithContext, Maybe} from '../../../util'
|
||||||
|
import {QuerySource} from '../../types'
|
||||||
|
import {RelationBuilder} from './RelationBuilder'
|
||||||
|
import {InjectionAware} from '../../../di'
|
||||||
|
|
||||||
|
/** Type alias for possible values of a relation. */
|
||||||
|
export type RelationValue<T2> = Maybe<Collection<T2> | T2>
|
||||||
|
|
||||||
|
/** Error thrown when a relation result is accessed synchronously before it is loaded. */
|
||||||
|
export class RelationNotLoadedError extends ErrorWithContext {
|
||||||
|
constructor(
|
||||||
|
context: {[key: string]: any} = {},
|
||||||
|
) {
|
||||||
|
super('Attempted to get value of relation that has not yet been loaded.', context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for inter-model relation implementations.
|
||||||
|
*/
|
||||||
|
export abstract class Relation<T extends Model<T>, T2 extends Model<T2>, V extends RelationValue<T2>> extends InjectionAware {
|
||||||
|
protected constructor(
|
||||||
|
/** The model related from. */
|
||||||
|
protected parent: T,
|
||||||
|
|
||||||
|
/** The model related to. */
|
||||||
|
public readonly related: T2,
|
||||||
|
) {
|
||||||
|
super()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the value of the key field from the parent model. */
|
||||||
|
protected abstract get parentValue(): any
|
||||||
|
|
||||||
|
/** Create a new relation builder query for this relation instance. */
|
||||||
|
public abstract query(): RelationBuilder<T2>
|
||||||
|
|
||||||
|
/** Limit the results of the builder to only this relation's rows. */
|
||||||
|
public abstract applyScope(where: AbstractBuilder<T2>): void
|
||||||
|
|
||||||
|
/** Create a relation query that will eager-load the result of this relation for a set of models. */
|
||||||
|
public abstract buildEagerQuery(parentQuery: ModelBuilder<T>, result: Collection<T>): ModelBuilder<T2>
|
||||||
|
|
||||||
|
/** Given a set of possibly-related instances, filter out the ones that are relevant to the parent. */
|
||||||
|
public abstract matchResults(possiblyRelated: Collection<T>): Collection<T>
|
||||||
|
|
||||||
|
/** Set the value of the relation. */
|
||||||
|
public abstract setValue(related: V): void
|
||||||
|
|
||||||
|
/** Get the value of the relation. */
|
||||||
|
public abstract getValue(): V
|
||||||
|
|
||||||
|
/** Returns true if the relation has been loaded. */
|
||||||
|
public abstract isLoaded(): boolean
|
||||||
|
|
||||||
|
/** Get a collection of the results of this relation. */
|
||||||
|
public fetch(): ResultCollection<T2> {
|
||||||
|
return this.query().get()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve the result of this relation. */
|
||||||
|
public abstract get(): Promise<V>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes the relation "thenable" so relation methods on models can be awaited
|
||||||
|
* to yield the result of the relation.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```ts
|
||||||
|
* const rows = await myModelInstance.myHasManyRelation() -- rows is a Collection
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param resolve
|
||||||
|
* @param reject
|
||||||
|
*/
|
||||||
|
public then(resolve: (result: V) => unknown, reject: (e: Error) => unknown): void {
|
||||||
|
if ( this.isLoaded() ) {
|
||||||
|
resolve(this.getValue())
|
||||||
|
} else {
|
||||||
|
this.get()
|
||||||
|
.then(result => {
|
||||||
|
if ( result instanceof Collection ) {
|
||||||
|
this.setValue(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(result)
|
||||||
|
})
|
||||||
|
.catch(reject)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the value of this relation. */
|
||||||
|
public get value(): V {
|
||||||
|
return this.getValue()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the query source for the related model in this relation. */
|
||||||
|
public get relatedQuerySource(): QuerySource {
|
||||||
|
const related = this.related.constructor as typeof Model
|
||||||
|
return related.querySource()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get a new builder instance for this relation. */
|
||||||
|
public builder(): RelationBuilder<T2> {
|
||||||
|
return this.make(RelationBuilder, this)
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/orm/model/relation/RelationBuilder.ts
Normal file
14
src/orm/model/relation/RelationBuilder.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import {Model} from '../Model'
|
||||||
|
import {ModelBuilder} from '../ModelBuilder'
|
||||||
|
import {Relation} from './Relation'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ModelBuilder instance that queries the related model in a relation.
|
||||||
|
*/
|
||||||
|
export class RelationBuilder<T extends Model<T>> extends ModelBuilder<T> {
|
||||||
|
constructor(
|
||||||
|
protected relation: Relation<any, T, any>,
|
||||||
|
) {
|
||||||
|
super(relation.related.constructor as any)
|
||||||
|
}
|
||||||
|
}
|
||||||
37
src/orm/model/relation/decorators.ts
Normal file
37
src/orm/model/relation/decorators.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import {Model} from '../Model'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decorator for relation methods on a Model implementation.
|
||||||
|
* Caches the relation instances between uses for the life of the model.
|
||||||
|
* @constructor
|
||||||
|
*/
|
||||||
|
export function Related(): MethodDecorator {
|
||||||
|
return (target, propertyKey, descriptor) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore
|
||||||
|
const original = descriptor.value
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore
|
||||||
|
descriptor.value = function(...args) {
|
||||||
|
const model = this as Model<any>
|
||||||
|
const cache = model.relationCache
|
||||||
|
|
||||||
|
const existing = cache.firstWhere('accessor', '=', propertyKey)
|
||||||
|
if ( existing ) {
|
||||||
|
return existing.relation
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
// @ts-ignore
|
||||||
|
const value = original.apply(this, args)
|
||||||
|
|
||||||
|
cache.push({
|
||||||
|
accessor: propertyKey,
|
||||||
|
relation: value,
|
||||||
|
})
|
||||||
|
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
11
src/orm/model/scope/ActiveScope.ts
Normal file
11
src/orm/model/scope/ActiveScope.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import {Scope} from './Scope'
|
||||||
|
import {AbstractBuilder} from '../../builder/AbstractBuilder'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A basic scope to limit results where `active` = true.
|
||||||
|
*/
|
||||||
|
export class ActiveScope extends Scope {
|
||||||
|
apply(query: AbstractBuilder<any>): void {
|
||||||
|
query.where('active', '=', true)
|
||||||
|
}
|
||||||
|
}
|
||||||
18
src/orm/model/scope/Scope.ts
Normal file
18
src/orm/model/scope/Scope.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import {Injectable, InjectionAware} from '../../../di'
|
||||||
|
import {Awaitable} from '../../../util'
|
||||||
|
import {AbstractBuilder} from '../../builder/AbstractBuilder'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A closure that takes a query and applies some scope to it.
|
||||||
|
*/
|
||||||
|
export type ScopeClosure = (query: AbstractBuilder<any>) => Awaitable<void>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Base class for scopes that can be applied to queries.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export abstract class Scope extends InjectionAware {
|
||||||
|
|
||||||
|
abstract apply(query: AbstractBuilder<any>): Awaitable<void>
|
||||||
|
|
||||||
|
}
|
||||||
@@ -131,6 +131,7 @@ export enum FieldType {
|
|||||||
json = 'json',
|
json = 'json',
|
||||||
line = 'line',
|
line = 'line',
|
||||||
lseg = 'lseg',
|
lseg = 'lseg',
|
||||||
|
ltree = 'ltree',
|
||||||
macaddr = 'macaddr',
|
macaddr = 'macaddr',
|
||||||
money = 'money',
|
money = 'money',
|
||||||
numeric = 'numeric',
|
numeric = 'numeric',
|
||||||
@@ -189,6 +190,7 @@ export function inverseFieldType(type: FieldType): string {
|
|||||||
json: 'json',
|
json: 'json',
|
||||||
line: 'line',
|
line: 'line',
|
||||||
lseg: 'lseg',
|
lseg: 'lseg',
|
||||||
|
ltree: 'ltree',
|
||||||
macaddr: 'macaddr',
|
macaddr: 'macaddr',
|
||||||
money: 'money',
|
money: 'money',
|
||||||
numeric: 'numeric',
|
numeric: 'numeric',
|
||||||
|
|||||||
@@ -16,8 +16,11 @@ type ComparisonFunction<T> = (item: CollectionItem<T>, otherItem: CollectionItem
|
|||||||
import { WhereOperator, applyWhere, whereMatch } from './where'
|
import { WhereOperator, applyWhere, whereMatch } from './where'
|
||||||
|
|
||||||
const collect = <T>(items: CollectionItem<T>[]): Collection<T> => Collection.collect(items)
|
const collect = <T>(items: CollectionItem<T>[]): Collection<T> => Collection.collect(items)
|
||||||
|
const toString = (item: unknown): string => String(item)
|
||||||
|
|
||||||
export {
|
export {
|
||||||
collect,
|
collect,
|
||||||
|
toString,
|
||||||
Collection,
|
Collection,
|
||||||
|
|
||||||
// Types
|
// Types
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import {Collection} from './Collection'
|
import {Collection} from './Collection'
|
||||||
|
import {InjectionAware} from '../../di'
|
||||||
|
|
||||||
export type MaybeIterationItem<T> = { done: boolean, value?: T }
|
export type MaybeIterationItem<T> = { done: boolean, value?: T }
|
||||||
export type ChunkCallback<T> = (items: Collection<T>) => any
|
export type ChunkCallback<T> = (items: Collection<T>) => any
|
||||||
@@ -9,7 +10,7 @@ export class StopIteration extends Error {}
|
|||||||
* Abstract class representing an iterable, lazy-loaded dataset.
|
* Abstract class representing an iterable, lazy-loaded dataset.
|
||||||
* @abstract
|
* @abstract
|
||||||
*/
|
*/
|
||||||
export abstract class Iterable<T> {
|
export abstract class Iterable<T> extends InjectionAware {
|
||||||
/**
|
/**
|
||||||
* The current index of the iterable.
|
* The current index of the iterable.
|
||||||
* @type number
|
* @type number
|
||||||
|
|||||||
@@ -9,3 +9,12 @@ export type ParameterizedCallback<T> = ((arg: T) => any)
|
|||||||
|
|
||||||
/** A key-value form of a given type. */
|
/** A key-value form of a given type. */
|
||||||
export type KeyValue<T> = {key: string, value: T}
|
export type KeyValue<T> = {key: string, value: T}
|
||||||
|
|
||||||
|
/** Simple helper method to verify that a key is a keyof some object. */
|
||||||
|
export function isKeyof<T>(key: unknown, obj: T): key is keyof T {
|
||||||
|
if ( typeof key !== 'string' && typeof key !== 'symbol' ) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return key in obj
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user