wg-easy/src/lib/Util.js
Emile Nijssen 30f56510e6 wip
2021-05-23 15:27:46 +02:00

61 lines
1.3 KiB
JavaScript

'use strict';
const childProcess = require('child_process');
module.exports = class Util {
static promisify(fn) {
// eslint-disable-next-line func-names
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);
}
// eslint-disable-next-line no-console
console.error(error);
return res
.status(error.statusCode || 500)
.json({
error: error.message || error.toString(),
stack: error.stack,
});
});
};
}
static async exec(cmd) {
// eslint-disable-next-line no-console
console.log(`$ ${cmd}`);
if (process.platform !== 'linux') {
return '';
}
return new Promise((resolve, reject) => {
childProcess.exec(cmd, {
shell: 'bash',
}, (err, stdout) => {
if (err) return reject(err);
return resolve(String(stdout).trim());
});
});
}
};