Skip to content

Typed API definition  #364

@anuragkumar19

Description

@anuragkumar19

Describe the feature

Hi! I have been using nuxt and ofetch for a while. The ofetch package(independently) lacks the types safety I get when working with ofetch with nitro. I have to specify types for response on every request manually. So, I looked up in the repo and found out that types inference based on schema was a part of nitro not ofetch. I think those types should belong here in ofetch repo so, if we work independently with ofetch we can get type safety.

I open a dicussion in Nitro repo, here nitrojs/nitro#2157

I have been working on it for past couple of days. It is almost done. There are few thing to fix and discuss.

While I was implementing it. I thought it is also time to change the structure of InternalApi so that it will now support more types like body/query/params.

Here is now schema I come up with.

interface ApiDefinition {
  "/api/v1": {
    default: {
      response: { message: string };
    };
  };
  "/api/v1/auth/register": {
    post: {
      response: { message: string };
      request: {
        body: {
          name: string;
          email: string;
          username: string;
          password: string;
        };
      };
    };
  };
  "/api/v1/users/search": {
    get: {
      response: { users: { username: string }[] };
      request: {
        query: {
          username: string;
        };
      };
    };
  };
  "/api/users/:username": {
    get: {
      response: { user: { username: string; name: string; isFriend: boolean } };
      request: {
        params: {
          username: string;
        };
      };
    };
    post: {
      response: { message: string };
      request: {
        params: {
          username: string;
        };
      };
    };
  };
}

You can check out my version of implementation in
https://github.com/anuragkumar19/ofetch

There are some examples embedded in the types.ts for testing while development which will be removed in final version.

I have also examples in playground/index.ts for convention.

I think it will be totally backward compatible but we will discuss. Also compatible with nitro because it fully override $Fetch, also after this change we can fully drop types/fetch.ts in nitro.

This will solve many issues opened in nitro and nuxt repo for type-safety with request object.

I will open a PR soon. I need to clean few this up first.

Additional information

  • Would you be willing to help implement this feature?

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