Skip to content

Commit

Permalink
feat: CommonDao tx ops now can be undefined
Browse files Browse the repository at this point in the history
To allow things like:

tx.deleteById(undefined)
tx.saveBatch([])

which become no-op.
  • Loading branch information
kirillgroshkov committed Mar 22, 2023
1 parent dc4cf23 commit 0bf28e0
Show file tree
Hide file tree
Showing 2 changed files with 219 additions and 184 deletions.
24 changes: 17 additions & 7 deletions src/commondao/common.dao.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
_assert,
_filterNullishValues,
_filterUndefinedValues,
_isTruthy,
_passthroughPredicate,
_since,
_truncate,
Expand All @@ -14,6 +15,7 @@ import {
JsonSchemaRootObject,
ObjectWithId,
pMap,
Promisable,
Saved,
Unsaved,
ZodSchema,
Expand Down Expand Up @@ -633,7 +635,8 @@ export class CommonDao<
saveBatch: async (
bms: Unsaved<BM>[],
opt: CommonDaoSaveOptions<DBM> = {},
): Promise<DBSaveBatchOperation> => {
): Promise<DBSaveBatchOperation | undefined> => {
if (!bms.length) return
const rows: DBM[] = (await this.saveBatch(bms, { ...opt, tx: true })) as any

return {
Expand All @@ -646,15 +649,23 @@ export class CommonDao<
},
}
},
deleteByIds: async (ids: ID[], opt: CommonDaoOptions = {}): Promise<DBDeleteByIdsOperation> => {
deleteByIds: async (
ids: ID[],
opt: CommonDaoOptions = {},
): Promise<DBDeleteByIdsOperation | undefined> => {
if (!ids.length) return
return {
type: 'deleteByIds',
table: this.cfg.table,
ids: ids as string[],
opt,
}
},
deleteById: async (id: ID, opt: CommonDaoOptions = {}): Promise<DBDeleteByIdsOperation> => {
deleteById: async (
id: ID | null | undefined,
opt: CommonDaoOptions = {},
): Promise<DBDeleteByIdsOperation | undefined> => {
if (!id) return
return {
type: 'deleteByIds',
table: this.cfg.table,
Expand Down Expand Up @@ -1164,10 +1175,9 @@ export class CommonDao<
await this.cfg.db.ping()
}

async runInTransaction(ops: Promise<DBOperation>[]): Promise<void> {
if (!ops.length) return

const resolvedOps = await Promise.all(ops)
async runInTransaction(ops: Promisable<DBOperation | undefined>[]): Promise<void> {
const resolvedOps = (await Promise.all(ops)).filter(_isTruthy)
if (!resolvedOps.length) return

await this.cfg.db.commitTransaction(DBTransaction.create(resolvedOps))
}
Expand Down
Loading

0 comments on commit 0bf28e0

Please sign in to comment.