From d40c0febb53dfee4220ac08966ec706331394791 Mon Sep 17 00:00:00 2001 From: Hage Yaapa Date: Wed, 26 Feb 2020 15:58:50 +0530 Subject: [PATCH] feat: apply feedback Applied feedback. Signed-off-by: Hage Yaapa --- types/observer-mixin.d.ts | 11 ++++++- types/persisted-model.d.ts | 61 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/types/observer-mixin.d.ts b/types/observer-mixin.d.ts index 6a020e6cd..3af58adae 100644 --- a/types/observer-mixin.d.ts +++ b/types/observer-mixin.d.ts @@ -5,7 +5,16 @@ import {Callback, PromiseOrVoid} from './common'; -export interface OperationHookContext { +export interface OperationHookContext { + /** + * The constructor of the model that triggered the operation. + */ + Model: T; + + /** + * Additional context properties, not typed yet. + * See https://loopback.io/doc/en/lb3/Operation-hooks.html#hooks + */ [property: string]: any; } diff --git a/types/persisted-model.d.ts b/types/persisted-model.d.ts index dd4af1ad8..c268fbf1d 100644 --- a/types/persisted-model.d.ts +++ b/types/persisted-model.d.ts @@ -521,9 +521,66 @@ export declare class PersistedModel extends ModelBase { */ static getIdName(): string; - definePersistedModel(entityClass: T): PersistedModel; - + /** + * Register an asynchronous observer for the given operation (event). + * + * Example: + * + * Registers a `before save` observer for a given model. + * + * ```js + * MyModel.observe('before save', function filterProperties(ctx, next) { + if (ctx.options && ctx.options.skipPropertyFilter) return next(); + if (ctx.instance) { + FILTERED_PROPERTIES.forEach(function(p) { + ctx.instance.unsetAttribute(p); + }); + } else { + FILTERED_PROPERTIES.forEach(function(p) { + delete ctx.data[p]; + }); + } + next(); + }); + * ``` + * + * @param {String} operation The operation name. + * @callback {function} listener The listener function. It will be invoked with + * `this` set to the model constructor, e.g. `User`. + */ static observe(operation: string, handler: Listener): void; + + /** + * Unregister an asynchronous observer for the given operation (event). + * + * Example: + * + * ```js + * MyModel.removeObserver('before save', function removedObserver(ctx, next) { + // some logic user want to apply to the removed observer... + next(); + }); + * ``` + * + * @param {String} operation The operation name. + * @callback {function} listener The listener function. + */ + static removeObserver(operation: string, handler: Listener): void; + + /** + * Unregister all asynchronous observers for the given operation (event). + * + * Example: + * + * Remove all observers connected to the `before save` operation. + * + * ```js + * MyModel.clearObservers('before save'); + * ``` + * + * @param {String} operation The operation name. + */ + static clearObservers(operation: string): void; } export type PersistedModelClass = typeof PersistedModel;