From c0e447b08b6f8c804573655232041caf2744bcf3 Mon Sep 17 00:00:00 2001 From: "D.Zaharov" Date: Thu, 20 May 2021 16:14:24 +0400 Subject: [PATCH] waitfordb function and package config --- .gitignore | 1 + index.js | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 14 +++++++++++ yarn.lock | 4 ++++ 4 files changed, 84 insertions(+) create mode 100644 .gitignore create mode 100644 index.js create mode 100644 package.json create mode 100644 yarn.lock diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..096746c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/node_modules/ \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..6b20de9 --- /dev/null +++ b/index.js @@ -0,0 +1,65 @@ +#! /usr/bin/env node +'use strict' + +const path = require('path'); + +const KNEXFILE_DEFAULT = 'knexfile'; +const RETRY_DEFAULT = 10; +const DELAY_DEFAULT = 1; +const TESTSQL = 'select 1+1'; + +const sleep = (time) => new Promise((r) => setTimeout(r, time)); + +const retry = async (fn, attempts, delaySeconds) => { + for (let i = 1; i <= attempts; i++) { + try { + await fn(); + return true; + } catch (error) { + console.warn(`Attempt #${i}/${attempts} failed: ${error.message}`); + } + if (i < attempts) { + await sleep(1000 * delaySeconds); + } + } + return false; +}; + +const checkConnection = async (config) => { + const knex = require('knex')(config); + try { + await knex.raw(TESTSQL); + } finally { + await knex.destroy(); + } +} + +const checkKnexInstalled = () => { + try { + require('knex'); + } catch (e) { + return false; + } + return true; +} + +const waitfordb = async () => { + const config = require(path.join(process.cwd(), KNEXFILE_DEFAULT)) + if (!checkKnexInstalled()) { + console.error("ERROR: Knex is not installed. Please run 'npm install knex'"); + return process.exit(1); + } + + const rc = await retry(() => checkConnection(config), RETRY_DEFAULT, DELAY_DEFAULT); + if (rc) { + console.info('Database connection successful'); + return process.exit(0); + } else { + console.error('ERROR: There are no more attempts left, exiting...'); + return process.exit(1); + } +} + + +waitfordb() + diff --git a/package.json b/package.json new file mode 100644 index 0000000..d1dcc10 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "knex-waitfordb", + "version": "1.0.0", + "description": "Waiting knex database connection", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "https://github.com/plesk/knex-waitfordb.git" + }, + "bin": { + "knex-waitfordb": "index.js" + }, + "dependencies": {} +} diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..fb57ccd --- /dev/null +++ b/yarn.lock @@ -0,0 +1,4 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + +