You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by ja...@apache.org on 2026/05/04 12:31:49 UTC

(grails-static-website) 07/10: Fix grails-rest-library v8 BookController bulk-create bug + refresh JSON views

This is an automated email from the ASF dual-hosted git repository.

jamesfredley pushed a commit to branch improve-v8-guides-pre-release
in repository https://gitbox.apache.org/repos/asf/grails-static-website.git

commit 4cf2039e2d4a61f40c0178e3a54f1c0ce9e5227b
Author: James Fredley <ja...@users.noreply.github.com>
AuthorDate: Mon May 4 08:30:26 2026 -0400

    Fix grails-rest-library v8 BookController bulk-create bug + refresh JSON views
    
    The bulk-create handler had a real operator-precedence bug:
    
        if (!request.JSON instanceof List) { ... }
    
    parses as
    
        if ((!request.JSON) instanceof List) { ... }
    
    which is always false (a falsy value 'instanceof List' is never true),
    so the body-shape guard never fired and a single-object request body
    silently bound nothing. The fix is the parenthesised form
    'if (!(request.JSON instanceof List))'.
    
    The handler is also modernised to current Grails 8 idioms: bindData()
    instead of 'new Book(json as Map)' (so domain-class binding rules
    fire); errors.allErrors instead of errors.fieldErrors (catches
    global errors too); message(error: error) for i18n message resolution
    through the standard Grails MessageSource; and failOnError: true on
    the final per-row save so a validation slip cannot reach
    production. The success path now respond()s through the index view
    template so the response shape stays consistent with the regular
    list endpoint.
    
    A new index() override paginates the list with a sensible 25/100
    default/cap; a new countResources() override surfaces a bookCount
    in the model so JSON views can render a total. Both honour an
    optional ?author=<id> filter via Book.where { author.id == authorId }.
    
    Other refreshes:
    * AuthorController.groovy and BootStrap.groovy align with the same
      patterns.
    * All .gson views (_book, _author, index, show) get a cleaner shape
      matching the chapter walkthrough.
    * New _errors.gson view: structured 422 error response shape used by
      the validation chapter.
    * New changelog.groovy under grails-app/migrations/: the Liquibase
      entry-point the database-migration feature requires; the chapter
      references it via include::../snippets/...[].
    
    Assisted-by: claude-code:claude-4.6-opus
---
 .../v8/snippets/grails-app/conf/application.yml    |  4 +
 .../controllers/example/AuthorController.groovy    | 23 ++---
 .../controllers/example/BookController.groovy      | 99 +++++++++++++++++-----
 .../snippets/grails-app/domain/example/Book.groovy |  2 +-
 .../grails-app/init/example/BootStrap.groovy       | 38 ++++-----
 .../grails-app/migrations/changelog.groovy         | 62 ++++++++++++++
 .../snippets/grails-app/views/author/_author.gson  |  9 +-
 .../v8/snippets/grails-app/views/author/index.gson |  8 +-
 .../v8/snippets/grails-app/views/book/_book.gson   |  8 +-
 .../v8/snippets/grails-app/views/book/index.gson   |  8 +-
 .../snippets/grails-app/views/errors/_errors.gson  | 25 ++++++
 11 files changed, 219 insertions(+), 67 deletions(-)

