0

Using bash, I think this is possible, but not sure about JavaScript, say we have this:

    const {masterid} = req.query;

    if (!masterid) {
        return res.status(500).send(new Error('Missing query param "masterid".'));
    }

What I want to do is not hardcode "masterid" in the string, instead do something like this:

    const {masterid} = req.query;

    if (!masterid) {
        return res.status(500).send(new Error(`Missing query param "${Reflect(masterid).name()}.".`));
    }

is there a way to do this with the Reflect API?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect

Machavity
  • 30,841
  • 27
  • 92
  • 100
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • I think the OP is similar to this question: https://stackoverflow.com/questions/7861956/javascript-reflection-obtaining-a-variables-name – Alexander Mills Sep 17 '18 at 22:54
  • Not sure exactly what your use case is, but could you use a key/value setup instead? param = { key:"masterid", val="whatever" }. Then if you had a bunch of these you could loop through them and if the value is missing return res.status(500).send(new Error("missing " + iteratedParam.key)) – William Prevett Sep 17 '18 at 23:03

2 Answers2

5

From this other post

var masterid = 2;
var text = Object.keys({masterid})[0]; //equals "masterid"
Without Haste
  • 507
  • 2
  • 6
1

This may be possible for testing/debugging purposes but is inappropriate in production. The only way is to tamper it in some way, e.g. parse it, modify and evaluate. For instance, rewire uses eval to intercept top-level module variables, this approach won't work with scoped variables.

Due to these JavaScript limitations, a proper approach is to not rely on variables. There will be no problems with handling property names. Assertions are common in Node, this case can make use of helper function:

assertParam(obj, param) {
  assert.ok(obj[param], `Missing param "${param}".`);
}

...

try {
  assertParam(req.query, 'masterid');
} catch (err) {
  return res.status(500).send(err);
}
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Security risk in production? – Alexander Mills Sep 17 '18 at 23:39
  • I wouldn't expect any specific risk in this particular case because it won't be affected from the outside and cannot be exploited by intruder. Source code patching is unsuitable for production because this would be too complex, potentially buggy and slow. – Estus Flask Sep 17 '18 at 23:52