66 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			66 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
| /*
 | |
|  * Copyright (C) Sapphirecode - All Rights Reserved
 | |
|  * This file is part of Snippeteer which is released under BSD-3-Clause.
 | |
|  * See file 'LICENSE' for full license details.
 | |
|  * Created by Timo Hocker <timo@scode.ovh>, March 2020
 | |
|  */
 | |
| 
 | |
| '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 (
 | |
|       // eslint-disable-next-line no-magic-numbers
 | |
|       (table) => knex.bulkInsert (table.name, table.data, 64)
 | |
|     )
 | |
|   );
 | |
| }
 | |
| 
 | |
| /**
 | |
|  * revert migration
 | |
|  */
 | |
| function down () {
 | |
|   // noop
 | |
| }
 | |
| 
 | |
| module.exports = { up, down };
 |