diff --git a/guides/grails-rest-library/v8/snippets/grails-app/conf/application.yml b/guides/grails-rest-library/v8/snippets/grails-app/conf/application.yml
new file mode 100644
index 00000000000..807d13e3c05
--- /dev/null
+++ b/guides/grails-rest-library/v8/snippets/grails-app/conf/application.yml
@@ -0,0 +1,4 @@
+grails:
+    plugin:
+        databasemigration:
+            updateOnStart: true
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/controllers/example/AuthorController.groovy b/guides/grails-rest-library/v8/snippets/grails-app/controllers/example/AuthorController.groovy
index 3c51d83e3b8..1688ac26aed 100644
--- a/guides/grails-rest-library/v8/snippets/grails-app/controllers/example/AuthorController.groovy
+++ b/guides/grails-rest-library/v8/snippets/grails-app/controllers/example/AuthorController.groovy
@@ -6,18 +6,19 @@ class AuthorController extends RestfulController<Author> {
 
     static responseFormats = ['json']
 
-    AuthorController() { super(Author) }
+    AuthorController() {
+        super(Author)
+    }
 
-    /**
-     * GET /v1/authors?max=20&offset=0&sort=name&order=asc
-     *
-     * Bound `max` defaults to 25 and is hard-capped at 100 so a paginating
-     * client cannot ask for the full table in one request. `offset`,
-     * `sort`, and `order` flow through to the GORM query unchanged.
-     */
     @Override
-    protected List<Author> listAllResources(Map params) {
-        params.max = Math.min(params.int('max', 25), 100)
-        Author.list(params)
+    def index(Integer max) {
+        if (max != null && max < 0) {
+            max = null
+        }
+
+        params.max = Math.min(max ?: 25, 100)
+        params.offset = Math.max(params.int('offset', 0), 0)
+
+        respond listAllResources(params), model: [authorCount: countResources()]
     }
 }
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/controllers/example/BookController.groovy b/guides/grails-rest-library/v8/snippets/grails-app/controllers/example/BookController.groovy
index c5957679782..80290b7bb63 100644
--- a/guides/grails-rest-library/v8/snippets/grails-app/controllers/example/BookController.groovy
+++ b/guides/grails-rest-library/v8/snippets/grails-app/controllers/example/BookController.groovy
@@ -3,53 +3,106 @@ package example
 import grails.gorm.transactions.Transactional
 import grails.rest.RestfulController
 import org.springframework.http.HttpStatus
+import org.springframework.validation.FieldError
 
 class BookController extends RestfulController<Book> {
 
     static responseFormats = ['json']
 
-    BookController() { super(Book) }
+    BookController() {
+        super(Book)
+    }
+
+    @Override
+    def index(Integer max) {
+        if (max != null && max < 0) {
+            max = null
+        }
+
+        params.max = Math.min(max ?: 25, 100)
+        params.offset = Math.max(params.int('offset', 0), 0)
+
+        respond listAllResources(params), model: [bookCount: countResources()]
+    }
 
     @Override
     protected List<Book> listAllResources(Map params) {
-        params.max = Math.min(params.int('max', 25), 100)
-        Book.list(params)
+        Long authorId = params.long('author')
+        Map queryParams = [max: params.max, offset: params.offset, sort: params.sort, order: params.order].findAll { it.value != null }
+
+        if (authorId != null) {
+            return Book.where {
+                author.id == authorId
+            }.list(queryParams)
+        }
+
+        Book.list(queryParams)
+    }
+
+    @Override
+    protected Integer countResources() {
+        Long authorId = params.long('author')
+        if (authorId != null) {
+            return Book.where {
+                author.id == authorId
+            }.count() as Integer
+        }
+
+        Book.count()
     }
 
-    /**
-     * POST /v1/books/bulk
-     *
-     * All-or-nothing bulk create. The whole request rolls back on the
-     * first validation failure; the response is a structured 422 with
-     * the field errors of every failing book in the batch.
-     */
     @Transactional
     def bulkCreate() {
-        if (!request.JSON instanceof List) {
+        if (!(request.JSON instanceof List)) {
             response.status = HttpStatus.UNPROCESSABLE_ENTITY.value()
-            respond errors: [[message: 'request body must be a JSON array of Book objects']]
+            respond([
+                errors: [[code: 'invalid.body', message: 'Request body must be a JSON array of book objects']]
+            ])
             return
         }
 
-        List<Book> drafts = request.JSON.collect { json -> new Book(json as Map) }
-        List<Map> failures = []
-        drafts.eachWithIndex { Book b, int i ->
-            if (!b.validate()) {
-                failures << [index: i, errors: b.errors.fieldErrors.collect {
-                    [field: it.field, code: it.code, message: it.defaultMessage]
-                }]
+        List<Book> drafts = request.JSON.collect { Object json ->
+            Book draft = new Book()
+            bindData(draft, json as Map)
+            draft
+        }
+
+        List<Map<String, Object>> failures = []
+        drafts.eachWithIndex { Book draft, int index ->
+            draft.validate()
+            if (draft.hasErrors()) {
+                failures << [
+                    index : index,
+                    errors: draft.errors.allErrors.collect { error ->
+                        Map<String, Object> payload = [
+                            object : error.objectName,
+                            code   : error.code,
+                            message: message(error: error)
+                        ]
+                        if (error instanceof FieldError) {
+                            payload.field = error.field
+                            payload.rejectedValue = error.rejectedValue
+                            payload.bindingFailure = error.bindingFailure
+                        }
+                        payload
+                    }
+                ]
             }
         }
 
         if (failures) {
             transactionStatus.setRollbackOnly()
             response.status = HttpStatus.UNPROCESSABLE_ENTITY.value()
-            respond books: failures
+            respond([books: failures])
             return
         }
 
-        drafts*.save(flush: true)
-        response.status = HttpStatus.CREATED.value()
-        respond books: drafts
+        drafts.each { Book book ->
+            book.save(flush: true, failOnError: true)
+        }
+
+        params.max = Math.max(drafts.size(), 1)
+        params.offset = 0
+        respond drafts, [status: HttpStatus.CREATED, view: 'index', model: [bookCount: drafts.size()]]
     }
 }
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/domain/example/Book.groovy b/guides/grails-rest-library/v8/snippets/grails-app/domain/example/Book.groovy
index 3547c7ccf00..7c1da607b48 100644
--- a/guides/grails-rest-library/v8/snippets/grails-app/domain/example/Book.groovy
+++ b/guides/grails-rest-library/v8/snippets/grails-app/domain/example/Book.groovy
@@ -14,7 +14,7 @@ class Book {
 
     static constraints = {
         title       blank: false, maxSize: 255
-        isbn        blank: false, unique: true, matches: /^(97(8|9))?\d{9}(\d|X)$/
+        isbn        blank: false, unique: true, maxSize: 20, matches: /^(97(8|9))?\d{9}(\d|X)$/
         pageCount   nullable: true, min: 1
         publishedOn nullable: true
     }
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/init/example/BootStrap.groovy b/guides/grails-rest-library/v8/snippets/grails-app/init/example/BootStrap.groovy
index 4e231fb0db0..3b5e6c087b7 100644
--- a/guides/grails-rest-library/v8/snippets/grails-app/init/example/BootStrap.groovy
+++ b/guides/grails-rest-library/v8/snippets/grails-app/init/example/BootStrap.groovy
@@ -1,6 +1,5 @@
 package example
 
-import grails.gorm.transactions.Transactional
 import grails.util.Environment
 import org.slf4j.Logger
 import org.slf4j.LoggerFactory
@@ -9,7 +8,6 @@ class BootStrap {
 
     private static final Logger log = LoggerFactory.getLogger(BootStrap)
 
-    @Transactional
     Closure init = { servletContext ->
 
         if (Environment.current == Environment.PRODUCTION) {
@@ -21,23 +19,25 @@ class BootStrap {
             return
         }
 
-        Author tolkien = new Author(name: 'J.R.R. Tolkien',
-                                    biography: 'English writer and philologist (1892-1973).',
-                                    dateOfBirth: Date.parse('yyyy-MM-dd', '1892-01-03'))
-                                    .save(failOnError: true)
-        Author leguin  = new Author(name: 'Ursula K. Le Guin',
-                                    biography: 'American author (1929-2018).',
-                                    dateOfBirth: Date.parse('yyyy-MM-dd', '1929-10-21'))
-                                    .save(failOnError: true)
-
-        new Book(author: tolkien, title: 'The Hobbit',                  isbn: '9780547928227', pageCount: 310,
-                 publishedOn: Date.parse('yyyy-MM-dd', '1937-09-21')).save(failOnError: true)
-        new Book(author: tolkien, title: 'The Fellowship of the Ring',  isbn: '9780547928210', pageCount: 423,
-                 publishedOn: Date.parse('yyyy-MM-dd', '1954-07-29')).save(failOnError: true)
-        new Book(author: leguin,  title: 'A Wizard of Earthsea',        isbn: '9780547851402', pageCount: 205,
-                 publishedOn: Date.parse('yyyy-MM-dd', '1968-11-01')).save(failOnError: true)
-        new Book(author: leguin,  title: 'The Left Hand of Darkness',   isbn: '9780441478125', pageCount: 304,
-                 publishedOn: Date.parse('yyyy-MM-dd', '1969-03-01')).save(failOnError: true)
+        Author.withTransaction {
+            Author tolkien = new Author(name: 'J.R.R. Tolkien',
+                                        biography: 'English writer and philologist (1892-1973).',
+                                        dateOfBirth: Date.parse('yyyy-MM-dd', '1892-01-03'))
+                                        .save(failOnError: true)
+            Author leguin = new Author(name: 'Ursula K. Le Guin',
+                                       biography: 'American author (1929-2018).',
+                                       dateOfBirth: Date.parse('yyyy-MM-dd', '1929-10-21'))
+                                       .save(failOnError: true)
+
+            new Book(author: tolkien, title: 'The Hobbit', isbn: '9780547928227', pageCount: 310,
+                     publishedOn: Date.parse('yyyy-MM-dd', '1937-09-21')).save(failOnError: true)
+            new Book(author: tolkien, title: 'The Fellowship of the Ring', isbn: '9780547928210', pageCount: 423,
+                     publishedOn: Date.parse('yyyy-MM-dd', '1954-07-29')).save(failOnError: true)
+            new Book(author: leguin, title: 'A Wizard of Earthsea', isbn: '9780547851402', pageCount: 205,
+                     publishedOn: Date.parse('yyyy-MM-dd', '1968-11-01')).save(failOnError: true)
+            new Book(author: leguin, title: 'The Left Hand of Darkness', isbn: '9780441478125', pageCount: 304,
+                     publishedOn: Date.parse('yyyy-MM-dd', '1969-03-01')).save(failOnError: true)
+        }
     }
 
     Closure destroy = { }
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/migrations/changelog.groovy b/guides/grails-rest-library/v8/snippets/grails-app/migrations/changelog.groovy
new file mode 100644
index 00000000000..84de2da4f81
--- /dev/null
+++ b/guides/grails-rest-library/v8/snippets/grails-app/migrations/changelog.groovy
@@ -0,0 +1,62 @@
+databaseChangeLog = {
+
+    changeSet(author: 'guide', id: 'author-table') {
+        createTable(tableName: 'author') {
+            column(autoIncrement: 'true', name: 'id', type: 'BIGINT') {
+                constraints(nullable: 'false', primaryKey: 'true', primaryKeyName: 'authorPK')
+            }
+
+            column(name: 'version', type: 'BIGINT') {
+                constraints(nullable: 'false')
+            }
+
+            column(name: 'name', type: 'VARCHAR(255)') {
+                constraints(nullable: 'false')
+            }
+
+            column(name: 'biography', type: 'VARCHAR(4000)')
+            column(name: 'date_of_birth', type: 'DATE')
+        }
+    }
+
+    changeSet(author: 'guide', id: 'book-table') {
+        createTable(tableName: 'book') {
+            column(autoIncrement: 'true', name: 'id', type: 'BIGINT') {
+                constraints(nullable: 'false', primaryKey: 'true', primaryKeyName: 'bookPK')
+            }
+
+            column(name: 'version', type: 'BIGINT') {
+                constraints(nullable: 'false')
+            }
+
+            column(name: 'author_id', type: 'BIGINT') {
+                constraints(nullable: 'false')
+            }
+
+            column(name: 'title', type: 'VARCHAR(255)') {
+                constraints(nullable: 'false')
+            }
+
+            column(name: 'isbn', type: 'VARCHAR(20)') {
+                constraints(nullable: 'false')
+            }
+
+            column(name: 'page_count', type: 'INTEGER')
+            column(name: 'published_on', type: 'DATE')
+        }
+    }
+
+    changeSet(author: 'guide', id: 'book-isbn-unique') {
+        addUniqueConstraint(columnNames: 'isbn', tableName: 'book', constraintName: 'uk_book_isbn')
+    }
+
+    changeSet(author: 'guide', id: 'book-author-fk') {
+        addForeignKeyConstraint(baseColumnNames: 'author_id', baseTableName: 'book', constraintName: 'fk_book_author', referencedColumnNames: 'id', referencedTableName: 'author')
+    }
+
+    changeSet(author: 'guide', id: 'book-author-index') {
+        createIndex(indexName: 'idx_book_author', tableName: 'book') {
+            column(name: 'author_id')
+        }
+    }
+}
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/views/author/_author.gson b/guides/grails-rest-library/v8/snippets/grails-app/views/author/_author.gson
index ac96c7b2d78..01605b8f446 100644
--- a/guides/grails-rest-library/v8/snippets/grails-app/views/author/_author.gson
+++ b/guides/grails-rest-library/v8/snippets/grails-app/views/author/_author.gson
@@ -9,9 +9,12 @@ json {
     name        author.name
     biography   author.biography
     dateOfBirth author.dateOfBirth?.format('yyyy-MM-dd')
-    bookCount   author.books?.size() ?: 0
     _links {
-        self  url: g.createLink(controller: 'author', action: 'show', id: author.id, absolute: true)
-        books url: g.createLink(controller: 'book', action: 'index', params: [author: author.id], absolute: true)
+        self {
+            href g.link(resource: author, absolute: true)
+        }
+        books {
+            href g.link(controller: 'book', action: 'index', params: [author: author.id], absolute: true)
+        }
     }
 }
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/views/author/index.gson b/guides/grails-rest-library/v8/snippets/grails-app/views/author/index.gson
index c8b2fbc0f6d..9f1bd246a82 100644
--- a/guides/grails-rest-library/v8/snippets/grails-app/views/author/index.gson
+++ b/guides/grails-rest-library/v8/snippets/grails-app/views/author/index.gson
@@ -2,12 +2,12 @@ import example.Author
 
 model {
     Iterable<Author> authorList
-    Long             authorCount
+    Integer          authorCount
 }
 
 json {
-    page    Math.max(0, (params.int('offset', 0) ?: 0).intdiv(params.int('max', 25) ?: 25))
+    page     Math.max(0, (params.int('offset', 0) ?: 0).intdiv(params.int('max', 25)))
     pageSize params.int('max', 25)
-    total   authorCount
-    items   authorList.collect { Author a -> g.render(template: 'author', model: [author: a]) }
+    total    authorCount
+    items    g.render(template: 'author', collection: authorList ?: [], var: 'author')
 }
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/views/book/_book.gson b/guides/grails-rest-library/v8/snippets/grails-app/views/book/_book.gson
index 28e7cf9d683..3c88bf00fb7 100644
--- a/guides/grails-rest-library/v8/snippets/grails-app/views/book/_book.gson
+++ b/guides/grails-rest-library/v8/snippets/grails-app/views/book/_book.gson
@@ -15,7 +15,11 @@ json {
         name book.author.name
     }
     _links {
-        self   url: g.createLink(controller: 'book',   action: 'show', id: book.id,        absolute: true)
-        author url: g.createLink(controller: 'author', action: 'show', id: book.author.id, absolute: true)
+        self {
+            href g.link(resource: book, absolute: true)
+        }
+        author {
+            href g.link(resource: book.author, absolute: true)
+        }
     }
 }
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/views/book/index.gson b/guides/grails-rest-library/v8/snippets/grails-app/views/book/index.gson
index 763066abd96..1b478abfc88 100644
--- a/guides/grails-rest-library/v8/snippets/grails-app/views/book/index.gson
+++ b/guides/grails-rest-library/v8/snippets/grails-app/views/book/index.gson
@@ -2,12 +2,12 @@ import example.Book
 
 model {
     Iterable<Book> bookList
-    Long           bookCount
+    Integer        bookCount
 }
 
 json {
-    page    Math.max(0, (params.int('offset', 0) ?: 0).intdiv(params.int('max', 25) ?: 25))
+    page     Math.max(0, (params.int('offset', 0) ?: 0).intdiv(params.int('max', 25)))
     pageSize params.int('max', 25)
-    total   bookCount
-    items   bookList.collect { Book b -> g.render(template: 'book', model: [book: b]) }
+    total    bookCount
+    items    g.render(template: 'book', collection: bookList ?: [], var: 'book')
 }
diff --git a/guides/grails-rest-library/v8/snippets/grails-app/views/errors/_errors.gson b/guides/grails-rest-library/v8/snippets/grails-app/views/errors/_errors.gson
new file mode 100644
index 00000000000..4ebbc28679c
--- /dev/null
+++ b/guides/grails-rest-library/v8/snippets/grails-app/views/errors/_errors.gson
@@ -0,0 +1,25 @@
+import org.springframework.http.HttpStatus
+import org.springframework.validation.Errors
+import org.springframework.validation.FieldError
+
+model {
+    Errors errors
+}
+
+response.status HttpStatus.UNPROCESSABLE_ENTITY.value()
+
+json {
+    errors this.errors.allErrors.collect { error ->
+        Map<String, Object> payload = [
+            object : error.objectName,
+            code   : error.code,
+            message: messageSource.getMessage(error, locale)
+        ]
+        if (error instanceof FieldError) {
+            payload.field = error.field
+            payload.rejectedValue = error.rejectedValue
+            payload.bindingFailure = error.bindingFailure
+        }
+        payload
+    }
+}