Last active
August 29, 2015 14:22
-
-
Save chiquitinxx/b661f27c647c3cfe5d38 to your computer and use it in GitHub Desktop.
Rest API from client side with trait and jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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