Skip to content

[typescript-fetch] Dates in request body are not ISO formatted #13841

@danmichaelo

Description

@danmichaelo
Description

If the schema contains a date-time field in a request body, and I pass a Date object to one of the generated methods, the date is not ISO formatted, but encoded using the default string representation of the Date (i.e. Thu Oct 27 2022 14:04:50 GMT+0200 (Central European Summer Time)).

openapi-generator version

6.2.0, not a regression

OpenAPI declaration file content or url

Here's a minimal declaration:

openapi: 3.0.0
paths:
  "/jobs/{id}":
    patch:
      summary: Patch update job
      operationId: patch-job
      requestBody:
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              additionalProperties: false
              properties:
                started_at:
                  type: string
                  format: date-time
Command line used for generation
openapi-generator generate -i openapi.yaml -g typescript-fetch --skip-validate-spec

(--skip-validate-spec because I tried to keep the example minimal, so I didn't include responses, info, etc.)

Steps to reproduce
import {DefaultApi} from "."

const api = new DefaultApi();
api.createJob({startedAt: new Date()})
Related issues/PRs

Couldn't find any issue related to this particular problem. The closest I found was this other typescript-fetch serialization issue: #11613

Suggest a fix/enhancement

This seems to be happening because the Date object is passed directly to URLSearchParams at

formParams.append('{{baseName}}', requestParameters.{{paramName}} as any);

Basically this is what happens:

const params = new URLSearchParams()
params.set("started_at", new Date())

If I add .toISOString() to the relevant line in the generated apis.ts, it works:

if (requestParameters.endedAt !== undefined) {
  formParams.append('started_at', requestParameters.startedAt.toISOString() as any);
}

So I guess perhaps a new helper method could be introduced? Something like this?

export function encodeFormParamValue(value: any): any {
    if (value instanceof Date) {
        return value.toISOString();
    }
    // ... add more types to be serialized as needed ...
    return value;
}

Do you think this would be a good approach?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions