fix context key validation + add tests

- adds a helper function validateContextKey to keep it DRY
- adds tests ensure key of null "" 1 {} [] [""] [1] [{}] all throw error
This commit is contained in:
Steve-Mcl
2021-05-26 13:04:09 +01:00
parent 4d768fd236
commit a92f0c4c6e
2 changed files with 181 additions and 10 deletions

View File

@@ -215,6 +215,22 @@ function followParentContext(parent, key) {
return null;
}
function validateContextKey(key) {
try {
const keys = Array.isArray(key) ? key : [key];
if(!keys.length) { return false }; //no key to get/set
for (let index = 0; index < keys.length; index++) {
const k = keys[index];
if (typeof k !== "string" || !k.length) {
return false; //not string or zero-length
}
}
} catch (error) {
return false;
}
return true;
}
function createContext(id,seed,parent) {
// Seed is only set for global context - sourced from functionGlobalContext
var scope = id;
@@ -251,14 +267,11 @@ function createContext(id,seed,parent) {
}
}
}
Object.defineProperties(obj, {
get: {
value: function(key, storage, callback) {
var context;
if (typeof key !== "string" || !key.length) {
throw new Error("context get() requires 'key' to be a valid string");
}
if (!callback && typeof storage === 'function') {
callback = storage;
storage = undefined;
@@ -266,7 +279,14 @@ function createContext(id,seed,parent) {
if (callback && typeof callback !== 'function'){
throw new Error("Callback must be a function");
}
if (!validateContextKey(key)) {
var err = Error("Invalid context key");
if(callback) {
return callback(err);
} else {
throw err;
}
}
if (!Array.isArray(key)) {
var keyParts = util.parseContextStore(key);
key = keyParts.key;
@@ -340,10 +360,6 @@ function createContext(id,seed,parent) {
set: {
value: function(key, value, storage, callback) {
var context;
if (typeof key !== "string" || !key.length) {
throw new Error("context set() requires 'key' to be a valid string");
}
if (!callback && typeof storage === 'function') {
callback = storage;
storage = undefined;
@@ -351,7 +367,14 @@ function createContext(id,seed,parent) {
if (callback && typeof callback !== 'function'){
throw new Error("Callback must be a function");
}
if (!validateContextKey(key)) {
var err = Error("Invalid context key");
if(callback) {
return callback(err);
} else {
throw err;
}
}
if (!Array.isArray(key)) {
var keyParts = util.parseContextStore(key);
key = keyParts.key;