简体   繁体   中英

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 (ie token.validate() should be false).

How can I accomplish this with Grails / GORM?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM