I have an object of valid query parameters for each object type for a GET request to the API.
var queryFields = {
'organisation': ['limit', 'page', 'id', 'search'],
'actor': ['limit', 'page', 'id', 'search'],
'version': ['limit', 'page', 'search'],
'product': ['limit', 'page', 'search', 'id', 'type', 'brand', 'model', 'manufacturerSpid'],
'asset': ['limit', 'page', 'search', 'order', 'sort', 'id', 'name', 'currentCustodianSpid', 'currentLocationSpid', 'productSpid', 'search'],
'location': ['limit', 'page', 'search', 'id'],
'workorder': ['limit', 'page', 'search', 'id', 'type', 'status', 'requirementSpid', ],
'move': ['limit', 'page', 'search'],
'transfer': ['limit', 'page', 'search'],
'requirement': ['limit', 'page', 'search', 'id', 'type', 'source', 'productSpid', 'status', ],
'artefact': ['limit', 'page', 'search'],
'attestation': ['limit', 'page', 'search'],
};
I want to use this function to make sure that only these valid parameters are accepted for a request. Right now the promise resolves false with valid, invalid, or 0 parameters. It seems to be an issue with the way I am filtering. I pass in the object type and the request. If the request has query parameters, I want to grab the valid parameters from the object, and check that the parameters in the req are all valid matches to ones in the object. If there are any that are invalid, I want to resolve false. If there are no parameters, I want to resolve true. If there are only valid parameters, I want to resolve true. Is there some tweaking I can do to this function to get that outcome?
function getQueryFields(object) {
if (utils.isDefined(queryFields[object])) return queryFields[object];
return [];
}
function fieldValidator (objType, req) {
return new Promise(function(resolve) {
if (utils.isDefined(req.query)) {
var fields = getQueryFields(objType);
//Only resolve true with valid fields
fields = fields.filter(function(field) { return Object.keys(req.query).indexOf(field) > -1;});
if (Object.keys(req.query) !== Object.keys(fields)) {
resolve(false);
} else {
resolve (true);
}
} else {
resolve(true);
}
});
}
Promise, everything in there is synchronous. You can return abooleandirectly. And also, there's no need forutils.isDefined, a simpleif(req.query)is enough. Which also is not needed if you're usingexpress,req.queryis always defined as an empty object if there's no parameter.fieldValidator