enkot / nuxt-open-fetch

Generate zero-overhead, typed OpenAPI clients for Nuxt.
https://nuxt-open-fetch.vercel.app
MIT License
114 stars 10 forks source link

Type body parameters #3

Closed IlyaSemenov closed 8 months ago

IlyaSemenov commented 8 months ago

As a developer making OpenAPI requests, I would like the body parameter to be type checked against OpenAPI schema.

Example:

await $authFetch("/user/authorize/", {
  method: "post",
  body: {
    login: "foo",
    password: 123, // Expected: type error
  },
})

This respective typings are readily available in generated paths:

export interface paths {
  "/user/authorize/": {
    post: {
      requestBody: {
        content: {
          "application/json": {
            login?: string;
            password?: string; // <--- we already know that

However, FetchOptions doesn't even attempt to pull them:

https://github.com/enkot/nuxt-open-fetch/blob/abdfdf447a3a7c2fb24447518c1b9908ca29a4ab/src/runtime/clients.ts#L19-L23

I once created a custom tailored useFetch wrapper using OpenAPI 2.0 (openapi-typescript@4) bindings which was actually extracting body typings, so I am pretty sure this is doable.

Is that something you are considering/perhaps already working on? Or at least willing to be accepting a PR?

enkot commented 8 months ago

@IlyaSemenov Good catch! body jumped out of sight on some iteration 🙈

IlyaSemenov commented 8 months ago

Just a heads up, you'll need to use Lowercase<M>. The reason being, OpenAPI uses "patch" for the method name, yet it must be upper-case "PATCH" in ofetch parameters (e.g. see https://github.com/whatwg/fetch/issues/50, but this is also relevant for native fetch).

enkot commented 8 months ago

ofetch now supports patch and other methods in lower and upper case - https://github.com/unjs/ofetch/pull/259 But you are right, the types for upper-cased methods are missing. Will fix it 👌

IlyaSemenov commented 8 months ago

Oh, good to know, that's a recent addition. Thanks!

enkot commented 8 months ago

@IlyaSemenov Fixed in 0.2.0