diff --git a/src/commondao/common.dao.model.ts b/src/commondao/common.dao.model.ts index 6aa7bde..2dae726 100644 --- a/src/commondao/common.dao.model.ts +++ b/src/commondao/common.dao.model.ts @@ -4,7 +4,6 @@ import { CommonLogger, ErrorMode, Promisable, - Saved, ZodError, ZodSchema, } from '@naturalcycles/js-lib' @@ -76,7 +75,7 @@ export interface CommonDaoHooks) => Promisable | null> + afterLoad?: (dbm: DBM) => Promisable /** * Allows to access the DBM just before it's supposed to be saved to the DB. @@ -91,7 +90,7 @@ export interface CommonDaoHooks) => Promisable | null> + beforeSave?: (dbm: DBM) => Promisable /** * Called in: diff --git a/src/commondao/common.dao.test.ts b/src/commondao/common.dao.test.ts index c368622..89471bd 100644 --- a/src/commondao/common.dao.test.ts +++ b/src/commondao/common.dao.test.ts @@ -1,5 +1,13 @@ import { mockTime, MOCK_TS_2018_06_21 } from '@naturalcycles/dev-lib/dist/testing' -import { ErrorMode, _omit, _range, _sortBy, pTry, pExpectedError } from '@naturalcycles/js-lib' +import { + ErrorMode, + _omit, + _range, + _sortBy, + pTry, + pExpectedError, + BaseDBEntity, +} from '@naturalcycles/js-lib' import { AjvSchema, AjvValidationError, @@ -400,7 +408,7 @@ test('ajvSchema', async () => { console.log((err as any).data) }) -interface Item { +interface Item extends BaseDBEntity { id: string obj: any } diff --git a/src/commondao/common.dao.ts b/src/commondao/common.dao.ts index 4be9a68..c460ae2 100644 --- a/src/commondao/common.dao.ts +++ b/src/commondao/common.dao.ts @@ -21,10 +21,9 @@ import { JsonSchemaRootObject, ObjectWithId, pMap, - Saved, SKIP, UnixTimestampMillisNumber, - UnsavedId, + Unsaved, ZodSchema, ZodValidationError, zSafeValidate, @@ -115,7 +114,7 @@ export class CommonDao< } // CREATE - create(part: Partial = {}, opt: CommonDaoOptions = {}): Saved { + create(part: Partial = {}, opt: CommonDaoOptions = {}): BM { const bm = this.cfg.hooks!.beforeCreate!(part) // First assignIdCreatedUpdated, then validate! this.assignIdCreatedUpdated(bm, opt) @@ -124,14 +123,14 @@ export class CommonDao< // GET async getById(id: undefined | null, opt?: CommonDaoOptions): Promise - async getById(id?: string | null, opt?: CommonDaoOptions): Promise | null> - async getById(id?: string | null, opt: CommonDaoOptions = {}): Promise | null> { + async getById(id?: string | null, opt?: CommonDaoOptions): Promise + async getById(id?: string | null, opt: CommonDaoOptions = {}): Promise { if (!id) return null const op = `getById(${id})` const table = opt.table || this.cfg.table const started = this.logStarted(op, table) - let dbm = (await (opt.tx || this.cfg.db).getByIds>(table, [id]))[0] + let dbm = (await (opt.tx || this.cfg.db).getByIds(table, [id]))[0] if (dbm && !opt.raw && this.cfg.hooks!.afterLoad) { dbm = (await this.cfg.hooks!.afterLoad(dbm)) || undefined } @@ -141,11 +140,7 @@ export class CommonDao< return bm || null } - async getByIdOrEmpty( - id: string, - part: Partial = {}, - opt?: CommonDaoOptions, - ): Promise> { + async getByIdOrEmpty(id: string, part: Partial = {}, opt?: CommonDaoOptions): Promise { const bm = await this.getById(id, opt) if (bm) return bm @@ -156,7 +151,7 @@ export class CommonDao< id: string, part: Partial = {}, opt?: CommonDaoOptions, - ): Promise> { + ): Promise { const dbm = await this.getByIdAsDBM(id, opt) if (dbm) return dbm @@ -165,13 +160,13 @@ export class CommonDao< } async getByIdAsDBM(id: undefined | null, opt?: CommonDaoOptions): Promise - async getByIdAsDBM(id?: string | null, opt?: CommonDaoOptions): Promise | null> - async getByIdAsDBM(id?: string | null, opt: CommonDaoOptions = {}): Promise | null> { + async getByIdAsDBM(id?: string | null, opt?: CommonDaoOptions): Promise + async getByIdAsDBM(id?: string | null, opt: CommonDaoOptions = {}): Promise { if (!id) return null const op = `getByIdAsDBM(${id})` const table = opt.table || this.cfg.table const started = this.logStarted(op, table) - let [dbm] = await (opt.tx || this.cfg.db).getByIds>(table, [id]) + let [dbm] = await (opt.tx || this.cfg.db).getByIds(table, [id]) if (dbm && !opt.raw && this.cfg.hooks!.afterLoad) { dbm = (await this.cfg.hooks!.afterLoad(dbm)) || undefined } @@ -190,7 +185,7 @@ export class CommonDao< const op = `getByIdAsTM(${id})` const table = opt.table || this.cfg.table const started = this.logStarted(op, table) - let [dbm] = await (opt.tx || this.cfg.db).getByIds>(table, [id]) + let [dbm] = await (opt.tx || this.cfg.db).getByIds(table, [id]) if (dbm && !opt.raw && this.cfg.hooks!.afterLoad) { dbm = (await this.cfg.hooks!.afterLoad(dbm)) || undefined } @@ -205,12 +200,12 @@ export class CommonDao< return tm || null } - async getByIds(ids: string[], opt: CommonDaoOptions = {}): Promise[]> { + async getByIds(ids: string[], opt: CommonDaoOptions = {}): Promise { if (!ids.length) return [] const op = `getByIds ${ids.length} id(s) (${_truncate(ids.slice(0, 10).join(', '), 50)})` const table = opt.table || this.cfg.table const started = this.logStarted(op, table) - let dbms = await (opt.tx || this.cfg.db).getByIds>(table, ids) + let dbms = await (opt.tx || this.cfg.db).getByIds(table, ids) if (!opt.raw && this.cfg.hooks!.afterLoad && dbms.length) { dbms = (await pMap(dbms, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter( _isTruthy, @@ -222,12 +217,12 @@ export class CommonDao< return bms } - async getByIdsAsDBM(ids: string[], opt: CommonDaoOptions = {}): Promise[]> { + async getByIdsAsDBM(ids: string[], opt: CommonDaoOptions = {}): Promise { if (!ids.length) return [] const op = `getByIdsAsDBM ${ids.length} id(s) (${_truncate(ids.slice(0, 10).join(', '), 50)})` const table = opt.table || this.cfg.table const started = this.logStarted(op, table) - let dbms = await (opt.tx || this.cfg.db).getByIds>(table, ids) + let dbms = await (opt.tx || this.cfg.db).getByIds(table, ids) if (!opt.raw && this.cfg.hooks!.afterLoad && dbms.length) { dbms = (await pMap(dbms, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter( _isTruthy, @@ -238,7 +233,7 @@ export class CommonDao< return dbms } - async requireById(id: string, opt: CommonDaoOptions = {}): Promise> { + async requireById(id: string, opt: CommonDaoOptions = {}): Promise { const r = await this.getById(id, opt) if (!r) { this.throwRequiredError(id, opt) @@ -246,7 +241,7 @@ export class CommonDao< return r } - async requireByIdAsDBM(id: string, opt: CommonDaoOptions = {}): Promise> { + async requireByIdAsDBM(id: string, opt: CommonDaoOptions = {}): Promise { const r = await this.getByIdAsDBM(id, opt) if (!r) { this.throwRequiredError(id, opt) @@ -295,16 +290,16 @@ export class CommonDao< } } - async getBy(by: keyof DBM, value: any, limit = 0, opt?: CommonDaoOptions): Promise[]> { + async getBy(by: keyof DBM, value: any, limit = 0, opt?: CommonDaoOptions): Promise { return await this.query().filterEq(by, value).limit(limit).runQuery(opt) } - async getOneBy(by: keyof DBM, value: any, opt?: CommonDaoOptions): Promise | null> { + async getOneBy(by: keyof DBM, value: any, opt?: CommonDaoOptions): Promise { const [bm] = await this.query().filterEq(by, value).limit(1).runQuery(opt) return bm || null } - async getAll(opt?: CommonDaoOptions): Promise[]> { + async getAll(opt?: CommonDaoOptions): Promise { return await this.query().runQuery(opt) } @@ -316,7 +311,7 @@ export class CommonDao< return new RunnableDBQuery(this, table) } - async runQuery(q: DBQuery, opt?: CommonDaoOptions): Promise[]> { + async runQuery(q: DBQuery, opt?: CommonDaoOptions): Promise { const { rows } = await this.runQueryExtended(q, opt) return rows } @@ -338,21 +333,18 @@ export class CommonDao< * Does deduplication by id. * Order is not guaranteed, as queries run in parallel. */ - async runUnionQueries(queries: DBQuery[], opt?: CommonDaoOptions): Promise[]> { + async runUnionQueries(queries: DBQuery[], opt?: CommonDaoOptions): Promise { const results = ( await pMap(queries, async q => (await this.runQueryExtended(q, opt)).rows) ).flat() return _uniqBy(results, r => r.id) } - async runQueryExtended( - q: DBQuery, - opt: CommonDaoOptions = {}, - ): Promise>> { + async runQueryExtended(q: DBQuery, opt: CommonDaoOptions = {}): Promise> { q.table = opt.table || q.table const op = `runQuery(${q.pretty()})` const started = this.logStarted(op, q.table) - let { rows, ...queryResult } = await this.cfg.db.runQuery>(q, opt) + let { rows, ...queryResult } = await this.cfg.db.runQuery(q, opt) const partialQuery = !!q._selectedFieldNames if (!opt.raw && this.cfg.hooks!.afterLoad && rows.length) { rows = (await pMap(rows, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter( @@ -368,7 +360,7 @@ export class CommonDao< } } - async runQueryAsDBM(q: DBQuery, opt?: CommonDaoOptions): Promise[]> { + async runQueryAsDBM(q: DBQuery, opt?: CommonDaoOptions): Promise { const { rows } = await this.runQueryExtendedAsDBM(q, opt) return rows } @@ -376,11 +368,11 @@ export class CommonDao< async runQueryExtendedAsDBM( q: DBQuery, opt: CommonDaoOptions = {}, - ): Promise>> { + ): Promise> { q.table = opt.table || q.table const op = `runQueryAsDBM(${q.pretty()})` const started = this.logStarted(op, q.table) - let { rows, ...queryResult } = await this.cfg.db.runQuery>(q, opt) + let { rows, ...queryResult } = await this.cfg.db.runQuery(q, opt) if (!opt.raw && this.cfg.hooks!.afterLoad && rows.length) { rows = (await pMap(rows, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter( _isTruthy, @@ -405,7 +397,7 @@ export class CommonDao< q.table = opt.table || q.table const op = `runQueryAsTM(${q.pretty()})` const started = this.logStarted(op, q.table) - let { rows, ...queryResult } = await this.cfg.db.runQuery>(q, opt) + let { rows, ...queryResult } = await this.cfg.db.runQuery(q, opt) if (!opt.raw && this.cfg.hooks!.afterLoad && rows.length) { rows = (await pMap(rows, async dbm => await this.cfg.hooks!.afterLoad!(dbm))).filter( _isTruthy, @@ -435,8 +427,8 @@ export class CommonDao< async streamQueryForEach( q: DBQuery, - mapper: AsyncMapper, void>, - opt: CommonDaoStreamForEachOptions> = {}, + mapper: AsyncMapper, + opt: CommonDaoStreamForEachOptions = {}, ): Promise { q.table = opt.table || q.table opt.skipValidation = opt.skipValidation !== false // default true @@ -450,7 +442,7 @@ export class CommonDao< await _pipeline([ this.cfg.db.streamQuery(q, opt), - transformMap, Saved>( + transformMap( async dbm => { count++ if (partialQuery || opt.raw) return dbm as any @@ -466,7 +458,7 @@ export class CommonDao< errorMode: opt.errorMode, }, ), - transformMap, void>(mapper, { + transformMap(mapper, { ...opt, predicate: _passthroughPredicate, // to be able to logProgress }), @@ -485,7 +477,7 @@ export class CommonDao< async streamQueryAsDBMForEach( q: DBQuery, - mapper: AsyncMapper, void>, + mapper: AsyncMapper, opt: CommonDaoStreamForEachOptions = {}, ): Promise { q.table = opt.table || q.table @@ -516,7 +508,7 @@ export class CommonDao< errorMode: opt.errorMode, }, ), - transformMap, void>(mapper, { + transformMap(mapper, { ...opt, predicate: _passthroughPredicate, // to be able to logProgress }), @@ -536,10 +528,7 @@ export class CommonDao< /** * Stream as Readable, to be able to .pipe() it further with support of backpressure. */ - streamQueryAsDBM( - q: DBQuery, - opt: CommonDaoStreamOptions = {}, - ): ReadableTyped> { + streamQueryAsDBM(q: DBQuery, opt: CommonDaoStreamOptions = {}): ReadableTyped { q.table = opt.table || q.table opt.skipValidation = opt.skipValidation !== false // default true opt.skipConversion = opt.skipConversion !== false // default true @@ -553,7 +542,7 @@ export class CommonDao< return stream .on('error', err => stream.emit('error', err)) .pipe( - transformMap>( + transformMap( async dbm => { if (this.cfg.hooks!.afterLoad) { dbm = (await this.cfg.hooks!.afterLoad(dbm))! @@ -578,10 +567,7 @@ export class CommonDao< * * You can do `.pipe(transformNoOp)` to make it "valid again". */ - streamQuery( - q: DBQuery, - opt: CommonDaoStreamOptions> = {}, - ): ReadableTyped> { + streamQuery(q: DBQuery, opt: CommonDaoStreamOptions = {}): ReadableTyped { q.table = opt.table || q.table opt.skipValidation = opt.skipValidation !== false // default true opt.skipConversion = opt.skipConversion !== false // default true @@ -595,10 +581,10 @@ export class CommonDao< stream // optimization: 1 validation is enough // .pipe(transformMap(dbm => this.anyToDBM(dbm, opt), safeOpt)) - // .pipe(transformMap>(dbm => this.dbmToBM(dbm, opt), safeOpt)) + // .pipe(transformMap(dbm => this.dbmToBM(dbm, opt), safeOpt)) .on('error', err => stream.emit('error', err)) .pipe( - transformMap, Saved>( + transformMap( async dbm => { if (this.cfg.hooks!.afterLoad) { dbm = (await this.cfg.hooks!.afterLoad(dbm))! @@ -632,7 +618,7 @@ export class CommonDao< .streamQuery(q.select(['id']), opt) .on('error', err => stream.emit('error', err)) .pipe( - transformMapSimple, string>(r => r.id, { + transformMapSimple(r => r.id, { errorMode: ErrorMode.SUPPRESS, // cause .pipe() cannot propagate errors }), ) @@ -654,7 +640,7 @@ export class CommonDao< await _pipeline([ this.cfg.db.streamQuery(q.select(['id']), opt), - transformMapSimple, string>(r => { + transformMapSimple(r => { count++ return r.id }), @@ -701,17 +687,17 @@ export class CommonDao< /** * Mutates with id, created, updated */ - async save(bm: UnsavedId, opt: CommonDaoSaveOptions = {}): Promise> { + async save(bm: Unsaved, opt: CommonDaoSaveOptions = {}): Promise { this.requireWriteAccess() if (opt.skipIfEquals && _deepJsonEquals(bm, opt.skipIfEquals)) { // Skipping the save operation - return bm as Saved + return bm as BM } const idWasGenerated = !bm.id && this.cfg.generateId this.assignIdCreatedUpdated(bm, opt) // mutates - _typeCast>(bm) + _typeCast(bm) let dbm = await this.bmToDBM(bm, opt) if (this.cfg.hooks!.beforeSave) { @@ -751,11 +737,7 @@ export class CommonDao< * Similar to `save` with skipIfEquals. * Similar to `patch`, but doesn't load the object from the Database. */ - async savePatch( - bm: BM, - patch: Partial, - opt: CommonDaoSaveBatchOptions, - ): Promise> { + async savePatch(bm: BM, patch: Partial, opt: CommonDaoSaveBatchOptions): Promise { const patched: BM = { ...bm, ...patch, @@ -763,7 +745,7 @@ export class CommonDao< if (_deepJsonEquals(bm, patched)) { // Skipping the save operation, as data is the same - return bm as Saved + return bm } // Actually apply the patch by mutating the original object (by design) @@ -785,7 +767,7 @@ export class CommonDao< id: string, patch: Partial, opt: CommonDaoSaveBatchOptions = {}, - ): Promise> { + ): Promise { if (this.cfg.patchInTransaction && !opt.tx) { // patchInTransaction means that we should run this op in Transaction // But if opt.tx is passed - means that we are already in a Transaction, @@ -793,7 +775,7 @@ export class CommonDao< return await this.patchByIdInTransaction(id, patch, opt) } - let patched: Saved + let patched: BM const loaded = await this.getById(id, opt) if (loaded) { @@ -817,7 +799,7 @@ export class CommonDao< id: string, patch: Partial, opt?: CommonDaoSaveBatchOptions, - ): Promise> { + ): Promise { return await this.runInTransaction(async daoTx => { return await this.patchById(id, patch, { ...opt, tx: daoTx.tx }) }) @@ -829,11 +811,7 @@ export class CommonDao< * Otherwise, similar behavior as patchById. * It still loads the row from the DB. */ - async patch( - bm: BM, - patch: Partial, - opt: CommonDaoSaveBatchOptions = {}, - ): Promise> { + async patch(bm: BM, patch: Partial, opt: CommonDaoSaveBatchOptions = {}): Promise { if (this.cfg.patchInTransaction && !opt.tx) { // patchInTransaction means that we should run this op in Transaction // But if opt.tx is passed - means that we are already in a Transaction, @@ -848,7 +826,7 @@ export class CommonDao< if (_deepJsonEquals(loaded, bm)) { // Skipping the save operation, as data is the same - return bm as Saved + return bm } // Make `bm` exactly the same as `loaded` @@ -867,22 +845,19 @@ export class CommonDao< bm: BM, patch: Partial, opt?: CommonDaoSaveBatchOptions, - ): Promise> { + ): Promise { return await this.runInTransaction(async daoTx => { return await this.patch(bm, patch, { ...opt, tx: daoTx.tx }) }) } - async saveAsDBM( - dbm: UnsavedId, - opt: CommonDaoSaveBatchOptions = {}, - ): Promise> { + async saveAsDBM(dbm: Unsaved, opt: CommonDaoSaveBatchOptions = {}): Promise { this.requireWriteAccess() const table = opt.table || this.cfg.table // assigning id in case it misses the id // will override/set `updated` field, unless opts.preserveUpdated is set - let row = dbm as Saved + let row = dbm as DBM if (!opt.raw) { const idWasGenerated = !dbm.id && this.cfg.generateId this.assignIdCreatedUpdated(dbm, opt) // mutates @@ -899,7 +874,7 @@ export class CommonDao< if (this.cfg.hooks!.beforeSave) { row = (await this.cfg.hooks!.beforeSave(row))! - if (row === null) return dbm as Saved + if (row === null) return dbm as DBM } await (opt.tx || this.cfg.db).saveBatch(table, [row], { @@ -916,10 +891,7 @@ export class CommonDao< return row } - async saveBatch( - bms: UnsavedId[], - opt: CommonDaoSaveBatchOptions = {}, - ): Promise[]> { + async saveBatch(bms: Unsaved[], opt: CommonDaoSaveBatchOptions = {}): Promise { if (!bms.length) return [] this.requireWriteAccess() const table = opt.table || this.cfg.table @@ -960,20 +932,20 @@ export class CommonDao< this.logSaveResult(started, op, table) - return bms as Saved[] + return bms as BM[] } async saveBatchAsDBM( - dbms: UnsavedId[], + dbms: Unsaved[], opt: CommonDaoSaveBatchOptions = {}, - ): Promise[]> { + ): Promise { if (!dbms.length) return [] this.requireWriteAccess() const table = opt.table || this.cfg.table - let rows = dbms as Saved[] + let rows = dbms as DBM[] if (!opt.raw) { dbms.forEach(dbm => this.assignIdCreatedUpdated(dbm, opt)) // mutates - rows = this.anyToDBMs(dbms as Saved[], opt) + rows = this.anyToDBMs(dbms as DBM[], opt) if (opt.ensureUniqueId) throw new AppError('ensureUniqueId is not supported in saveBatch') } if (this.cfg.immutable && !opt.allowMutability && !opt.saveMethod) { @@ -1034,7 +1006,7 @@ export class CommonDao< const { batchSize = 500, batchConcurrency = 16, errorMode } = opt return [ - transformMap>( + transformMap( async bm => { this.assignIdCreatedUpdated(bm, opt) // mutates @@ -1191,8 +1163,8 @@ export class CommonDao< // CONVERSIONS async dbmToBM(_dbm: undefined, opt?: CommonDaoOptions): Promise - async dbmToBM(_dbm?: DBM, opt?: CommonDaoOptions): Promise> - async dbmToBM(_dbm?: DBM, opt: CommonDaoOptions = {}): Promise | undefined> { + async dbmToBM(_dbm?: DBM, opt?: CommonDaoOptions): Promise + async dbmToBM(_dbm?: DBM, opt: CommonDaoOptions = {}): Promise { if (!_dbm) return // optimization: no need to run full joi DBM validation, cause BM validation will be run @@ -1211,7 +1183,7 @@ export class CommonDao< return this.validateAndConvert(bm, this.cfg.bmSchema, DBModelType.BM, opt) } - async dbmsToBM(dbms: DBM[], opt: CommonDaoOptions = {}): Promise[]> { + async dbmsToBM(dbms: DBM[], opt: CommonDaoOptions = {}): Promise { return await pMap(dbms, async dbm => await this.dbmToBM(dbm, opt)) } @@ -1220,8 +1192,8 @@ export class CommonDao< * Returns DBM (new reference). */ async bmToDBM(bm: undefined, opt?: CommonDaoOptions): Promise - async bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise> - async bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise | undefined> { + async bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise + async bmToDBM(bm?: BM, opt?: CommonDaoOptions): Promise { if (bm === undefined) return // optimization: no need to run the BM validation, since DBM will be validated anyway @@ -1240,14 +1212,14 @@ export class CommonDao< return this.validateAndConvert(dbm, this.cfg.dbmSchema, DBModelType.DBM, opt) } - async bmsToDBM(bms: BM[], opt: CommonDaoOptions = {}): Promise[]> { + async bmsToDBM(bms: BM[], opt: CommonDaoOptions = {}): Promise { // try/catch? return await pMap(bms, async bm => await this.bmToDBM(bm, opt)) } anyToDBM(dbm: undefined, opt?: CommonDaoOptions): undefined - anyToDBM(dbm?: any, opt?: CommonDaoOptions): Saved - anyToDBM(dbm?: DBM, opt: CommonDaoOptions = {}): Saved | undefined { + anyToDBM(dbm?: any, opt?: CommonDaoOptions): DBM + anyToDBM(dbm?: DBM, opt: CommonDaoOptions = {}): DBM | undefined { if (!dbm) return // this shouldn't be happening on load! but should on save! @@ -1263,7 +1235,7 @@ export class CommonDao< return this.validateAndConvert(dbm, this.cfg.dbmSchema, DBModelType.DBM, opt) } - anyToDBMs(entities: DBM[], opt: CommonDaoOptions = {}): Saved[] { + anyToDBMs(entities: DBM[], opt: CommonDaoOptions = {}): DBM[] { return entities.map(entity => this.anyToDBM(entity, opt)) } @@ -1491,7 +1463,7 @@ export class CommonDaoTransaction { dao: CommonDao, id?: string | null, opt?: CommonDaoOptions, - ): Promise | null> { + ): Promise { return await dao.getById(id, { ...opt, tx: this.tx }) } @@ -1499,7 +1471,7 @@ export class CommonDaoTransaction { dao: CommonDao, ids: string[], opt?: CommonDaoOptions, - ): Promise[]> { + ): Promise { return await dao.getByIds(ids, { ...opt, tx: this.tx }) } @@ -1508,7 +1480,7 @@ export class CommonDaoTransaction { // dao: CommonDao, // q: DBQuery, // opt?: CommonDaoOptions, - // ): Promise[]> { + // ): Promise { // try { // return await dao.runQuery(q, { ...opt, tx: this.tx }) // } catch (err) { @@ -1519,17 +1491,17 @@ export class CommonDaoTransaction { async save( dao: CommonDao, - bm: UnsavedId, + bm: Unsaved, opt?: CommonDaoSaveBatchOptions, - ): Promise> { + ): Promise { return (await this.saveBatch(dao, [bm], opt))[0]! } async saveBatch( dao: CommonDao, - bms: UnsavedId[], + bms: Unsaved[], opt?: CommonDaoSaveBatchOptions, - ): Promise[]> { + ): Promise { return await dao.saveBatch(bms, { ...opt, tx: this.tx }) } diff --git a/src/pipeline/dbPipelineRestore.ts b/src/pipeline/dbPipelineRestore.ts index f31aaff..7026361 100644 --- a/src/pipeline/dbPipelineRestore.ts +++ b/src/pipeline/dbPipelineRestore.ts @@ -10,7 +10,6 @@ import { localTime, JsonSchemaObject, BaseDBEntity, - Saved, } from '@naturalcycles/js-lib' import { NDJsonStats, @@ -217,7 +216,7 @@ export async function dbPipelineRestore(opt: DBPipelineRestoreOptions): Promise< }), transformLimit({ limit }), ...(sinceUpdated - ? [transformFilterSync>(r => r.updated >= sinceUpdated)] + ? [transformFilterSync(r => r.updated >= sinceUpdated)] : []), transformMap(mapperPerTable[table] || _passthroughMapper, { errorMode, diff --git a/src/query/dbQuery.ts b/src/query/dbQuery.ts index d7f878b..d9ddbde 100644 --- a/src/query/dbQuery.ts +++ b/src/query/dbQuery.ts @@ -1,7 +1,6 @@ import { AsyncMapper, _truncate, - Saved, AnyObject, _objectAssign, BaseDBEntity, @@ -251,7 +250,7 @@ export class RunnableDBQuery< super(table || dao.cfg.table) } - async runQuery(opt?: CommonDaoOptions): Promise[]> { + async runQuery(opt?: CommonDaoOptions): Promise { return await this.dao.runQuery(this, opt) } @@ -259,7 +258,7 @@ export class RunnableDBQuery< return await this.dao.runQuerySingleColumn(this, opt) } - async runQueryAsDBM(opt?: CommonDaoOptions): Promise[]> { + async runQueryAsDBM(opt?: CommonDaoOptions): Promise { return await this.dao.runQueryAsDBM(this, opt) } @@ -267,11 +266,11 @@ export class RunnableDBQuery< return await this.dao.runQueryAsTM(this, opt) } - async runQueryExtended(opt?: CommonDaoOptions): Promise>> { + async runQueryExtended(opt?: CommonDaoOptions): Promise> { return await this.dao.runQueryExtended(this, opt) } - async runQueryExtendedAsDBM(opt?: CommonDaoOptions): Promise>> { + async runQueryExtendedAsDBM(opt?: CommonDaoOptions): Promise> { return await this.dao.runQueryExtendedAsDBM(this, opt) } @@ -288,24 +287,24 @@ export class RunnableDBQuery< } async streamQueryForEach( - mapper: AsyncMapper, void>, - opt?: CommonDaoStreamForEachOptions>, + mapper: AsyncMapper, + opt?: CommonDaoStreamForEachOptions, ): Promise { await this.dao.streamQueryForEach(this, mapper, opt) } async streamQueryAsDBMForEach( - mapper: AsyncMapper, void>, + mapper: AsyncMapper, opt?: CommonDaoStreamForEachOptions, ): Promise { await this.dao.streamQueryAsDBMForEach(this, mapper, opt) } - streamQuery(opt?: CommonDaoStreamOptions>): ReadableTyped> { + streamQuery(opt?: CommonDaoStreamOptions): ReadableTyped { return this.dao.streamQuery(this, opt) } - streamQueryAsDBM(opt?: CommonDaoStreamOptions): ReadableTyped> { + streamQueryAsDBM(opt?: CommonDaoStreamOptions): ReadableTyped { return this.dao.streamQueryAsDBM(this, opt) } diff --git a/src/testing/test.model.ts b/src/testing/test.model.ts index d47faea..a43564b 100644 --- a/src/testing/test.model.ts +++ b/src/testing/test.model.ts @@ -1,4 +1,4 @@ -import { jsonSchema, _range, BaseDBEntity, Saved, JsonSchemaObject } from '@naturalcycles/js-lib' +import { jsonSchema, _range, BaseDBEntity, JsonSchemaObject } from '@naturalcycles/js-lib' import { baseDBEntitySchema, binarySchema, @@ -50,7 +50,10 @@ export const testItemTMSchema = objectSchema({ export const testItemBMJsonSchema: JsonSchemaObject = jsonSchema .rootObject({ + // todo: figure out how to not copy-paste these 3 fields id: jsonSchema.string(), // todo: not strictly needed here + created: jsonSchema.unixTimestamp(), + updated: jsonSchema.unixTimestamp(), k1: jsonSchema.string(), k2: jsonSchema.oneOf([jsonSchema.string(), jsonSchema.null()]).optional(), k3: jsonSchema.number().optional(), @@ -74,7 +77,7 @@ export const testItemDBMJsonSchema: JsonSchemaObject = jsonSchema }) .build() -export function createTestItemDBM(num = 1): Saved { +export function createTestItemDBM(num = 1): TestItemDBM { return { id: `id${num}`, k1: `v${num}`, @@ -86,14 +89,14 @@ export function createTestItemDBM(num = 1): Saved { } } -export function createTestItemBM(num = 1): Saved { +export function createTestItemBM(num = 1): TestItemBM { return createTestItemDBM(num) } -export function createTestItemsDBM(count = 1): Saved[] { +export function createTestItemsDBM(count = 1): TestItemDBM[] { return _range(1, count + 1).map(num => createTestItemDBM(num)) } -export function createTestItemsBM(count = 1): Saved[] { +export function createTestItemsBM(count = 1): TestItemBM[] { return _range(1, count + 1).map(num => createTestItemBM(num)) } diff --git a/yarn.lock b/yarn.lock index 70c573f..90b37a4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -858,9 +858,9 @@ yargs "^17.0.0" "@naturalcycles/js-lib@^14.0.0", "@naturalcycles/js-lib@^14.116.0": - version "14.206.0" - resolved "https://registry.yarnpkg.com/@naturalcycles/js-lib/-/js-lib-14.206.0.tgz#529be8c590f31cd7dd432032387cca239b860c8f" - integrity sha512-PAoaYwrViznvASPixkaXCvonbaLEHs3yb4maQm5b1SXkiQq6viR8NLzaI+8/Rt3iWveP4BScluYYqfbuPJCtgg== + version "14.206.2" + resolved "https://registry.yarnpkg.com/@naturalcycles/js-lib/-/js-lib-14.206.2.tgz#1dda453857d909549e7ef41367b657af60adc522" + integrity sha512-hqMfE3u8zURlrxKPj6jPiiATaHe9CfmeiFdHPj6vCo8MNE4f5bUWnsIBiS771pZF5/YXRD1eZL2oHrFRmZxXaQ== dependencies: tslib "^2.0.0" zod "^3.20.2"