From 2bbe4db5fe3e9966aee977cde9ac24b49eb06066 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Mon, 27 Jul 2020 10:56:10 +0200 Subject: [PATCH] ModelRelation: add post-query filters --- src/db/ModelRelation.ts | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/db/ModelRelation.ts b/src/db/ModelRelation.ts index 994cd78..bc6a39e 100644 --- a/src/db/ModelRelation.ts +++ b/src/db/ModelRelation.ts @@ -6,6 +6,7 @@ export default abstract class ModelRelation; protected readonly query: ModelQuery; + protected readonly filters: ModelFilter[] = []; protected cachedModels?: R; protected constructor(model: S, foreignFactory: ModelFactory) { @@ -21,6 +22,11 @@ export default abstract class ModelRelation): this { + this.filters.push(modelFilter); + return this; + } + public abstract getModelID(): any; protected abstract async compute(query: ModelQuery): Promise; @@ -63,6 +69,18 @@ export class OneModelRelation extends ModelRel return await query.first(); } + public async get(): Promise { + const model = await super.get(); + if (model) { + for (const filter of this.filters) { + if (!(await filter(model))) { + return null; + } + } + } + return model; + } + public async eagerLoad(relations: ModelRelation[]): Promise> { this.query.where( this.dbProperties.foreignKey, @@ -103,6 +121,20 @@ export class ManyModelRelation extends ModelRe return await query.get(); } + public async get(): Promise { + let models = await super.get(); + for (const filter of this.filters) { + const newModels = []; + for (const model of models) { + if (await filter(model)) { + newModels.push(model); + } + } + models = newModels; + } + return models; + } + public async eagerLoad(relations: ModelRelation[]): Promise> { this.query.where( this.dbProperties.foreignKey, @@ -142,6 +174,20 @@ export class ManyThroughModelRelation extends return await query.get(); } + public async get(): Promise { + let models = await super.get(); + for (const filter of this.filters) { + const newModels = []; + for (const model of models) { + if (await filter(model)) { + newModels.push(model); + } + } + models = newModels; + } + return models; + } + public async eagerLoad(relations: ModelRelation[]): Promise> { this.query.where( `pivot.${this.dbProperties.localPivotKey}`, @@ -163,6 +209,8 @@ export class ManyThroughModelRelation extends export type QueryModifier = (query: ModelQuery) => ModelQuery; +export type ModelFilter = (model: O) => boolean | Promise; + export type RelationDatabaseProperties = { localKey: string; foreignKey: string;