piston/api/src/index.js

64 lines
1.7 KiB
JavaScript
Raw Normal View History

2021-01-14 20:14:26 +01:00
const express = require('express');
2021-01-16 00:53:51 +01:00
const { execute } = require('./execute');
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
}),
(req, res) => {
const errors = validationResult(req).array();
if (errors.length === 0) {
const language = languages.find(language =>
language.aliases.includes(req.body.language.toLowerCase())
);
execute(res, language, req.body);
} 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}`));