Created
October 6, 2023 23:13
-
-
Save felds/5bcb07ca265b49e925081562da473c3e to your computer and use it in GitHub Desktop.
Serializing/reviving objects in TS
This file contains hidden or 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
class Point { | |
constructor( | |
public x: number, | |
public y: number, | |
) {} | |
serialize(): any { | |
return {__type: this.constructor.name, x: this.x, y: this.y} | |
} | |
toString() { | |
return `I'm a point: ${this.x}, ${this.y}` | |
} | |
} | |
const serializableTypes: Record<string, Function> = { | |
"Point": Point, | |
} | |
// Create sample points | |
const p1 = new Point(1, 2) | |
const p2 = new Point(3, 4) | |
const payload = {p1, p2} | |
console.log("Payload:", payload) | |
// Serialize | |
const serialized = JSON.stringify(payload, (k, v) => { | |
if (typeof v === "object" && "serialize" in v) { | |
return v.serialize() | |
} | |
return v | |
}) | |
console.log("Serialized:", serialized) | |
// Revive | |
const parsed = JSON.parse(serialized, (k, v) => { | |
if (typeof v === "object" && "__type" in v && v.__type in serializableTypes) { | |
const type = serializableTypes[v.__type] | |
delete v.__type | |
return Object.setPrototypeOf(v, type.prototype) | |
} | |
return v | |
}) | |
console.log("Parsed:", parsed) | |
console.log(`Proof that the object revived correctly:\n\t${parsed.p1}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment