orval-labs / orval

orval is able to generate client with appropriate type-signatures (TypeScript) from any valid OpenAPI v3 or Swagger v2 specification, either in yaml or json formats. 🍺
https://orval.dev
MIT License
3.01k stars 329 forks source link

Mock: Invalid mocked values when useDates enabled #1517

Closed clintonb closed 1 month ago

clintonb commented 3 months ago

What are the steps to reproduce this issue?

  1. Create an Open API spec with dates.
  2. Configure Orval with useDates: true and mock: true.
  3. Generate client

What happens?

The mocks use faker for the mocked values, but convert the fake Date to a string.

What were you expecting to happen?

The mocked data should be a Date.

What versions are you using?

Package Version: 6.31.0

clintonb commented 3 months ago

This also impacts usage of formData since the Date needs to be converted to a string.

clintonb commented 3 months ago

I can work around the mock issue with an override:

module.exports = {
  api: {
      mock: true,
      override: {
        useDates: true,
        mock: {
          format: {
            date: () => faker.date.recent(),
            'date-time': () => faker.date.recent(),
          },
        },
      },
  }
};
clintonb commented 3 months ago
module.exports = {
  api: {
      mock: true,
      override: {
        useDates: true,
                formData: {
          path: './src/api/custom-form-data.ts',
          name: 'customFormData',
        },
      },
  }
};
export const customFormData = <Body>(body: Body): FormData => {
  const formData = new FormData()

  Object.entries(body).forEach(([key, value]) => {
    // Ensure we encode dates as strings
    if (value instanceof Date) {
      value = value.toISOString()
    }

    formData.append(key, value)
  })

  return formData
}

export default customFormData
melloware commented 3 months ago

Nice solution!