Skip to content

Commit

Permalink
waitfordb function and package config
Browse files Browse the repository at this point in the history
  • Loading branch information
tdimdimich committed May 20, 2021
1 parent 3d1513c commit c0e447b
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/node_modules/
65 changes: 65 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -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()

14 changes: 14 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -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": {}
}
4 changes: 4 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1


0 comments on commit c0e447b

Please sign in to comment.