import {Model} from '../Model' import {HasOneOrMany} from './HasOneOrMany' import {RelationNotLoadedError} from './Relation' import {Maybe} from '../../../util' /** * One-to-one relation implementation. */ export class HasOne, T2 extends Model> extends HasOneOrMany> { 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> { 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 { if ( !this.cachedLoaded ) { throw new RelationNotLoadedError() } return this.cachedValue } /** Returns true if the relation has been loaded. */ public isLoaded(): boolean { return this.cachedLoaded } }