piston/api/src/index.js

73 lines
2.0 KiB
JavaScript
Raw Normal View History

2021-01-14 20:14:26 +01:00
const express = require('express');
2021-01-16 13:14:17 +01:00
const { execute } = require('../../shared/execute');
2021-01-16 00:53:51 +01:00
const { languages } = require('./languages');
const { checkSchema, validationResult } = require('express-validator');
2021-01-14 21:06:26 +01:00
2021-01-16 00:53:51 +01:00
const PORT = 2000;
2021-01-14 21:06:26 +01:00
2021-01-16 00:53:51 +01:00
const app = express();
app.use(express.json());
2021-01-15 20:40:18 +01:00
2021-01-16 00:53:51 +01:00
app.post(
'/execute',
checkSchema({
language: {
in: 'body',
notEmpty: {
errorMessage: 'Supply a language field',
},
isString: {
errorMessage: 'Supplied language is not a string',
},
custom: {
2021-01-16 00:59:25 +01:00
options: value => languages.find(language => language.aliases.includes(value?.toLowerCase())),
2021-01-16 00:53:51 +01:00
errorMessage: 'Supplied language is not supported by Piston',
},
},
source: {
in: 'body',
notEmpty: {
errorMessage: 'Supply a source field',
},
isString: {
errorMessage: 'Supplied source is not a string',
},
},
args: {
in: 'body',
optional: true,
isArray: {
errorMessage: 'Supplied args is not an array',
},
2021-01-14 21:06:26 +01:00
}
2021-01-16 00:53:51 +01:00
}),
2021-01-16 13:14:17 +01:00
async (req, res) => {
2021-01-16 00:53:51 +01:00
const errors = validationResult(req).array();
if (errors.length === 0) {
const language = languages.find(language =>
language.aliases.includes(req.body.language.toLowerCase())
);
2021-01-16 13:14:17 +01:00
const { stdout, stderr, output } = await execute(language, req.body.source, req.body.args);
res.status(200).json({
ran: true,
language: language.name,
version: language.version,
stdout,
stderr,
output,
});
2021-01-16 00:53:51 +01:00
} else {
res.status(400).json({
message: errors[0].msg,
});
2021-01-14 21:06:26 +01:00
}
2021-01-16 00:53:51 +01:00
},
);
2021-01-14 20:14:26 +01:00
2021-01-16 00:53:51 +01:00
app.get('/versions', (_, res) => res.json(languages));
2021-01-14 20:14:26 +01:00
app.listen(PORT, () => console.log(`Listening on port ${PORT}`));