Search code examples
jsonrestswift2siesta-swift

Siesta: Child resources


I am having difficulties understanding how does Siesta figure out the child of a resource. For example I have the following events resource:

JSON returned by "/events"

{
    "success": 1,
    "events": [
        {
            "id": 1,
            "type": "meeting", 
            "eventDate": "2015-08-20", 
            "notes": "fadsfasfa", 
            "title": null
        },{
            "id": 2, 
            "type": "game", 
            "eventDate": "2015-08-31", 
            "notes": "fdsafdf", 
            "title": null
        }
    ]
}

Sadly, calling "/events/1" for example, does not return the event with id=2. Is there a way to tell Siesta which event has the id=2?


Solution

  • Suppose you have:

    let events = myService.resource("/events")
    

    Then you can navigate from the /events resource to the /events/2 resource like this:

    let event = events.child("2")
    

    That will give you the same object as if you had asked for myService.resource("/events/2").

    To extract that 2 from the JSON, use normal Swift JSON parsing techniques. (Siesta doesn’t apply any special inspection or interpretation to the JSON once it’s parsed.) I recommend using the SwiftyJSON library for easier JSON traversal. For example, it lets you do something like this to extract those event IDs and get the child resources:

    let allEventResources =
        JSON(events.jsonDict)["events"]
            .arrayValue
            .flatMap { $0["id"].string }
            .map(event.child)