postgresql – GORM database colum with json data-ThrowExceptions

Exception or error:

I am trying to write an email service, where I want to store some data related to email into a Postgres DB using gorm. I have a field which needs to be stored as a JSON blob, which in request passed as a JSON object. When I am trying to migrate, it errors keep saying unsupported type map. When manually add the DB, then run gorm, it doesn’t write the row to the database.

I have seen some example where it’s using postgres.Json as field types, but I want the field loaded from the request as map[string]string.

// Email : Base with injected fields `UUID`, `CreatedAt`, `UpdatedAt`
type Email struct {
    gorm.Model
    Status      string             `grom:"type:varchar(32);not null"`
    TemplateID  string             `grom:"type:varchar(256)"`
    ToEmai      string             `grom:"type:varchar(256);not null"`
    FromEmail   string             `grom:"type:varchar(256);not null"`
    ToName      string             `grom:"type:varchar(256);not null"`
    FromName    string             `grom:"type:varchar(256);not null"`
    Subject     string             `grom:"type:varchar(256)"`
    Message     string             `grom:"type:varchar"`
    DynamicData *map[string]string `grom:"type:json"`
}

this is my model.

then I do a gin request:

// SendEmail : sends an email
func SendEmail(c *gin.Context) {
    body, err := ioutil.ReadAll(c.Request.Body)

    if err != nil {
        log.Error("Error reading request body to get rate estimates")
    }

    var newEmail = models.Email{
        Status: "PENDING",
    }

    jsonErr := json.Unmarshal(body, &newEmail)

    if jsonErr != nil {
        log.Error(jsonErr)
    }

    database.DB.Create(&newEmail)

    defer c.Request.Body.Close()

    err = newEmail.SendSendgridEmail()

    if err != nil {
        c.JSON(http.StatusBadRequest, err)
    } else {
        c.JSON(http.StatusOK, "Successfully sent email")
    }
}

which then looks into this function

func (e Email) dynamicTemplateEmailBody() []byte {
    newMail := mail.NewV3Mail()

    emailFrom := mail.NewEmail(e.FromName, e.FromEmail)
    newMail.SetFrom(emailFrom)

    newMail.SetTemplateID(e.TemplateID)

    p := mail.NewPersonalization()
    tos := []*mail.Email{
        mail.NewEmail(e.ToName, e.ToEmai),
    }
    p.AddTos(tos...)

    if e.DynamicData != nil {
        for key, value := range *e.DynamicData {
            log.Infof("%s %s", key, value)
            p.SetDynamicTemplateData(key, value)
        }
    }

    newMail.AddPersonalizations(p)
    return mail.GetRequestBody(newMail)
}

I would like to be able to run DB.AutoMigrate(&models.Email{}) and automatically migrate the objects, or and when I make a request to the endpoint, the row gets added to my email table.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *