UNPKG

@jesuferanmi/resource-transformer

Version:

Laravel-style API resources for NestJS apps

47 lines (46 loc) 1.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BaseResource = void 0; class BaseResource { constructor(resource) { this.resource = resource; this.additionalData = {}; } /** * Convert the resource to JSON, merging additional data. */ toJSON() { return { ...this.toArray(), ...this.additionalData, }; } /** * Conditionally include a value if condition is true. */ when(condition, value, defaultValue = undefined) { return condition ? value : defaultValue; } /** * Include related resource only if relation is loaded (exists). * Handles both single object and array of objects. */ whenLoaded(relation, ResourceClass) { const related = this.resource?.[relation]; if (related === undefined || related === null) { return null; } if (Array.isArray(related)) { return related.map(item => new ResourceClass(item).toArray()); } return new ResourceClass(related).toArray(); } /** * Add extra data to merge into final output. */ additional(data) { this.additionalData = { ...this.additionalData, ...data }; return this; } } exports.BaseResource = BaseResource;