Search code examples
grailsclosuresgrails-controllerhttpbuilder

Return value from HTTPResponse closure Grails HTTPBuilder to outer method


I have some code like this

def lookupTickets() {
    User currentUser = webAuthService.currentUser()
    def http = new HTTPBuilder(zdURL)
    http.auth.basic("${zdUser}/token", zdApiKey)
    http.get(path: "/api/v2/users/search.json", 
             query: [query: currentUser.emailAddress], 
             requestContentType: ContentType.JSON, { resp, json ->
              println "Response status: ${resp.statusLine}"
                  def zenDeskUserId = json?.users[0]?.id
    })
    return MYRESULT
}

The line def zenDeskUserId = json?.users[0]?.id gives me the result I am looking to return to the browser.

How can I return this value in the outer method when it is only in scope from within the inner closure?


Solution

  • Do you think this will not work?

    def lookupTickets() {
        def zenDeskUserId
    
        User currentUser = webAuthService.currentUser()
        def http = new HTTPBuilder(zdURL)
        http.auth.basic("${zdUser}/token", zdApiKey)
        http.get(path: "/api/v2/users/search.json", 
                 query: [query: currentUser.emailAddress], 
                 requestContentType: ContentType.JSON, { resp, json ->
    
                     println "Response status: ${resp.statusLine}"
                     zenDeskUserId = json?.users[0]?.id
        })
        return zenDeskUserId
    }