You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.2 KiB
48 lines
1.2 KiB
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, T2 extends Model> 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
|
|
}
|
|
}
|