2022-05-18 07:26:57 +00:00
|
|
|
// @ts-check
|
|
|
|
|
import pgpFactory from 'pg-promise';
|
2022-06-23 10:04:10 +00:00
|
|
|
import cn from './db-connection-string.cjs';
|
2022-05-18 07:26:57 +00:00
|
|
|
|
|
|
|
|
const pgp = pgpFactory();
|
|
|
|
|
const db = pgp(cn('postgres'));
|
|
|
|
|
|
|
|
|
|
const dbName = 'registry';
|
|
|
|
|
|
2022-11-24 10:00:41 +00:00
|
|
|
// eslint-disable-next-line no-undef
|
|
|
|
|
const log = console.log;
|
|
|
|
|
|
2022-05-18 07:26:57 +00:00
|
|
|
probe().then(() =>
|
|
|
|
|
db
|
|
|
|
|
.query(`SELECT 1 FROM pg_database WHERE datname = '${dbName}'`)
|
2022-05-24 13:31:53 +00:00
|
|
|
.then(result => {
|
2022-05-18 07:26:57 +00:00
|
|
|
if (!result.length) {
|
2022-11-24 10:00:41 +00:00
|
|
|
log(`Creating "${dbName}" database`);
|
2022-05-18 07:26:57 +00:00
|
|
|
return db.query(`CREATE DATABASE ${dbName}`);
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-24 10:00:41 +00:00
|
|
|
log(`Database "${dbName}" already exists`);
|
2022-05-18 07:26:57 +00:00
|
|
|
})
|
|
|
|
|
.then(() => {
|
2022-11-24 10:00:41 +00:00
|
|
|
// eslint-disable-next-line no-undef
|
2022-05-18 07:26:57 +00:00
|
|
|
process.exit(0);
|
|
|
|
|
})
|
2022-05-24 13:31:53 +00:00
|
|
|
.catch(error => {
|
2022-11-24 10:00:41 +00:00
|
|
|
// eslint-disable-next-line no-undef
|
2022-05-18 07:26:57 +00:00
|
|
|
console.error(error);
|
2022-11-24 10:00:41 +00:00
|
|
|
// eslint-disable-next-line no-undef
|
2022-05-18 07:26:57 +00:00
|
|
|
process.exit(1);
|
2022-11-24 10:00:41 +00:00
|
|
|
}),
|
2022-05-18 07:26:57 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
*
|
|
|
|
|
* @param {number} numberOfRetries
|
|
|
|
|
* @returns {any}
|
|
|
|
|
*/
|
|
|
|
|
function probe(numberOfRetries = 0) {
|
2022-05-24 13:31:53 +00:00
|
|
|
return db.any(`SELECT 1`).catch(async err => {
|
2022-05-18 07:26:57 +00:00
|
|
|
if (numberOfRetries === 15) {
|
|
|
|
|
throw new Error('Database not ready after 15 retries. Exiting.');
|
|
|
|
|
}
|
2022-11-24 10:00:41 +00:00
|
|
|
log('Database not ready. Retry in 1000ms\nReason:\n' + err);
|
|
|
|
|
// eslint-disable-next-line no-undef
|
2022-05-24 13:31:53 +00:00
|
|
|
await new Promise(res => setTimeout(res, 1000));
|
2022-05-18 07:26:57 +00:00
|
|
|
return probe(numberOfRetries + 1);
|
|
|
|
|
});
|
|
|
|
|
}
|