0
votes

tl;dr

How can I dynamize the JSON fields of a struct?

I am using gorm as the ORM. I have my model definition as a struct:

type UserAccessToken struct {
    Id        uint           `gorm:"primaryKey" json:"-"`
    CreatedAt time.Time      `json:"createdAt"`
    DeletedAt gorm.DeletedAt `json:"deletedAt"`
    User      User           `gorm:"constraint:OnDelete:CASCADE" json:"-"`
    UserId    uint           `gorm:"not null" json:"-"`
    IpAddress string         `gorm:"not null" json:"ipAddress"`
    Token     string         `gorm:"not null" json:"token"`
}

I have multiple endpoints and I want to use different fields of the struct serialized on each endpoint.

For example, on POST /user-access-tokens/ user will be basic authenticated and a new access token will be created and returned on the response. However, on GET /user-access-tokens/ list API endpoint, the response will be a list of the UserAccessTokens, but the Token won't be on the response. And I am planning to create another endpoint only to be used by the administration interface, and all fields will be available there.

There are two I can think of:

  1. Creating a different struct and reading from the database into this struct.
  2. Adding a method like Map(scenario string) to the model struct which will create a map of the struct according to scenario, but in this case, I also need to add function to handle multiple instances of the struct.

What is the recommended way for this?

1
Hi Gokhan, knowing more about your application can yield better answers. What are these two endpoints doing? How are they called? How complicated application are you building (lines of code / amount of layers / packages?) - Tomor
Hi Tomor, you are right, I updated my question and added example use cases. - Gokhan Sari

1 Answers

1
votes

You can use another struct:

type UserAccessstruct {
    Id        uint           `gorm:"primaryKey" json:"-"`
    CreatedAt time.Time      `json:"createdAt"`
    DeletedAt gorm.DeletedAt `json:"deletedAt"`
    User      User           `gorm:"constraint:OnDelete:CASCADE" json:"-"`
    UserId    uint           `gorm:"not null" json:"-"`
    IpAddress string         `gorm:"not null" json:"ipAddress"`
   
}


type UserAccessToken {
    UserAccessstruct
    Token     string         `gorm:"not null" json:"token"`
}

func Get() {
   var userAccess UserAccessToken
   db.Select(selectQuery).First(&userAccess)
   

   return userAccess // Full return
   return userAccess.UserAccessstruct // Inner struct without token
}