Add typeguard for node data passed in requests.

This commit is contained in:
baldo 2022-07-28 13:56:47 +02:00
parent d783bb634f
commit 779c072ac7

View file

@ -10,9 +10,13 @@ import {Request, Response} from "express";
import { import {
CreateOrUpdateNode, CreateOrUpdateNode,
DomainSpecificNodeResponse, DomainSpecificNodeResponse,
isCreateOrUpdateNode,
isNodeSortField, isNodeSortField,
isString,
isToken, isToken,
isUndefined,
JSONObject, JSONObject,
JSONValue,
MAC, MAC,
NodeResponse, NodeResponse,
NodeStateData, NodeStateData,
@ -25,19 +29,27 @@ import {
const nodeFields = ['hostname', 'key', 'email', 'nickname', 'mac', 'coords', 'monitoring']; const nodeFields = ['hostname', 'key', 'email', 'nickname', 'mac', 'coords', 'monitoring'];
// TODO: Rename function getNormalizedNodeData(reqData: JSONObject): CreateOrUpdateNode {
function getNormalizedNodeData(reqData: any): CreateOrUpdateNode {
const node: { [key: string]: any } = {}; const node: { [key: string]: any } = {};
for (const field of nodeFields) { for (const field of nodeFields) {
let value = normalizeString(reqData[field]); let value: JSONValue | undefined = reqData[field];
if (field === 'mac') { if (isString(value)) {
value = normalizeMac(value as MAC); value = normalizeString(value);
if (field === 'mac') {
value = normalizeMac(value as MAC);
}
}
if (!isUndefined(value)) {
node[field] = value;
} }
node[field] = value;
} }
// TODO: Add typeguard before cast. if (isCreateOrUpdateNode(node)) {
return node as CreateOrUpdateNode; return node;
}
throw {data: "Invalid node data.", type: ErrorTypes.badRequest};
} }
const isValidNode = forConstraints(Constraints.node, false); const isValidNode = forConstraints(Constraints.node, false);