# new BaseEntity(data, entityOptionsopt)
Construct entity instance from arbitrary data, automatically filtering hidden fields.
Hidden fields (e.g., passwords, tokens) are removed unless explicitly requested via entityOptions.includeHiddenFields = true. This ensures sensitive data is not accidentally exposed in API responses.
Parameters:
| Name | Type | Attributes | Default | Description |
|---|---|---|---|---|
data |
Object
|
Raw data object (typically from database or API) |
||
entityOptions |
Object
|
<optional> |
{} | Entity construction options |
includeHiddenFields |
boolean
|
<optional> |
false | If true, retain hidden fields |
Example
// Direct usage (rare, usually use createEntityFromModel)
class UserEntity extends BaseEntity {
static hiddenFields = ['password', 'resetToken'];
}
const user = new UserEntity({ id: 1, email: 'user@example.com', password: 'secret' });
console.log(user.password); // undefined (filtered by hiddenFields)
Methods
# cloneWith(updates) → {this}
Create a new entity instance by cloning current data and applying updates.
Since entities are immutable (frozen), this method provides a way to create a modified version without mutating the original. Useful for applying partial updates while preserving immutability.
Parameters:
| Name | Type | Description |
|---|---|---|
updates |
Object
|
Fields to add/override in the cloned instance |
New entity instance with updates applied
this
Example
const icon1 = new IconEntity({ id: 1, name: 'home', isActive: true });
const icon2 = icon1.cloneWith({ name: 'home-alt' });
console.log(icon1.name); // 'home' (unchanged)
console.log(icon2.name); // 'home-alt'
console.log(icon2.id); // 1 (copied from original)
console.log(icon1 !== icon2); // true (different instances)
# toJSON() → {Object}
Serialize entity to plain JSON object, recursively converting nested entities.
This method is automatically called by JSON.stringify() and ensures all nested entities (arrays or single objects) are also serialized properly. Essential for API responses where entities need to be converted to plain JSON.
Plain JavaScript object suitable for JSON serialization
Object
Examples
const icon = new IconEntity({
id: 1,
name: 'home',
set: new SetEntity({ id: 10, name: 'Material' }),
images: [
new ImageEntity({ id: 100, url: '/img1.png' }),
new ImageEntity({ id: 101, url: '/img2.png' })
]
});
const json = icon.toJSON();
// All nested entities converted to plain objects
console.log(json.set.name); // 'Material'
console.log(json.images[0].url); // '/img1.png'
// Automatic usage with JSON.stringify
const icon = new IconEntity({ id: 1, name: 'home' });
const str = JSON.stringify(icon);
console.log(str); // '{"id":1,"name":"home"}'