APIGEE - Default values in destructuring declarations are not supported

86 Views Asked by At

I am writing a javascript to validate whether client ip is in range of whitelisted IP. I am getting error

Compilation of JavaScript jsc://ApiKeyPathValidator.js failed with error:Compilation error: Default values in destructuring declarations are not supported (ApiKeyPathValidator#323). Line:323, column:23. Source is:const [range, bits = 32] = cidr.split('/')

Javascript code below

const ip4ToInt = ip =>
  ip.split('.').reduce((int, oct) => (int << 8) + parseInt(oct, 10), 0) >>> 0;

const isIp4InCidr = ip => cidr => {
  const [range, bits = 32] = cidr.split('/');
  const mask = ~(2 ** (32 - bits) - 1);
  return (ip4ToInt(ip) & mask) === (ip4ToInt(range) & mask);
};

var whitelistedCidr=['10.0.0.1', '10.1.1.1/21','10.0.0.1'];
var clientIp=getEnv("request.header.X-Forwarded-For");


const isIp4InCidrs = (ip, cidrs) => cidrs.some(isIp4InCidr(ip));
var isInRange=false;
isInRange=isIp4InCidrs(clientIp, whitelistedCidr); 
console.log("Whitelisted IP Test");
console.log(isInRange);
1

There are 1 best solutions below

0
T.J. Crowder On BEST ANSWER

"Default values in destructuring declarations are not supported" is telling you that the syntax you're using here is not supported:

const [range, bits = 32 ] = cidr.split('/');

The const [range, bits = 32] part is a destructuring declaration, and the = 32 part is a default value.

That's perfectly valid JavaScript syntax, but apparently it's not supported by the tool you're using. So do it the old fashioned way:

const parts = cidr.split('/');
const range = parts[0];
const bits = parts[1] ?? 32;

Or similar. (If the tool also doesn't support ??, you might use const bits = 1 in parts ? parts[1] : 32; or const bits = parts[1] || 32; depending on how you're going to use bits.)


Side note: The result of split is always an array of strings, so with your code (and the amended versions above), in some situations your bits constant will contain a string, and other times it'll contain a number (32). In general, it's probably best to use one or the other consistently, perhaps by parsing parts[1] to number if it's provided.