Skip to content
This repository has been archived by the owner on Sep 12, 2019. It is now read-only.

Make all classes serializable to JSON objects #10

Open
nathancarter opened this issue Mar 31, 2017 · 3 comments
Open

Make all classes serializable to JSON objects #10

nathancarter opened this issue Mar 31, 2017 · 3 comments

Comments

@nathancarter
Copy link
Contributor

Use case: Fetch a large group of matches and want to store them somewhere for later analysis offline. Want to be able to convert a match (with all included player, roster, participant, and asset objects) to JSON that can be written to a file, then deserialized back into the same hierarchy of Match/Player/Roster/Participant/Asset objects later. For bonus points, include telemetry data.

I include here some CoffeeScript code that seems to work, but native support is better than my hacking, of course.

vgObjectToJSON = ( object ) ->
    result = data : object.data
    for own name, ctor of vg.models
        if name isnt 'Base' and object instanceof ctor
            result.ctor = name
    for relationship in object.relationships ? [ ]
        type = relationship.type
        subobj = object[type]
        if subobj instanceof Array
            result[type] = ( vgObjectToJSON s for s in subobj )
        else
            result[type] = vgObjectToJSON subobj
    # in case I've fetched and embedded telemetry earlier:
    result.telemetry = object.telemetry
    result
vgObjectFromJSON = ( json ) ->
    if typeof json is 'string' then json = JSON.parse json
    ctor = vg.models[json.ctor]
    delete json.ctor
    telemetry = json.telemetry
    delete json.telemetry
    result = new ctor json.data
    for relationship in result.relationships ? [ ]
        type = relationship.type
        subobj = json[type]
        if subobj instanceof Array
            result[type] = ( vgObjectFromJSON s for s in subobj )
        else
            result[type] = vgObjectFromJSON subobj
    result.telemetry = telemetry
    result
@nathancarter
Copy link
Contributor Author

if you're not a coffeescript guy, you can just paste that code into the coffeescript website and it will create JS for you.

@PierreAndreis
Copy link
Contributor

Is there any specific reason we are creating functions instead of running the functions at request time and return as string?

@nathancarter
Copy link
Contributor Author

Hi, Pierre. Do you mean in the sample CoffeeScript code above? Are you referring to the part about storing the name of the constructor?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants