Created
November 17, 2024 19:15
-
-
Save galvao/2a9bccb6dc4dfa54763802b5c44034a7 to your computer and use it in GitHub Desktop.
A simple Hydrator in JS (ES6)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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