Skip to content

Commit

Permalink
Add change-db js file to build utils
Browse files Browse the repository at this point in the history
  • Loading branch information
SebastienGllmt committed Dec 9, 2023
1 parent 64d4681 commit 5204a63
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/build-utils/paima-build-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"build": "tsc --project tsconfig.cjs.json && tsc --project tsconfig.esm.json"
},
"bin": {
"paima-build-middleware": "./scripts/esbuild.sh"
"paima-build-middleware": "./scripts/esbuild.sh",
"paima-reset-db": "./scripts/change-db.js"
},
"peerDependencies": {
"esbuild": "^0.19.3",
Expand Down
58 changes: 58 additions & 0 deletions packages/build-utils/paima-build-utils/scripts/change-db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const fs = require('fs');
const https = require('https');

// RPC command
const getBlockHeight = (url, command) =>
new Promise((resolve, reject) => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': JSON.stringify(command).length,
},
};

const req = https.request(url, options, response => {
let result = '';
response.on('data', chunk => (result += chunk));
response.on('end', () => resolve(parseInt(JSON.parse(result).result.number, 16)));
});
req.on('error', err => reject(err));
req.write(JSON.stringify(command));
req.end();
});

// Update .env START_BLOCKHEIGHT with latest value from RPC command: "eth_getBlockByNumber"
const updateEnvFile = async file => {
const dataEnv = await fs.promises.readFile(__dirname + '/' + file, 'utf8');
const url = dataEnv.match(/\nCHAIN_URI="(.+)"/)[1];
if (!url) throw new Error('CHAIN_URI not found');
const START_BLOCKHEIGHT = await getBlockHeight(url, {
jsonrpc: '2.0',
method: 'eth_getBlockByNumber',
params: ['latest', false],
id: 1,
});
const ndataEnv = dataEnv.replace(
/\nSTART_BLOCKHEIGHT="\d+"/,
`\nSTART_BLOCKHEIGHT="${START_BLOCKHEIGHT}"`
);
await fs.promises.writeFile(file, ndataEnv, 'utf8');
console.log(`ENV file changed: START_BLOCKHEIGHT="${START_BLOCKHEIGHT}"`);
};

// Update docker compose volume with unique new name.
const updateDockerFile = async file => {
const data = await fs.promises.readFile(__dirname + '/' + file, 'utf8');
const ndata = data.replace(/generic(-.+)?-db/g, 'generic-' + new Date().getTime() + '-db');
await fs.promises.writeFile(file, ndata, 'utf8');
};

const start = async () => {
await updateEnvFile(`../.env.${process.env.NODE_ENV ?? 'development'}`);
await updateDockerFile('db/docker/docker-compose.yml');
};

start()
.then()
.catch(e => console.log('Error:', e));

0 comments on commit 5204a63

Please sign in to comment.