Utility functions for checking if an record has all required properties

Jens Pelzetter 2020-07-23 20:25:23 +02:00
parent 58fb0937d2
commit af3c2b3da4
1 changed files with 57 additions and 6 deletions

View File

@ -88,3 +88,54 @@ export function buildIsomorpicApiClient(
const nodeClient: LibreCcmApiClient = buildNodeApiClient(baseUrl, jwt);
return new IsomorphicClientImpl(fetchClient, nodeClient);
}
/**
* An utility function for checking if an record has specific properties.
*
* @param record The record to check.
* @param properties The required properties.
*
* @return `true` if all properties are found in the record, `false` otherwise.
*/
export function hasProperties(
record: Record<string, unknown>,
properties: string[]
): boolean {
const keys = Object.keys(record);
return properties.every((property) => keys.includes(property));
}
/**
* An utility function for checking if an record has specific properties. If
* one of the properties is not found, the function will throw an error.
*
* @param record The record to check.
* @param properties The required properties.
*/
export function assertProperties(
record: Record<string, unknown>,
properties: string[]
): void {
const missing = findMissingProperties(record, properties);
if (missing.length > 0) {
throw `record is missing the following required properties:
${missing.join(",")}`;
}
}
/**
* An utility function which checks which of the given properties the provided
* record is missing.
*
* @param record The record to check.
* @param properties The requird properties.
*
* @return An array with all missing properties.
*/
export function findMissingProperties(
record: Record<string, unknown>,
properties: string[]
): string[] {
const keys = Object.keys(record);
return properties.filter((property) => !keys.includes(property));
}