@nerdware/ddb-single-table
Version:
A schema-based DynamoDB modeling tool, high-level API, and type-generator built to supercharge single-table designs!⚡
27 lines (26 loc) • 1.29 kB
JavaScript
import { isDate } from "@nerdware/ts-type-safety-utils";
import { isValidIso8601DatetimeString, getRecursiveValueConverter, } from "../utils/index.js";
const DATE_CONVERSION_FNS = {
/** Recursively converts JS `Date` objects and datetime-formatted strings into ISO-8601 strings. */
toDB: getRecursiveValueConverter((value) => isDate(value)
? value.toISOString()
: isValidIso8601DatetimeString(value)
? new Date(value).toISOString()
: undefined),
/** Recursively converts datetime-formatted strings into JS `Date` objects. */
fromDB: getRecursiveValueConverter((value) => isValidIso8601DatetimeString(value) ? new Date(value) : undefined),
};
/**
* Converts all JS `Date` objects contained within `item` into ISO-8601 strings, and vice versa.
*/
export const convertJsDates = (ioDirection, item) => {
// Get the appropriate conversion function based on the I/O direction
const typeConverterFn = DATE_CONVERSION_FNS[ioDirection];
// To avoid mutating the original item, create a new object to return
const itemToReturn = { ...item };
// Iterate over the item's keys
for (const itemKey of Object.keys(item)) {
itemToReturn[itemKey] = typeConverterFn(item[itemKey]);
}
return itemToReturn;
};