The product object to validate
Array of missing or invalid field names (empty if all fields are valid)
TypeError if product is null or not an object
const product = { title: "NaCl", price: 29.99 };
const missing = checkMissingMinimalProductFields(product);
// ["quantity", "uom", "supplier", "url", "currencyCode", "currencySymbol"]
export function checkMissingMinimalProductFields(product: unknown): string[] {
if (!product || typeof product !== "object") {
throw new TypeError("checkMissingMinimalProductFields| Invalid product", { cause: product });
}
const requiredProps: Record<keyof RequiredProductFields, string> = {
title: "string",
price: "number",
quantity: "number",
uom: "string",
supplier: "string",
url: "string",
currencyCode: "string",
currencySymbol: "string",
};
const record = product as Record<string, unknown>;
const result = Object.entries(requiredProps).reduce(
(acc: string[], [key, expectedType]: [string, string]) => {
if (key in record === false) {
console.debug("checkMissingMinimalProductFields| No value found in product", {
product,
key,
});
return [...acc, key];
}
if (typeof record[key] !== expectedType) {
console.debug("checkMissingMinimalProductFields| Property not the correct type", {
product,
key,
expectedType,
actualType: typeof record[key],
});
return [...acc, key];
}
return acc;
},
[],
);
if (result.length > 0) {
console.warn("checkMissingMinimalProductFields| Results for product is", { product, result });
}
return result;
}
Checks a product object for missing or incorrectly typed minimal required fields. Returns an array of field names that are missing or have the wrong type.