Krystian
Krystian

Reputation: 3423

Grails - create read only api

I would like to limit some of the actions in controllers to be read-only. Is there any way I could do that? What I want is the transaction not to save after it is finished, for certain actions.

Any help is appreciated.

We are talking about 1.3.7.

Upvotes: 0

Views: 2111

Answers (4)

Oliver Tynes
Oliver Tynes

Reputation: 964

The 'how to make read only domains' is something that comes up now and then on the mailing lists and other places.

The quick answer is: You can't 100% secure against writes.

Various methods to achieve somewhat read only:

  1. Use .read() method to get an object, that ensures that you need to explicitly .save() to make item persist.

  2. If on sql, you can make a view and make a domain class map to this view, then you cant save (and trying to save will throw errors).

  3. Make beforeUpdate() throw exception, thereby stopping the save.

  4. Changes to static mapping = {}, but I am not quite sure what to do there, it has been mentioned on the mailing list is all I can remember, google through the nabble list for grails-user if you want to find out.

If your stuff is fairly static an mysql view is a good choice, if you need to query on them, the beforeUpdate() might be the good choice.

You ask for 'read only actions' though, do you mean scaffolded ones? Programmatically disallowing saving in a controller action is not harder than just.. not adding the save (or not modifying the object at all).

Upvotes: 4

jenk
jenk

Reputation: 1043

Put logic in method of grails service

class MyController {
  def myService

  def myAction = {
    myService.method(params)
    []
  }
  ...
}

and mark it as read-only:

class MyService {
  @Transactional(readOnly = true)
  def method(def patams) { ... }
}

Upvotes: 2

Krzysztof Cygan
Krzysztof Cygan

Reputation: 310

Not sure if that's enough for you, but there is a read method which is read-only as opposed to get http://grails.org/doc/latest/ref/Domain%20Classes/read.html

Upvotes: 0

socha23
socha23

Reputation: 10239

You can use withTransaction method on domain object and set it to rollback only there.

http://grails.org/doc/latest/ref/Domain%20Classes/withTransaction.html

Declarative transaction management is built-in for services, see Grails reference manual, Declarative Transactions. It won't work for controllers, but there is a plugin for that: http://www.grails.org/plugin/transactional-controller

Upvotes: 1

Related Questions