wg-easy/src/lib/Util.js

74 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-05-23 04:21:09 +08:00
'use strict';
2021-05-23 04:45:47 +08:00
const childProcess = require('child_process');
2021-05-23 04:21:09 +08:00
module.exports = class Util {
2021-07-14 02:51:23 +08:00
static isValidIPv4(str) {
const blocks = str.split('.');
if (blocks.length !== 4) return false;
for (let value of blocks) {
value = parseInt(value, 10);
if (Number.isNaN(value)) return false;
if (value < 0 || value > 255) return false;
}
return true;
}
2021-05-23 04:21:09 +08:00
static promisify(fn) {
2021-05-23 21:27:46 +08:00
// eslint-disable-next-line func-names
2021-05-23 04:21:09 +08:00
return function(req, res) {
Promise.resolve().then(async () => fn(req, res))
.then(result => {
if (res.headersSent) return;
if (typeof result === 'undefined') {
return res
.status(204)
.end();
}
return res
.status(200)
.json(result);
})
.catch(error => {
if (typeof error === 'string') {
error = new Error(error);
}
2021-05-23 18:04:43 +08:00
// eslint-disable-next-line no-console
console.error(error);
2021-05-23 04:21:09 +08:00
return res
.status(error.statusCode || 500)
.json({
error: error.message || error.toString(),
stack: error.stack,
});
});
};
}
2021-05-23 04:45:47 +08:00
static async exec(cmd) {
2021-05-23 21:27:46 +08:00
// eslint-disable-next-line no-console
console.log(`$ ${cmd}`);
2021-05-23 04:45:47 +08:00
if (process.platform !== 'linux') {
return '';
}
return new Promise((resolve, reject) => {
2021-05-23 20:28:22 +08:00
childProcess.exec(cmd, {
shell: 'bash',
}, (err, stdout) => {
2021-05-23 04:45:47 +08:00
if (err) return reject(err);
2021-05-23 18:02:56 +08:00
return resolve(String(stdout).trim());
2021-05-23 04:45:47 +08:00
});
});
}
2021-05-23 04:21:09 +08:00
};