Home > Enterprise >  Store webhooks functions inside a master function
Store webhooks functions inside a master function

Time:01-02

I have set up multiple webhook endpoints that follow the similar structure in Node.js: 1) stringify the JSON request and 2) do something about that stringified request in R.

This consequently leads to a lot of duplicate code, and I attempt to stay DRY by creating a function in which I specify the arguments that actually do change. Here's an example.

First, the top portion of the script:

require("dotenv").config();
const express = require("express");
const app = express();
const port = 3000;
app.use(express.json());

Then, the part I would like to rewrite into a master function (WH) in which everything capitalized below between < and > becomes the argument.

app.post(<ENDPOINT>, foobar);
function foobar(req, res) {
  var spawn = require("child_process").spawn;
  let body = JSON.stringify(req.body);
  var R_shell = spawn("/usr/local/bin/Rscript", [<PATH_TO_SCRIPT>,  body]);

  res.end("Processing completed");
}

app.get(<ENDPOINT>, (req, res) => res.send(`<html><body><h1>All working!</h1></body></html>
`));

Hence, with two endpoints, I'd end up with:

require("dotenv").config();
const express = require("express");
const app = express();
const port = 3000;
app.use(express.json());


WH(endpoint="foo", script_path="baz")
WH(endpoint="lorem", script_path="dolor")

P.S. Sorry if this is poorly formulated question from a Node.js standpoint—it's my first time developing with Node.js.

CodePudding user response:

If I understood your question correctly, what you can do is something like this:

Firstly, you need to create a function that returns a router with the specified routes (You could create this function in a different file to make the code cleaner).

const {Router} = require('express')

function WH(endpoint, scriptPath) {
  const router = Router()
  
  function fn(req, res) {
    var spawn = require("child_process").spawn;
    let body = JSON.stringify(req.body);
    var R_shell = spawn("/usr/local/bin/Rscript", [scriptPath,  body]);

    res.end("Processing completed");
  }

  router.post(endpoint, fn);
  router.get(endpoint, (req, res) => res.send(`<html><body><h1>All working!</h1></body></html>`));

  return router
}

And finally you should use it like this:

require("dotenv").config();
const express = require("express");
const app = express();
const port = 3000;
app.use(express.json());

app.use(WH("/foo", "./baz"))
app.use(WH("/lorem", "./dolor"))

I don't get why would you like to change the function name, it won't affect anything.

  • Related