Skip to content

Instantly share code, notes, and snippets.

@soundarmoorthy
Created July 29, 2020 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soundarmoorthy/25304a62e5d835907b2003ab2a2b5097 to your computer and use it in GitHub Desktop.
Save soundarmoorthy/25304a62e5d835907b2003ab2a2b5097 to your computer and use it in GitHub Desktop.
Grails
<title>Grails</title>
</div>

Grails 3.1.1 quick reference

http://docs.grails.org/3.1.1/ref/Command%20Line/Usage.html

How to respond from a REST API Controller

From the controller action , do the following. This is for returning one object by name obj

if(res == null)
	response.sendError 500
else
	withFormat {
	    json { render obj as JSON }
    }	

How to inject a service into controller

Define the variable as the class name of the service. It will be injected automatically
For example if your service name is
class AtlantisService { }

then in the controller

class AtlantisController
{
	 // inject an instance of type AtlantisService
     def atlantisService;      
}

GROM how to find the max element from a table

In this example ModelClassName is the name of the model in which you are running the query. max("id") id is the column that you are trying to find the max for.

        def items = ModelClassName.withCriteria {
            projections {
                max("id")
            }
        }

GROM constraints quick look

        id blank:false, nullable:false, unique : true
        expiryDate blank:false, nullable : false
        shortUrl blank:false, nullable: false, url : true

Add days to a date

  Date newDate = new Date().plus(100); //current date + 100 days.
  Date newDate = new Date().plus(-20); //current date - 20 dats.

Mark resource as readonly in a controller

UserApiController() {
super(User, true /* read-only */``)

Enable CORS

grails:
    cors:
        enabled: true

Inject properties

import org.springframework.beans.factory.annotation.Value
class WidgetService {
  @Value('${widget.width:50}')
  int width;
  def someServiceMethod() {
  // this method may use the area property...

CURD default actions

class CrudController {
    def index() {} //usually a "list" view
    def save() {} //save new records
    def show(Serializable id) {} //retrieve details on a specific record
    def update(Serializable id) {} //update a specific record
    def delete(Serializable id) {} //delete specific record
}

Verify mappings

package demo

import grails.testing.web.UrlMappingsUnitTest import spock.lang.Specification

class ConferenceUrlMappingsSpec extends Specification implements UrlMappingsUnitTest<ConferenceUrlMappings> {

void setup() {
    mockController(ConferenceController) 
}

void "test conference mappings"() {

    expect: "calls to /conference/talks to succeed"
    verifyUrlMapping("/conf/talks", controller: 'conference', action: 'talks', method: 'GET')  
    verifyUrlMapping("/conf/talks/1", controller: 'conference', action: 'talks', method: 'GET') {
        id = '1'
    }

    when: "calling /conf/speakers"
    assertUrlMapping("/conf/speakers", controller: 'conference', action: 'speakers', method: 'GET') 

    then: "no exception is thrown"
    noExceptionThrown()
}

}

Using Mysql

In build.gradle include the following

dependencies {
 runtime 'mysql:mysql-connector-java:5.1.33'

In application.yml use the following

 dbCreate: update
       pooled: true
       url: jdbc:mysql://127.0.0.1:3306/xxx
       username: yyy
       password: zzz
       driverClassName: com.mysql.jdbc.Driver
       dialect: org.hibernate.dialect.MySQL5InnoDBDialect

Using newer version of connector might cause timezone issues and to fix that mention the url to db as follows in application.yml
url: jdbc:mysql://127.0.0.1:3306/mydb?serverTimezone=UTC

Save with caution

It’s also possible to call the validate method before save.

if (user.validate()) {
    // do something with user
}
else {
    user.errors.allErrors.each {
        println it
    }
}

Directly calling save will also run validations.

if(song.save()) 
{ 
    println "Song was created!" 
} 
else 
{ 
    song.errors.allErrors.each { println it.defaultMessage } 
}

The above snippet will let you know of any failures during save and any of the hooks that gets executed.

GORM Url Validation fails for localhost url’s

grails/grails-core#10249

Sharing constraints

class User {
    String firstName
    String lastName
    String passwordHash
static constraints = {
    firstName blank: false, nullable: false
    lastName blank: false, nullable: false
    passwordHash blank: false, nullable: false
}

}

You then want to create a command object, UserCommand, that shares some of the properties of the domain class and the corresponding constraints. You do this with the importFrom() method:

class UserCommand {
    String firstName
    String lastName
    String password
    String confirmPassword
static constraints = {
    importFrom User

    password blank: false, nullable: false
    confirmPassword blank: false, nullable: false
}

}

Bind data from http request

To Bind request from url params

  bindData(obj, params, [include: ['originalUrl', 'expiryDate']])

To bind from request body

        /*
       {
            "urlEntry": {
                "originalUrl": "https://news.ycombinator.com",
                "expiryDate": "2020-08-29T07:05:45Z",
                "dateCreated" : "2020-07-29T07:05:45Z",
                "shortUrl" : "http://localhost:8080/u/1"
            }
        }
         */
        bindData(obj, request.JSON.urlEntry, [include: ['originalUrl', 'expiryDate']])
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment