GithubHelp home page GithubHelp logo

oupsla / openapi-ts-sdk-builder Goto Github PK

View Code? Open in Web Editor NEW

This project forked from nfroidure/openapi-ts-sdk-builder

0.0 1.0 0.0 1.63 MB

Create a TypeScript SDK from an OpenAPI 3 definition

License: MIT License

TypeScript 100.00%

openapi-ts-sdk-builder's Introduction

openapi-ts-sdk-builder

Create a TypeScript SDK from an OpenAPI 3 definition

GitHub license Build status Coverage Status NPM version Dependency Status devDependency Status Package Quality

A TypeScript rewrite of openapi-js-sdk-builder.

It basically brings a minimal TypeScript SDK from an OpenAPI3 file with no OOP inside. It is based on the axios module.

Usage

With a raw Node script:

import { generateSDKFromOpenAPI } from 'openapi-ts-sdk-builder';
import { readFileSync, writeFileSync } from 'fs';

const openAPIContents = readFileSync('openapi.json', 'utf-8');
const sdkContents = generateSDKFromOpenAPI(openAPIContents);

writeFileSync('sdk.ts', sdkContents, 'utf-8');

You can also use the built-in webpack loader in your frontends builds:

In webpack.config.js:

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /(\.|^)openapi.json$/,
        loader: require.resolve('openapi-js-sdk-builder'),
        type: 'javascript/auto',
      },
    ],
  },
};

In your code:

import API from './myapi.openapi.json';

// Just use the API then
await API.getPing();

You can also safely operate on the API by doing so:

import BaseAPI from './sdk';
import config from './config';
import type { AxiosRequestConfig } from 'axios';

type AuthTokenInput = { token?: string };

export default Object.keys(BaseAPI).reduce((FinalAPI, operationId) => {
  FinalAPI[operationId] = async (
    { token, ...input }: unknown & AuthTokenInput,
    options: AxiosRequestConfig = {},
  ) => {
    return BaseAPI[operationId](
      {
        ...input,
        xApplicationVersion: process.env.VERSION,
      },
      {
        ...options,
        baseURL: config.apiURL,
        headers: {
          ...options.headers,
          ...(token
            ? {
                authorization: `Bearer ${token}`,
              }
            : {}),
        },
        validateStatus: () => true,
      },
    );
  };
  return FinalAPI;
}, {}) as {
  [P in keyof typeof BaseAPI]: (
    input: Parameters<typeof BaseAPI[P]>[0] & AuthTokenInput,
    config?: AxiosRequestConfig,
  ) => Promise<ReturnType<typeof BaseAPI[P]>>;
};

Finally, you may appreciate using it with the useSSR React hook to benefit from your SDK types:

import useSWR from 'swr';
import type { PromiseValue } from 'type-fest';
import API from './api';

type Handler<I, O> = (input: I) => Promise<O>;
type HandlerInput<T> = T extends Handler<infer I, unknown> ? I : never;
type HandlerOutput<T> = T extends Handler<unknown, infer I> ? I : never;

const API_KEYS: Record<any, string> = Object.keys(API).reduce((hash, key) => {
  hash[API[key]] = key;
  return hash;
}, {});

export default function useAPISWR<T extends Handler<any, any>>(
  swrCouple: [T, HandlerInput<T>],
  options?: Parameters<typeof useSWR>[2],
) {
  const uniqueKey = swrCouple
    ? Object.keys(swrCouple[1]).reduce(
        (finalKey, key) => finalKey + key + JSON.stringify(swrCouple[1][key]),
        // Sadly, here, we cannot rely on `swrCouple[0].name` to
        // build the unicity key since the build destroys it
        API_KEYS[swrCouple[0]] + '-',
      )
    : null;

  return useSWR<
    PromiseValue<HandlerOutput<T>> extends { body: infer D } ? D : never
  >(
    uniqueKey,
    async () => (await swrCouple[0](swrCouple[1])).body,
    options as any,
  );
}

API

openapi-ts-sdk-builder

openapi-ts-sdk-builder~generateSDKFromOpenAPI(openAPIContent, options) โ‡’ Promise.<string>

Build a JS SDK from an OpenAPI file

Kind: inner method of openapi-ts-sdk-builder
Returns: Promise.<string> - The SDK JS code

Param Type Description
openAPIContent string
options Object
options.sdkVersion string The SDK version
[options.sdkName] string The SDK name (default to API)
[options.ignoredParametersNames] Array.<string> Provide a list of parameters to ignore
[options.undocumentedParametersNames] Array.<string> Provide a list of parameters to keep undocumented
[options.filterStatuses] Array.<number> Filter some response statuses
[options.generateUnusedSchemas] boolean Wether to generate the schemas that ain't used at the moment

Authors

License

MIT

openapi-ts-sdk-builder's People

Contributors

nfroidure avatar oupsla avatar antoinedmc avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.