@rashedmakkouk/dev-utils
Version:
Utility library.
31 lines (30 loc) • 1.17 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/** Utilities */
const isArray_1 = __importDefault(require("lodash/isArray"));
const normalizr_1 = require("normalizr");
/**
* Normalizes payload by defined object attribute.
*
* Options:
* options['idAttribute'] = 'id' // Object property to normalize based on.
*
* @param key - Entity type to move records under (e.g. posts).
* @param payload - Data object or object array to manipulate.
* @param options - Set custom column to use (e.g. idAttribute).
*
* @returns Result object:
* - Object.entities: Normalized records by 'key'.
* - Object.result: Array or single value of data 'idAttributes'.
*/
function normalize(key, payload, options = {}) {
if (!options?.idAttribute) {
options.idAttribute = 'id';
}
const resultsSchema = new normalizr_1.schema.Entity(key, {}, options);
return (0, normalizr_1.normalize)(payload, !(0, isArray_1.default)(payload) ? resultsSchema : [resultsSchema]);
}
exports.default = normalize;