Skip to content

Commit

Permalink
feat: implement CommonDao afterLoad, beforeSave hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillgroshkov committed Mar 29, 2023
1 parent fb3514d commit aa0a196
Show file tree
Hide file tree
Showing 3 changed files with 271 additions and 131 deletions.
32 changes: 31 additions & 1 deletion src/commondao/common.dao.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
CommonLogger,
ErrorMode,
ObjectWithId,
Promisable,
Saved,
ZodError,
ZodSchema,
Expand Down Expand Up @@ -54,7 +55,7 @@ export interface CommonDaoHooks<

/**
* Called when loading things "as DBM" and validation is not skipped.
* When loading things like BM/TM - other hooks get involved instead:
* When loading things as BM/TM - other hooks get involved instead:
* - beforeDBMToBM
* - beforeBMToTM
*
Expand All @@ -67,6 +68,35 @@ export interface CommonDaoHooks<
beforeBMToDBM: (bm: BM) => Partial<DBM> | Promise<Partial<DBM>>
beforeBMToTM: (bm: BM) => Partial<TM>

/**
* Allows to access the DBM just after it has been loaded from the DB.
*
* Normally does nothing.
*
* You can change the DBM as you want here: ok to mutate or not, but you need to return the DBM
* to pass it further.
*
* You can return `null` to make it look "not found".
*
* You can do validations as needed here and throw errors, they will be propagated.
*/
afterLoad?: (dbm: DBM) => Promisable<DBM | null>

/**
* Allows to access the DBM just before it's supposed to be saved to the DB.
*
* Normally does nothing.
*
* You can change the DBM as you want here: ok to mutate or not, but you need to return the DBM
* to pass it further.
*
* You can return `null` to prevent it from being saved, without throwing an error.
* `.save` method will then return the BM/DBM as it has entered the method (it **won't** return the null value!).
*
* You can do validations as needed here and throw errors, they will be propagated.
*/
beforeSave?: (dbm: DBM) => Promisable<DBM | null>

/**
* Called in:
* - dbmToBM (applied before DBM becomes BM)
Expand Down
Loading

0 comments on commit aa0a196

Please sign in to comment.