Skip to content

Instantly share code, notes, and snippets.

@galvao
Created November 17, 2024 19:15
Show Gist options
  • Save galvao/2a9bccb6dc4dfa54763802b5c44034a7 to your computer and use it in GitHub Desktop.
Save galvao/2a9bccb6dc4dfa54763802b5c44034a7 to your computer and use it in GitHub Desktop.
A simple Hydrator in JS (ES6)
"use strict";
class Hydrator
{
#immutable;
fromEntity;
toEntity;
constructor (fromEntity, toEntity, lazy = true, immutable = true)
{
this.fromEntity = fromEntity;
this.toEntity = toEntity;
this.immutable = !immutable;
if (lazy) {
this.toEntity = this.hydrate();
}
}
hydrate()
{
for (const [name, value] of Object.entries(this.fromEntity)) {
if (Object.hasOwn(this.toEntity, name)) {
Object.defineProperty(this.toEntity, name, {
value: value,
writable: this.immutable
});
}
}
return this.toEntity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment