oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

[suggestion] own Time type (would make calls to flaky API server easier)

Open aanno opened this issue 3 years ago • 3 comments

I tried oapi-codegen for client generation. Using the client, I encountered that data format the REST API server provides is not in line with https://swagger.io/docs/specification/data-models/data-types/#string (that requires RFC 3339, section 5.6).

Here are 2 samples of the flaky format: 2017-07-21T17:32:2938938 2017-07-21T17:32:3939937-07:00

Using code generated by oapi-codegen would be substantial easier if

  1. There would be an extra type for time, e.g. type Time time.Time
  2. This Time type would be used in the generated code, e.g. every occurence of *time.Time would be replaced with *Time.

With this changes in place, customising the JSON deserialisation would be possible with something like:

// https://stackoverflow.com/questions/45303326/how-to-parse-non-standard-time-format-from-json
const dtNoZ = "2006-01-02T15:04:05.999999999"
const dtNoZ2 = "2006-01-02T15:04:05.999999999-07:00"

type Time time.Time

// Implement Marshaler and Unmarshaler interface
func (j *Time) UnmarshalJSON(b []byte) error {
    s := strings.Trim(string(b), "\"")
    t, err := time.Parse(dtNoZ, s)
    if err != nil {
		t2, err := time.Parse(dtNoZ2, s)
		if err != nil {
			return err
		}
		*j = Time(t2)
		return nil
	}
    *j = Time(t)
    return nil
}
    
func (j *Time) MarshalJSON() ([]byte, error) {
    return json.Marshal(time.Time(j))
}

// Maybe a Format function for printing your date
func (j *Time) Format(s string) string {
    t := time.Time(j)
    return t.Format(s)
}

aanno avatar Dec 08 '22 14:12 aanno

We have encountered a similar requirement to parse non RFC3339 date-time into the generated resposne structure, but I think that is a generic issue for parsing time.Time object from string value. I would suggest to be able to provide the ability to use alternative Time type in the generated oapi code, so we can implement Unmarshaler/Marshaler interface for a customized type to be used.

moihn avatar Dec 12 '22 15:12 moihn

Hey guys, is there any way to deal with this? Unfortunately the (german) online retailer otto.de is using a different date format in his api and so the generated code from it's OpenAPI 3 spec file (blob:https://api.otto.market/040f5269-a447-45f9-90a9-a17b607aad149 is not working.

Thanks Simon

sim-jac avatar Jul 26 '23 15:07 sim-jac