Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
BookController that uses RxJava and RxGORM for MongoDB
package rxgorm.demo
import grails.artefact.Controller
import grails.rx.web.Rx
import grails.validation.ValidationException
import groovy.transform.CompileStatic
import static org.springframework.http.HttpStatus.*
import static grails.rx.web.Rx.*
import static rx.Observable.*
@CompileStatic
class BookController implements Controller {
static responseFormats = ['json', 'xml']
static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
zip( Book.list(params), Book.count() ) { List bookList, Number count ->
render view:"index", model:[bookList: bookList, bookCount: count]
}
}
def show() {
Book.get((Serializable)params.id)
}
def save() {
Rx.bindData(new Book(), request)
.switchMap { Book book ->
if(book.hasErrors()) {
just(
respond( book.errors, view:'create')
)
}
else {
book.save(flush:true)
.map { Book savedBook ->
respond savedBook, [status: CREATED, view:"show"]
}
.onErrorReturn { Throwable e ->
if(e instanceof ValidationException) {
respond e.errors, view:'create'
}
else {
log.error("Error saving entity: $e.message", e)
return INTERNAL_SERVER_ERROR
}
}
}
}
}
def update() {
def request = this.request
Book.get((Serializable)params.id)
.switchMap { Book book ->
Rx.bindData( book, request )
.switchMap { Book updatedBook ->
!updatedBook.hasErrors()? updatedBook.save() : updatedBook
}
}
.map { Book book ->
if(book.hasErrors()) {
respond book.errors, view:'edit'
}
else {
respond book, [status: OK, view:"show"]
}
}
.switchIfEmpty(
just( Rx.render(status: NOT_FOUND) )
)
.onErrorReturn { Throwable e ->
if(e instanceof ValidationException) {
respond e.errors, view:'edit'
}
else {
log.error("Error saving entity: $e.message", e)
return INTERNAL_SERVER_ERROR
}
}
}
def delete() {
Book.get((Serializable)params.id)
.switchMap { Book book ->
book.delete()
}
.map {
render status: NO_CONTENT
}
}
}
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.