seripap / vainglory

(*DEPRECATED*: The API no longer exists, so this will no longer work) A Javascript API Client wrapper for Vainglory
MIT License
29 stars 7 forks source link

Make all classes serializable to JSON objects #10

Open nathancarter opened 7 years ago

nathancarter commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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

nathancarter commented 7 years ago

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