Created
December 24, 2018 11:41
-
-
Save hidori/322ac187f811d68cf07ee97eaf0aac01 to your computer and use it in GitHub Desktop.
DB Helper for testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const SqlBuilder = require('json-sql-builder2'); | |
const fs = require('fs'); | |
const path = require('path'); | |
module.exports = class DbHelper { | |
static async init(connection, name) { | |
await this.execute(connection, name, 'truncate'); | |
await this.execute(connection, name, 'seed'); | |
} | |
static async execute(connection, name, command) { | |
const dir = path.resolve(__dirname, `../db/${name}/${command}`); | |
if (fs.existsSync(dir)) { | |
const files = fs.readdirSync(dir).map(_ => path.resolve(dir, _)).filter(_ => fs.statSync(_).isFile() && _.match(/\.sql$/i)); | |
const sqls = files.map(_ => fs.readFileSync(_, { encoding: 'utf8' })); | |
const results = await Promise.all(sqls.map(async _ => await connection.query(_))); | |
return results; | |
} | |
} | |
static async insert(connection, $table, source, action) { | |
const builder = new SqlBuilder('MySQL'); | |
const sql = source.map($documents => builder.$insert({ $table, $documents })).map(_ => `${connection.format(_.sql, _.values)};`).join('\n'); | |
const results = await connection.query(sql); | |
if (action) { | |
action(results); | |
} | |
return results; | |
} | |
static async select(connection, $from, options) { | |
options = Object.assign({}, options); | |
const $columns = options.columns ? options.columns : '*'; | |
const builder = new SqlBuilder('MySQL'); | |
const sql = [1].map(() => builder.$select({ $columns, $from })).map(_ => `${connection.format(_.sql, _.values)};`).join('\n'); | |
const results = await connection.query(sql); | |
return results; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment