The basic idea is, you create a database of functions stored as strings. Since JS allows you to create a function from a string using the Function()
constructor, you can dynamically generate a function on demand. I've provided a POST
endpoint to register the function.
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
var mongoose = require('mongoose');
db = mongoose.connect('mongodb://localhost:27017/login1');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var data = new mongoose.Schema({
"name": String,
"content": String
});
model = mongoose.model("functions", data);
router.post('/create', (req, res) => {
// Insert validation for security and removing duplicates etc.
model.insertMany({"name": req.body.name, "content": req.body.content}).then((d, err) => {
res.status(200).send({'result': "Added"});
});
});
router.get('/:func/*', (req, res) => {
var func = req.params.func;
var args = req.params['0'].split('/');
model.findOne({"name": func}).then((d, err) => {
if (err) {return res.status(404).send({'result': "Error with database"});}
else if (d === null) {return res.status(202).send({'result': "Function not present"});}
var func = Function(d.content);
res.status(200).send({'result': func(...args)});
});
});
app.use("/", router);
var port = process.env.PORT || 3000;
var server = app.listen(port, function() {
console.log('Express server listening on port ' + port);
});
Lets test this:
$ node server.js
Express server listening on port 3000
From postman or another terminal window:
$ curl -X GET "http://localhost:3000/add/1/2/3"
{"result":"Function not present"}
Now lets register the add
function (which is sum of arguments
):
$ curl -X POST "http://localhost:3000/create/" -H "content-type:application/json" -d '{"name": "add", "content": "return [...arguments].reduce( (i, j) => i+=parseInt(j), 0);"}'
{'result': "Added"}
The function registered here can be far more complicated. Just remember that you can get all the arguments passed to the function using the Agruments variable.
Test it:
$ curl -X GET "http://localhost:3000/add/1/2/3"
{"result": 6}
$ curl -X GET "http://localhost:3000/add/100/3/5/10/9/2"
{"result": 129}