snippeteer/snippets/migration/csv.template.js

59 lines
1.1 KiB
JavaScript
Raw Normal View History

2020-02-26 20:52:39 +01:00
'use strict';
const csv = require ('csv-parse');
const fs = require ('fs-extra');
const path = require ('path');
/**
* get all csv data that should be loaded
*
* @returns {Promise<Array<object>>} csv data
*/
async function get_csv () {
const csv_list = await Promise.all ((
await fs.readdir ('migrations/csv'))
.map (
async (file) => {
if (path.extname (file) !== '.csv')
return null;
const name = path.basename (file, '.csv');
const data = [];
const parser = csv (await fs.readFile (
path.join ('migrations/csv', file)
), { columns: true });
for await (const entry of parser)
data.push (entry);
return { name, data };
}
));
return csv_list.filter ((val) => val !== null);
}
/**
* execute migration
*
* @param {any} knex database connection
*/
async function up (knex) {
const data = await get_csv ();
await Promise.all (
data.map (
(table) => knex (table.name)
.insert (table.data)
)
);
}
/**
* revert migration
*/
function down () {
// noop
}
module.exports = { up, down };