Search code examples
grailsgrails-ormjwt

Run initializing function on Grails domain class


I have an AuthToken domain model. It accepts an token_string which is a JWT token.

class AuthToken {
  String token_string
}

After initializing the AuthToken via new AuthToken(token_string: '...'), I would like to parse the token, and set properties on the class appropriately. For example expiration should be set based on the token.

If the token is invalid for whatever reason, I'd like to invalidate the AuthToken (i.e. token.validate() should be false).

How can I accomplish this with Grails / GORM?


Solution

  • I recommend adding a static factory method to parse the token String and return a AuthToken. Since you're dealing with a domain class, I'd avoid adding the constructor AuthToken(String tokenString) because then the default Map-based constructor will be deleted. You probably do not want that (and neither does GORM).

    class AuthToken {
      String token_string
      String someProperty
    
      static AuthToken parse(String token_string) {
          new AuthToken(token_string: token_string).with {
              someProperty = token_string.reverse() // an example
    
              return delegate
          }
      }
    }
    
    def token = AuthToken.parse(aTokenString)