-
Notifications
You must be signed in to change notification settings - Fork 0
utils
Module:
utils
Purpose: Core utility belt — date validation, XML parsing, JSON manipulation, array operations, and UUID generation/parsing.
- Dependencies
- Exports
-
Class:
date -
Class:
xml -
Class:
json- json.isValid(oJson)
- json.copy(oJson)
- json.replace(oJson, sOldValue, sNewValue, oEvaluate?)
- json.getValue(oJson, sPropertyPath)
- json.unique(oNestedArray)
- json.order(oJson, oKeyOrder)
- json.projection(oJson, oColumns, bHasAssociattion?)
- json.map(oJson, oMap)
- json.merge(oJson1, oJson2)
- json.flat(oJson, sFlattenedProperty)
- json.stripUndefined(oSourceJson)
-
Class:
array- array.add(oArray, oItem)
- array.topN(oSortedArray, iTop)
- array.flat(oArray, sFlattenedProperty)
- array.unique(oArray)
- array.order(oArray, oOrder)
- array.projection(oArray, oColumns, bHasAssociattion?)
- array.map(oArray, oMap)
- array.sort(oArray, oOrderBy)
- array.filter(oArray, oFilterCondition)
- array.hasElement(oArray, oElement)
- array.toArray(oArray)
- array.toDisArray(oArray)
- array.toInterleavedArray(oArray, oElement)
- array.toArrayProjection(oArray, sProjectionFieldName)
- array.findProperty(oArray, sProjectionFieldName)
- array.toGroupByPropertyName(oArray, sPropertyName)
- array.toGroupByPropertyList(oArray, oPropertyList)
-
Class:
UUID
| Package | Purpose |
|---|---|
xml2js |
XML string parsing and validation |
uuid |
UUID format validation |
lodash |
Deep merge, orderBy, uniqWith, and isEqual |
module.exports = { date, xml, json, array, UUID };Date-related validation helpers. All methods are static.
| Parameter | Type | Description |
|---|---|---|
sDate |
string |
Date string to validate |
| Returns | Promise<boolean> |
true if valid date |
Behavior: Parses the string via new Date() and verifies the result is a real Date (not NaN). Logs errors via the framework logger.
await date.isValid("2026-04-20"); // true
await date.isValid("not-a-date"); // falseXML parsing and validation helpers. All methods are static.
| Parameter | Type | Description |
|---|---|---|
oXML |
string|object |
XML content to validate |
| Returns | Promise<boolean> |
true if well-formed XML |
Behavior: Uses xml2js.Parser.parseStringPromise to attempt parsing. Logs the parsed result on success and errors on failure.
await xml.isValid("<root><item>val</item></root>"); // true
await xml.isValid("not xml"); // falseComprehensive JSON/object manipulation utilities. All methods are static.
Checks if the input can be parsed as JSON via JSON.parse.
| Parameter | Type | Returns |
|---|---|---|
oJson |
string|object |
boolean |
Creates a deep clone using structuredClone. Falls back to returning the original reference if the input isn't valid JSON.
| Parameter | Type | Returns |
|---|---|---|
oJson |
object |
object |
Recursively walks objects and arrays, replacing all string occurrences of sOldValue with sNewValue. Mutates the input in place.
| Parameter | Type | Default | Description |
|---|---|---|---|
oJson |
object|Array |
— | Target structure |
sOldValue |
string |
— | Substring to find |
sNewValue |
string |
— | Replacement substring |
oEvaluate |
object |
undefined |
Optional context; when set, resolved string is evaluated as a property path via json.getValue
|
const data = { msg: "Hello {{name}}", nested: { msg: "Hi {{name}}" } };
json.replace(data, "{{name}}", "World");
// data → { msg: "Hello World", nested: { msg: "Hi World" } }Resolves a dot-separated property path to its value.
| Parameter | Type | Returns |
|---|---|---|
oJson |
object |
* |
sPropertyPath |
string |
Value or undefined
|
json.getValue({ a: { b: { c: 42 } } }, "a.b.c"); // 42
json.getValue({ a: 1 }, "x.y"); // undefinedFlattens a nested array and removes duplicates using JSON serialization for deep equality.
| Parameter | Type | Returns |
|---|---|---|
oNestedArray |
any[] |
any[] |
Returns a new object with keys reordered: specified keys first, then the rest.
| Parameter | Type | Returns |
|---|---|---|
oJson |
object |
object |
oKeyOrder |
string[] |
— |
json.order({ c: 3, a: 1, b: 2 }, ["a", "b"]); // { a: 1, b: 2, c: 3 }Filters an object to include only the specified properties.
| Parameter | Type | Default | Description |
|---|---|---|---|
oJson |
object |
— | Source object |
oColumns |
string[] |
— | Property names to keep |
bHasAssociattion |
boolean |
false |
Also include keys prefixed with column names |
Creates a new object by mapping source properties via a definition object.
| Parameter | Type | Description |
|---|---|---|
oJson |
object |
Source data |
oMap |
object |
{ targetKey: "source.path" } mapping definition |
json.map({ user: { name: "John" } }, { fullName: "user.name" }); // { fullName: "John" }Deep-merges two objects using Lodash _.merge. Returns {} if either argument is not an object.
Promotes a nested property's contents to the top level of the object.
json.flat({ id: 1, details: { name: "A", desc: "B" } }, "details");
// { id: 1, name: "A", desc: "B" }Removes properties where the value is undefined, null, or an empty string.
Array operations with automatic fallback to the json class for single-object inputs. All methods are static.
Appends item(s) to an array. Accepts single values or arrays.
Returns the first iTop elements via Array.slice.
Flattens a nested property for each element. Delegates to json.flat for single objects.
Deduplicates using Lodash _.uniqWith with _.isEqual for deep comparison.
Reorders keys for every object in the array per the specified key order.
Projects each element to only contain the listed columns.
Applies a property mapping to every element in the array.
Multi-column sort with type coercion support.
oOrderBy entry |
Property | Type | Description |
|---|---|---|---|
ref |
string[] |
Required | Column path |
sort |
'asc'|'desc' |
Optional (default 'asc') |
Sort direction |
function |
'Date'|'parseFloat' |
Optional | Value coercion |
array.sort(items, [
{ ref: ["date"], sort: "desc", function: "Date" },
{ ref: ["price"], sort: "asc", function: "parseFloat" }
]);Filters array elements based on a list of filter conditions (AND logic).
FilterCondition:
| Property | Type | Description |
|---|---|---|
name |
string |
Property name to filter by |
op |
'='|'!='|'>'|'<'|'>='|'<=' |
Comparison operator |
value |
string|number|boolean |
Value to compare against |
array.filter(employees, [
{ name: "age", op: ">=", value: 30 },
{ name: "dept", op: "=", value: "Engineering" }
]);Returns true if the element is found (strict === via Array.includes).
Normalizes any value into an array: undefined → [], non-array → [value], array → as-is.
Unwraps a single-element array to its value. Multi-element arrays pass through.
Inserts a separator element between consecutive items.
array.toInterleavedArray(["a", "b", "c"], "|"); // ["a", ["|"], "b", ["|"], "c"]Extracts a single field from each element into a flat array.
array.toArrayProjection([{ id: 1 }, { id: 2 }], "id"); // [1, 2]Recursively searches nested structures for all values of a named property. Returns a deduplicated array.
Groups elements into an object keyed by a single property's value.
array.toGroupByPropertyName(
[{ type: "A", v: 1 }, { type: "B", v: 2 }, { type: "A", v: 3 }],
"type"
);
// { A: [{...}, {...}], B: [{...}] }Groups elements by a composite key derived from multiple properties (joined with ##). Supports dot-notation paths and recursive deep property lookup.
array.toGroupByPropertyList(data, ["region", "details.category"]);
// { "US##Electronics": [...], "EU##Clothing": [...] }Singleton class for deterministic UUID generation and parsing based on a fixed field configuration. Encodes/decodes structured business data into RFC-4122-compliant UUIDs.
const uuidHelper = new UUID();Creates a singleton instance. Subsequent new UUID() calls return the same instance.
Encodes structured JSON data into a deterministic UUID.
| Parameter | Type | Description |
|---|---|---|
oJsonData |
object |
Object |
| Returns | string |
A valid UUID string |
| Throws | Error |
If any field has an invalid format or the generated UUID fails validation |
const uid = new UUID();
uid.converse({
ABC: "AB12",
MNO: "I1234567",
XYZ: "000000012345"
});
// Returns a valid UUID string e.g., "c0656612-2e12-4345-8670-000000012345"Decodes a previously generated UUID back into its original structured data.
| Parameter | Type | Description |
|---|---|---|
sUUID |
string |
A UUID previously created by converse
|
| Returns | object |
{ ABC, MNO, XYZ } or {} if invalid |
const uid = new UUID();
uid.inverse("c0656612-2e12-4345-8670-000000012345");
// { ABC: "AB12", MNO: "I1234567", XYZ: "000000012345" }const { date, xml, json, array, UUID } = require('@cap-ts/esi').utils;
// Validate & transform
const valid = await date.isValid("2026-04-20");
const items = [{ id: 1, name: "A" }, { id: 2, name: "B" }];
// Project, sort, filter
const names = array.toArrayProjection(items, "name"); // ["A", "B"]
const sorted = array.sort(items, [{ ref: ["id"], sort: "desc" }]);
const filtered = array.filter(items, [{ name: "id", op: ">", value: 1 }]);
// Group & merge
const grouped = array.toGroupByPropertyName(items, "name");
const merged = json.merge({ a: 1 }, { b: 2 }); // { a: 1, b: 2 }
// UUID round-trip
const uid = new UUID();
const uuidStr = uid.converse({ ABC: "AB12", MNO: "I1234567", XYZ: "000000012345" });
const original = uid.inverse(uuidStr);