From 4b9b62517b6802811d58068708039700e8b7c03e Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Wed, 2 Sep 2020 14:08:35 +0200 Subject: [PATCH] ModelRelation: add count(), has() methods --- src/db/ModelRelation.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/db/ModelRelation.ts b/src/db/ModelRelation.ts index 027f178..baa9a0e 100644 --- a/src/db/ModelRelation.ts +++ b/src/db/ModelRelation.ts @@ -53,6 +53,18 @@ export default abstract class ModelRelation[]): Promise>; public abstract async populate(models: ModelQueryResult): Promise; + + public async count(): Promise { + const models = await this.get(); + if (Array.isArray(models)) return models.length; + else return models !== null ? 1 : 0; + } + + public async has(model: O): Promise { + const models = await this.get(); + if (Array.isArray(models)) return models.find(m => m.equals(model)) !== undefined; + else return models && models.equals(model); + } } export class OneModelRelation extends ModelRelation { @@ -154,7 +166,6 @@ export class ManyModelRelation extends ModelRe public async populate(models: ModelQueryResult): Promise { this.cachedModels = models.filter(m => m[this.dbProperties.foreignKey] === this.getModelID()); } - } export class ManyThroughModelRelation extends ModelRelation { @@ -212,10 +223,8 @@ export class ManyThroughModelRelation extends .map(p => p[`pivot.${this.dbProperties.foreignPivotKey}`]); this.cachedModels = models.filter(m => ids.indexOf(m[this.dbProperties.foreignKey]) >= 0); } - } - export type QueryModifier = (query: ModelQuery) => ModelQuery; export type ModelFilter = (model: O) => boolean | Promise;