@avonjs/avonjs
Version:
A fluent Node.js API generator.
96 lines (95 loc) • 3.25 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const change_case_all_1 = require("change-case-all");
const collect_js_1 = __importDefault(require("collect.js"));
exports.default = (Parent) => {
class HasAttributes extends Parent {
/**
* The model's attributes.
*/
attributes = {};
/**
* Get hidden attributes on the serialization.
*/
hidden = [];
/**
* Get visible attributes on the serialization.
*/
visible = [];
/**
* Set value for the given key.
*/
setAttributeValue(key, value) {
const mutator = `set${(0, change_case_all_1.pascalCase)(key)}Attribute`;
// Check if the mutator method exists and is a function
if (typeof this[mutator] === 'function') {
// Use the correct function signature for the mutator
const mutatorFn = this[mutator];
mutatorFn.apply(this, [value]);
}
else {
// Fallback to setting the attribute directly if no mutator exists
this.attributes[key] = value;
}
return this;
}
/**
* Get value for the given key.
*/
getAttributeValue(key) {
const value = this.attributes[key];
// Dynamically construct the mutator method name
const mutator = `get${(0, change_case_all_1.pascalCase)(key)}Attribute`;
// Check if the mutator method exists and is a function
if (typeof this[mutator] === 'function') {
// Use correct typing for the mutator method instead of Function type
const mutatorFn = this[mutator];
return mutatorFn.apply(this, [value]);
}
// Return the attribute value directly if no mutator method exists
return value;
}
/**
* Make an attribute serializable.
*/
makeVisible(attribute) {
this.visible.push(attribute);
return this;
}
/**
* Hidden an attribute from serializable.
*/
makeHidden(attribute) {
this.hidden.push(attribute);
return this;
}
/**
* Get all mutated values.
*/
getAttributes() {
return this.attributes;
}
/**
* Get all mutated values.
*/
getAttributesValue() {
return (0, collect_js_1.default)(this.getAttributes())
.map((value, key) => this.getAttributeValue(key))
.all();
}
/**
* Get all serializable attributes.
*/
toSerializable() {
const attributes = (0, collect_js_1.default)(this.attributes).except(this.hidden);
if (this.visible.length > 0) {
return attributes.only(this.visible).all();
}
return attributes.all();
}
}
return HasAttributes;
};