npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@progresso/openapi-typescript-client-api-generator

v1.0.2

Published

A generator that reads swagger / open api 3 json configs and generates typescript client services with axios

Downloads

8

Readme

openapi-typescript-client-api-generator

A generator that reads swagger / open api 3 json configs and generates typescript client services with axios.

Hint: implemented with specific use case in mind.

npm version

Example

Your open-api 3 json config file:

{
  "openapi": "3.0.1",
  "info": {
    "title": "Awesome project API",
    "description": "The API that is just awesome.",
    "version": "1.3.8"
  },
  "tags" : [ { "name" : "users" } ],
  ...
  "paths": {
    "/users": {
      "get": {
        "tags": [ "users" ],
        "operationId": "getAllUsers",
        "description": "Gets all users. Can optionally be filtered by group id.",
        "parameters": [ {
          "name": "groupId",
          "in": "query",
          "description": "The group of the users to retrieve.",
          "required": false,
          "schema": {
            "type": "integer",
            "format": "int32"
          }
        } ],
        "responses": {
          "default": {
            "description": "The users.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref" : "#/components/schemas/User"
                  }
                }
              }
            }
          }
        }
      }
    },
    "/users/{userId}": {
      "get": {
        "tags": [ "users" ],
        "operationId": "getUserById",
        "description": "Retrieve a user by id.",
        "parameters": [ {
          "name": "userId",
          "in": "path",
          "description": "The id of the user to retrieve.",
          "required": true,
          "schema": {
            "type": "integer",
            "format": "int32"
          }
        } ],
        "responses": {
          "default": {
            "description": "The user.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref" : "#/components/schemas/User"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "User": {
        "description": "The user.",
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int32",
            "description": "The id of the user."
          },
          "name": {
            "type": "string",
            "description": "The name of the user."
          },
          "groupId": {
            "type": "integer",
            "format": "int32",
            "description": "The group id of the user."
          }
        }
      }
    }
  }
}

Generated model ( user.ts )

/**
 * Awesome project API 1.3.8 (OpenAPI: 3.0.1)
 * The API that is just awesome.
 *
 * NOTE: This class is auto generated by openapi-typescript-client-api-generator.
 * Do not edit the file manually.
 */

export class User {

    /**
     * Creates a ListColumn.
     *
     * @param {number} id The id of the user.
     * @param {string} name The name of the user.
     * @param {number} groupId The group id of the user.
     */
    constructor(id: number, name: string, groupId: number) {
        this.id = id;
        this.name = name;
        this.groupId = groupId;
    }

    /**
     * The id of the user.
     */
    public id: number;

    /**
     * The name of the user.
     */
    public name: string;

    /**
     * The group id of the user.
     */
    public group id: number;
}

Generated service ( usersService.ts )

/**
 * Awesome project API 1.3.8 (OpenAPI: 3.0.1)
 * The API that is just awesome.
 *
 * NOTE: This class is auto generated by openapi-typescript-client-api-generator.
 * Do not edit the file manually.
 */

import axios from "axios";

import { ServiceBase } from "../../services/serviceBase";
import { IUsersService } from "./usersService.interface";

import { User } from "../models/user";

export class UsersService extends ServiceBase implements IUsersService {
    /**
     * Gets all users. Can optionally be filtered by group id.
     *
     * @param {number} [groupId] The group of the users to retrieve.
     */
    public async getAllUsers(groupId?: number): Promise<User[]> {
        const config = this.getAxiosConfiguration();

        const queryList: string[] = [];
        if (groupId !== undefined) {
            queryList.push(`groupId=${groupId}`);
        }
        const query = `?${queryList.join("&")}`;

        const response = await axios.get<User[]>(`/users${query}`, config);
        return response.data;
    }

    /**
     * Retrieve a user by id..
     *
     * @param {number} userId The id of the user to retrieve.
     */
    public async getUserById(userId?: number): Promise<User[]> {
        const config = this.getAxiosConfiguration();

        const response = await axios.get<User[]>(`/users/${userId}`, config);
        return response.data;
    }
}

Installation

$ yarn add @progresso/openapi-typescript-client-api-generator --dev

Usage

Add an open-api 2.0 / 3.x file to your project

Add a swagger (open-api 2.0) or open-api 3 json config file into your project. I.e. at
[project-root]/api/awesone-api.json

Configure scripts section in package.json

Add a script line into your package.json:

{
  ...
  "scripts": {
    "generate": "openapi-typescript-client-api-generator"
  }
}

Implement ServiceBase for request headers

Implement a service base class called ServiceBase that implements the following method so you are able to pass custom headers like authentication tokens to your requests:

protected getAxiosConfiguration(): AxiosRequestConfig

Run the generator

Execute the generator with

$ yarn generate -c /api/awesome-api.json -sb /client/services -s /client/api/services -m /client/api/models -sm /server/modules/api/models

Parameter documentation

All parameters are required currently. All pathes are relative to the project root.

| Parameter | Description | Example | |--------------|-----------------------------------------------------------------------------------------------------------|-------------------------| | -c <path> | The path to your json config file. | /api/awesome-api.json | | -sb <path> | The path to the directory where your ServiceBase class is located. | /client/services | | -s <path> | The path to the directory where the generated services should be saved to. Will be created if neccessary. | /client/api/services | | -m <path> | The path to the directory where the generated models should be saved to. Will be created if neccessary. | /client/api/models | | -sm <path> | The path to a directory that contains server side models decorated for @nestjs/swagger generation. Used when the config file's version is 2.0 (swagger) to augment services and models by inheritance information. Not used when config file's version is >= 3.0.0 (open-api 3). | /server/modules/api/models |