Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rest API from client side with trait and jQuery
import org.grooscript.asts.GsNative
trait JQueryRestApi {
static String url
static String resource
void add(Closure onSuccess, Closure onError) {
ajaxCall('POST', "${url}/${resource}", onSuccess, onError)
}
void one(Long id, Closure onSuccess, Closure onError) {
ajaxCall('GET', "${url}/${resource}/${id}", onSuccess, onError)
}
void all(Closure onSuccess, Closure onError) {
ajaxCall('GET', "${url}/${resource}", onSuccess, onError)
}
@GsNative
void ajaxCall(String type, String url, Closure onSuccess, Closure onError) {/*
jQuery.ajax({
type: type,
url: url,
data: (type == 'POST' ? JSON.stringify(gs.toJavascript($self)) : null),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status, jqXHR) {
onSuccess(data);
},
error: function (jqXHR, status) {
onError(jqXHR, status);
}
});
*/}
}
class Author implements JQueryRestApi {
Long id
String name
String city
String image
int age
String toString() {
"id: ${id} name: ${name}"
}
}
def onError = { jqXHR, status ->
println "Error jqXHR: ${jqXHR} status: ${status}"
}
Author.url = 'http://localhost:3000'
Author.resource ='authors'
def api = new Author()
api.one(1, { data ->
def author = new Author(data)
println "Success get one: ${author}"
}, onError)
api.all({ authors ->
println "Success get all: ${authors.size()}"
authors.findAll { it.image }.each {
$('body').append("<img src='${it.image}'/>")
}
}, onError)
def newAuthor = new Author(name: "Jorge Franco", city: "Madrid / Sevilla", image: "img/logo.png")
newAuthor.add({ data ->
println "Success add: ${data.id}"
api.all({ authors ->
println "Success after insert ${data.name}: ${authors.size()}"
}, onError)
}, onError)
/* Console output:
XHR finished loading: GET "http://localhost:3000/authors/1".
Success one: id: 1 name: Ole
XHR finished loading: POST "http://localhost:3000/authors".
Success add: 4
XHR finished loading: GET "http://localhost:3000/authors".
Success all: 4
XHR finished loading: GET "http://localhost:3000/authors".
Success after insert Jorge Franco: 4
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.