Skip to content
This repository has been archived by the owner on Aug 24, 2023. It is now read-only.

gServ HATEOAS

Lee Collins edited this page Aug 2, 2016 · 6 revisions

In accordance with one of the constraints of REST, HATEOAS, gServ provides facilities for defining and producing links related to a particular resource.

Below is the 'Thing' resource - it defines a "links" function that returns an array of links.

def gserv = ...
def service = ...
gserv.resource("thing"){

    links{ id ->
        [
            [rel:"self", href:"/thing/$id", method: "GET" ],
            [rel:"edit", href:"/thing/$id", method: "PUT" ],
            [rel:"delete", href:"/thing/$id", method: "DELETE" ]
        ]

    }

    put("/:id"){ Thing thing, id ->
        def thing = service.updateThing(thing)
        location "/thing/$id"
        writeJson [thing : thing, links : links(id) ]
    } 
    
    delete("/:id"){ id ->
        def ok = service.deleteThing(id)
        writeJson [success : ok ]
    } 
    
    get("/:id"){ id ->
        def thing = service.getThing(id)
        writeJson [ thing:thing, links:links(id) ]
    } 
    
}

The "links" function is user-defined and can have multiple arguments - these arguments and any other values can be used to create the links.

def gserv = ...
def service = ...
gserv.resource("thing"){

    links{user, id ->
        def l = [
            [rel:"self", href:"/thing/$id", method: "GET" ],
        ]

        service.hasUpdateAccess(user) ? l + [
                [rel:"edit", href:"/thing/$id", method: "PUT" ],
                [rel:"delete", href:"/thing/$id", method: "DELETE" ]
            ] : l
        
    }

    put("/:id"){ Thing thing, id ->
        def thing = service.updateThing(thing)
        location "/thing/$id"
        writeJson [ thing : thing, 
                    links : links(requestContext.principal.username, id) ]
    } 
    
    delete("/:id"){ id ->
        def ok = service.deleteThing(id)
        writeJson [success : ok ]
    }
    
    get("/:id"){ id ->
        def thing = service.getThing(id)
        writeJson [ thing:thing, 
                    links:links(requestContext.principal.username, id) ]
    } 
    
}

In this example, we use the username to determine which links the client will receive.

Clone this wiki locally