Add has and require methods to Extendable

This commit is contained in:
Alice Gaudon 2021-05-13 15:58:41 +02:00
parent c896accdfa
commit cdf95c0c0b
3 changed files with 35 additions and 2 deletions

View File

@ -13,7 +13,7 @@ import Controller from "./Controller.js";
import Migration, {MigrationType} from "./db/Migration.js";
import MysqlConnectionManager from "./db/MysqlConnectionManager.js";
import {ValidationBag, ValidationError} from "./db/Validator.js";
import Extendable from "./Extendable.js";
import Extendable, {MissingComponentError} from "./Extendable.js";
import {BadRequestError, HttpError, NotFoundHttpError, ServerError, ServiceUnavailableHttpError} from "./HttpError.js";
import {logger, loggingContextMiddleware} from "./Logger.js";
import SecurityError from "./SecurityError.js";
@ -384,6 +384,16 @@ export default abstract class Application implements Extendable<ApplicationCompo
return module ? module as C : null;
}
public has<C extends ApplicationComponent | WebSocketListener<Application>>(type: Type<C>): boolean {
return !!this.asOptional(type);
}
public require<C extends ApplicationComponent | WebSocketListener<Application>>(type: Type<C>): void {
if (!this.has(type)) {
throw new MissingComponentError(type);
}
}
public async isInNodeModules(): Promise<boolean> {
return await doesFileExist('node_modules/swaf');
}

View File

@ -4,4 +4,17 @@ export default interface Extendable<ComponentClass> {
as<C extends ComponentClass>(type: Type<C>): C;
asOptional<C extends ComponentClass>(type: Type<C>): C | null;
has<C extends ComponentClass>(type: Type<C>): boolean;
/**
* @throws MissingComponentError
*/
require<C extends ComponentClass>(type: Type<C>): void;
}
export class MissingComponentError<ComponentClass> extends Error {
public constructor(type: Type<ComponentClass>) {
super(`Required component ${type.name} was not found.`);
}
}

View File

@ -1,7 +1,7 @@
import {Request} from "express";
import {Connection} from "mysql";
import Extendable from "../Extendable.js";
import Extendable, {MissingComponentError} from "../Extendable.js";
import {Type} from "../Utils.js";
import ModelComponent from "./ModelComponent.js";
import ModelFactory, {PrimaryKeyValue} from "./ModelFactory.js";
@ -99,6 +99,16 @@ export default abstract class Model implements Extendable<ModelComponent<Model>>
return null;
}
public has<C extends ModelComponent<Model>>(type: Type<C>): boolean {
return !!this.asOptional(type);
}
public require<C extends ModelComponent<Model>>(type: Type<C>): void {
if (!this.has(type)) {
throw new MissingComponentError(type);
}
}
public updateWithData(data: Pick<this, keyof this> | Record<string, unknown>): void {
for (const property of this._properties) {
if (data[property] !== undefined) {