by rafram · 1y ago · 0 comments
let someArray = [1, 2, , 4];
console.log(as.numbers(someArray) === someArray); // => true
for (let number of numbers) {
// This should be safe because I know everything in the array is a number, right?
console.log(number.toFixed(2)); // => TypeError: number is undefined
}
I mean, it's probably fine if you're only ever getting your data from JSON.parse(). But I would hesitate to use this in production.So 90% of use cases?
If something can directly hand you a maliciously built data structure, you're probably designing your system wrong. Are you running untrusted javascript in the same interpreter? That's a very hard problem that should be avoided if at all possible.
Basically, only working on JSON.parse is something to document but it's not at all a weird restriction, or a reason to balk at putting it into production.
1. Validate your Buffer/UInt8Array for valid size/encoding/etc first
2. Parse it to an object via JSON.parse or whatever your use-case needs
3. Reach into it with this function to get data if it matches the type you need
This code only deals with #3 and makes a few assumptions about #2 (e.g. no undefined, typical JSON-like object, etc).