ajaishankar / openapi-typescript-fetch

A typed fetch client for openapi-typescript
MIT License
233 stars 54 forks source link

String request payload is incorrectly serialized #48

Open ondrejpar opened 2 years ago

ondrejpar commented 2 years ago

Relevant part of api.yml:

      requestBody:
        content:
          application/json:
            schema:
              type: string

The generated function has correct signature: myFunc(arg: string). However, fetcher.ts only handles objects and arrays. The string "foo" is this serialized as {"0":"f","1":o","2":"o"}

Is there any workaround atm?

ondrejpar commented 2 years ago

Found a workaround: call the function like this:

myFunc({ _BODY_STRING: 'real data' } as unknown as string);

add fetch middleware like this:

fetcher.configure({
  baseUrl: "...",
  init: ...
  use: [
    async (url, init, next) => {
      const body = JSON.parse(init.body);
      if (body._BODY_STRING) {
        init.body = JSON.stringify(body._BODY_STRING);
      }
      return await next(url, init)
    }
  ]
});

Ugly AF but works for now.

studiosciences commented 2 years ago

~I don't think your spec is correct. It doesn't return application/json. It should betext/plain`.~

~The fetch function will return a type of unknown, which you can cast to a string. At least, that is what I am seeing. That isn't ideal, but you don't need the middleware.~

ondrejpar commented 2 years ago

@studiosciences it's requestBody specification, not responseBody specification. Also, it's not text/plain, it really is application/json - it is actually possible, although adimttedly unusual, to JSON serialize non-objects ('42' is valid JSON containing number 42, '"foo"' is valid JSON containing string "foo").