From 692f48883c73767c9224b782c0f01bb5e50973fd Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Mon, 20 Jan 2020 09:12:01 +0100 Subject: [PATCH] add migration template --- snippets/migration/index.js | 69 ++++++++++++++++++++++++++++++++++ snippets/migration/template.js | 24 ++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 snippets/migration/index.js create mode 100644 snippets/migration/template.js diff --git a/snippets/migration/index.js b/snippets/migration/index.js new file mode 100644 index 0000000..a37e715 --- /dev/null +++ b/snippets/migration/index.js @@ -0,0 +1,69 @@ +/* + * 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 , January 2020 + */ + +/* eslint-disable no-sync */ +/* eslint-disable no-console */ + +const fs = require ('fs-extra'); +const path = require ('path'); + +/** + * copies the full template to a new folder named after arg[0] + * + * @param {string} folder folder to run in + * @param {Array} args function arguments + */ +async function run (folder, args) { + const template = path.join (__dirname, 'template.js'); + const dest = path.join (folder, `${args[0]}.js`); + await fs.writeFile (dest, await fs.readFile (template)); +} + +/** + * checks if the arguments meet the requirements + * + * @param {string} folder folder to run in + * @param {Array} args function arguments + * @returns {boolean} true if arguments match requirements + */ +function assert (folder, args) { + const tests = [ + { + f: () => (args.length < 2), + reason: 'too many arguments' + }, + { + f: () => (args.length === 1 && typeof args[0] === 'string'), + reason: 'name is not a string' + }, + { + f: () => ((/^[0-9]+-[a-z]+$/iu).test (args[0])), + reason: 'name has to match /^[0-9]+-[a-z]+$/' + }, + { + f: () => (typeof folder === 'string'), + reason: 'cwd is not a folder (internal error)' + }, + { + f: () => (fs.existsSync (folder)), + reason: 'cwd does not exist (internal error)' + }, + { + f: () => (!fs.existsSync (path.join (folder, args[0]))), + reason: 'migration already exists' + } + ]; + for (const test of tests) + if (!test.f ()) { + console.log (test.reason); + return false; + } + + return true; +} + +module.exports = { run, assert }; diff --git a/snippets/migration/template.js b/snippets/migration/template.js new file mode 100644 index 0000000..dbb8383 --- /dev/null +++ b/snippets/migration/template.js @@ -0,0 +1,24 @@ +/* eslint-disable no-magic-numbers */ + +/** + * execute migration + * + * @param {any} knex database connections + */ +async function up (knex) { + await knex.schema.createTable ('template', (table) => { + table.increments ('id'); + table.string ('text', 64); + }); +} + +/** + * revert migration + * + * @param {any} knex database connections + */ +async function down (knex) { + await knex.schema.dropTable ('template'); +} + +module.exports = { up, down };