Skip to content

Pentadome/nuxt-openAPI-wrapper

Repository files navigation

Nuxt Typesafe OpenAPI Fetch wrapper

npm version npm downloads License Nuxt

Generates a typesafe fetch client for Nuxt and Nitro using Openapi-ts.

Usage

Install the module:

npx nuxi module add nuxt-openapi-wrapper

Configure the api clients:

export default defineNuxtConfig({
  modules: ['nuxt-openapi-wrapper'],
  openAPIWrapper: {
    // config options for openAPI-ts
    openApiTsConfig: {},
    apis: {
      github: {
        baseUrl: 'https://api.github.com',
        // no explicit openAPI document. Will look for an openapi.{json,yaml} in the ./openapi/github directory
      },
      gitlab: {
        baseUrl: 'https://gitlab.com',
        // explicit openAPI document.
        openApi:
          'https://gitlab.com/gitlab-org/gitlab/-/raw/master/doc/api/openapi/openapi.yaml?inline=false',
      },
    },
  },
});

That's it! You can now use Nuxt OpenAPI wrapper in your Nuxt app ✨

const x = await $fetchGithub('/advisories/{ghsa_id}' /* auto completion! */, {
  pathParams: {
    // support for path parameters!
    ghsa_id: '2', // typesafety!
  },
});

console.log(x.description); // typesafe response type!

Customizing the client

Often you want to customize the client, e.g. so it always adds an authentication header to requests.

Disable auto import for the base client

export default defineNuxtConfig({
  modules: ['nuxt-openapi-wrapper'],
  openAPIWrapper: {
    apis: {
      github: {
        baseUrl: 'https://api.github.com',
        clients: { nuxt: { autoImport: false }}
        ...

Add a new ts file to your composables folder, e.g. ./composables/githubClient.ts.

// import the base client explicitly
import {
  $fetchGithub as _$fetchGithub,
  useGithubFetch as _useGithubFetch,
  useLazyGithubFetch as _useLazyGithubFetch,
} from '#openapi-wrapper';

// you might need to add // @ts-ignore error
export const $fetchGithub: typeof _$fetchGithub = (path, opts?) => {
  // customize the request
  opts ??= {};

  opts.onRequest = (ctx) =>
    ctx.options.headers.append('Authorization', 'Bearer 1234');

  opts.onResponse = (ctx) => console.log('response!');

  return _$fetchGithub(path, opts);
};

// Do the same for useGithubFetch and useLazyGithubFetch

You can also create a custom Nitro fetch client. E.g. by creating a ./server/utils/githubClient.ts file.

Nuxt composable example

Nitro utils example

Contribution

Local development
# Install dependencies
npm install

# Generate type stubs
npm run dev:prepare

# Develop with the playground
npm run dev

# Build the playground
npm run dev:build

# Run ESLint
npm run lint

# Run Vitest
npm run test
npm run test:watch

# Release new version
npm run release