UNPKG

newmax-utils

Version:
52 lines (51 loc) 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.bulkCreate = void 0; const ApiError_1 = require("./ApiError"); const Winston_1 = require("./libs/Winston"); const winston_config_1 = require("./configs/winston.config"); const Sequelize_1 = require("./utils/Sequelize"); async function bulkCreate(Model, dataList, duplicateList, comment, transaction) { const schemaName = Model.getTableName().schema; const tableName = Model.getTableName().tableName; const fieldList = Object.keys(Model.getAttributes()); const Logger = new Winston_1.Winston({ schema: schemaName }); const logger = Logger.createInstance({ fn: 'bulkCreate' }); const colorSchemaName = Logger.colorize('magenta', schemaName); const colorTableName = Logger.colorize('cyan', tableName); if (!(dataList instanceof Array)) { throw new ApiError_1.ApiError(-1, `[${schemaName}.${tableName}]: Bulk didn't complete: IS NOT ARRAY`, { comment, }); } if (!dataList.length) { logger.log(winston_config_1.winstonConfig.levelsEnums.warn, `[${colorSchemaName}.${colorTableName}]: Bulk didn't complete: EMPTY`, { comment }); return; } try { await Model.bulkCreate(dataList, { fields: fieldList, updateOnDuplicate: duplicateList, transaction, }); logger.log(winston_config_1.winstonConfig.levelsEnums.info, `[${colorSchemaName}.${colorTableName}]: Bulk completed success`, { comment }); } catch (e) { if (e.original.message === 'Operation timeout') { return await bulkCreate(Model, dataList, duplicateList, comment, transaction); } if (e.original.code === '40P01') { // deadlock detected return await bulkCreate(Model, dataList, duplicateList, comment, transaction); } if (e.original.code === '55P03') { // canceling statement due to lock timeout return await bulkCreate(Model, dataList, duplicateList, comment, transaction); } throw new Sequelize_1.SequelizeError(`[${colorSchemaName}.${colorTableName}]: Bulk completed error`, { original: e.original, comment, }); } } exports.bulkCreate = bulkCreate;