Skip to content

Commit

Permalink
fix: types
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillgroshkov committed Jan 19, 2024
1 parent 16742f2 commit 7a2c15c
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 13 deletions.
3 changes: 2 additions & 1 deletion src/commondao/common.dao.model.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
AnyObject,
CommonLogger,
ErrorMode,
PartialObjectWithId,
Expand Down Expand Up @@ -138,7 +139,7 @@ export enum CommonDaoLogLevel {
export interface CommonDaoCfg<
BM extends PartialObjectWithId,
DBM extends PartialObjectWithId = BM,
TM = BM,
TM extends AnyObject = BM,
> {
db: CommonDB
table: string
Expand Down
19 changes: 7 additions & 12 deletions src/commondao/common.dao.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
AnyObject,
AppError,
AsyncMapper,
BaseDBEntity,
CommonLogger,
ErrorMode,
JsonSchemaObject,
Expand Down Expand Up @@ -116,7 +117,7 @@ export class CommonDao<
create(part: Partial<BM> = {}, opt: CommonDaoOptions = {}): Saved<BM> {
const bm = this.cfg.hooks!.beforeCreate!(part)
// First assignIdCreatedUpdated, then validate!
this.assignIdCreatedUpdated(bm as BM, opt)
this.assignIdCreatedUpdated(bm, opt)
return this.validateAndConvert(bm, this.cfg.bmSchema, DBModelType.BM, opt)
}

Expand Down Expand Up @@ -674,28 +675,22 @@ export class CommonDao<
* Mutates!
* "Returns", just to have a type of "Saved"
*/
assignIdCreatedUpdated(obj: Partial<DBM>, opt?: CommonDaoOptions): Saved<Partial<DBM>>
assignIdCreatedUpdated(obj: Partial<BM>, opt?: CommonDaoOptions): Saved<Partial<BM>>
assignIdCreatedUpdated(
obj: Partial<DBM> | Partial<BM>,
opt: CommonDaoOptions = {},
): Saved<Partial<DBM>> | Saved<Partial<BM>> {
assignIdCreatedUpdated<T extends BaseDBEntity>(obj: T, opt: CommonDaoOptions = {}): Saved<T> {
const now = Math.floor(Date.now() / 1000)

if (this.cfg.useCreatedProperty) {
;(obj as any)['created'] ||= (obj as any)['updated'] || now
obj.created ||= obj.updated || now
}

if (this.cfg.useUpdatedProperty) {
;(obj as any)['updated'] =
opt.preserveUpdatedCreated && (obj as any)['updated'] ? (obj as any)['updated'] : now
obj.updated = opt.preserveUpdatedCreated && obj.updated ? obj.updated : now
}

if (this.cfg.createId) {
obj.id ||= this.cfg.hooks!.createNaturalId?.(obj as BM) || this.cfg.hooks!.createRandomId!()
obj.id ||= this.cfg.hooks!.createNaturalId?.(obj as any) || this.cfg.hooks!.createRandomId!()
}

return obj as any
return obj as Saved<T>
}

// SAVE
Expand Down

0 comments on commit 7a2c15c

Please sign in to comment.