2024-05-09 17:22:15 +03:00
|
|
|
const TableImporter = require('../importers/TableImporter');
|
|
|
|
|
|
|
|
class JsonImporter extends TableImporter {
|
2023-08-02 16:43:26 +03:00
|
|
|
constructor(knex, transaction) {
|
2024-05-09 17:22:15 +03:00
|
|
|
super();
|
2022-11-03 17:54:17 +03:00
|
|
|
this.knex = knex;
|
2023-08-02 16:43:26 +03:00
|
|
|
this.transaction = transaction;
|
2022-11-03 17:54:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @typedef {Object} JsonImportOptions
|
|
|
|
* @property {string} name Name of the table to import
|
|
|
|
* @property {Object} data Models without ids to be imported
|
|
|
|
* @property {Array<string>} [rows] Set of rows to be returned
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Import a dataset to the database
|
|
|
|
* @param {JsonImportOptions} options
|
2023-08-02 16:43:26 +03:00
|
|
|
* @returns {Promise}
|
2022-11-03 17:54:17 +03:00
|
|
|
*/
|
|
|
|
async import({
|
|
|
|
name,
|
|
|
|
data,
|
|
|
|
rows = []
|
|
|
|
}) {
|
|
|
|
for (const obj of data) {
|
|
|
|
if (!('id' in obj)) {
|
2024-01-05 16:42:30 +03:00
|
|
|
obj.id = this.fastFakeObjectId();
|
2022-11-03 17:54:17 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if (rows.findIndex(row => row === 'id') === -1) {
|
|
|
|
rows.unshift('id');
|
|
|
|
}
|
2023-08-02 16:43:26 +03:00
|
|
|
await this.knex.batchInsert(name, data, 500).transacting(this.transaction);
|
2022-11-03 17:54:17 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = JsonImporter;
|