3.0.8 ā€¢ Published 1 year ago

swagger-typescript-types v3.0.8

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

swagger-typescript-types

Open in Visual Studio Code npm bundle size Github workflow Quality Gate Status Maintainability Rating Security Rating Reliability Rating Coverage Coverage Lines of Code Technical Debt Code Smells Bugs Vulnerabilities Snyk Vulnerabilities for npm package Duplicated Lines (%) Last commit

Generating typescript types from swagger.

āš” Purpose

Here is a little utility to generate typescript artifacts from swagger. This can be useful when you want to sync types between your backend and your frontend.

For example, we have this backend exposing a swagger. The /devs/by-squads route returns an array of DevDto which is a model described in swagger.

Now, I could just write the interface for it myself in the frontend codebase šŸ¤”, right? This is simple enough in our example:

export interface DevDto {
  id: number;
  idSquad: number;
  firstName: string;
  avatar: string;
}

But what if we could just extract these models and generate types instead? Oh...! šŸ˜

šŸ”¶ Disclaimer

šŸšØ I wrote this for a stack based on nestjs for the backend and react-query for the frontend, so this tool may or may not suit your needs. If you think about another usecase, do not hesitate to drop an issue šŸ™ƒ.

āš” Installation

To install, use either yarn or npm:

yarn add -D swagger-typescript-types
npm i -D swagger-typescript-types

āš” Typical use : cli

šŸ”¶ From an url

Let's say we have a backend exposing endpoints on this url: https://devfriends-backend.fly.dev. Now, swagger exposes a json file on the /-json path in this example.

Knowing this, we can add a script to our package.json:

{
  "scripts": {
    "api:sync": "generateTypesFromUrl -u https://devfriends-backend.fly.dev/-json -o ./src/api/types [-t]"
  }
}

The generateTypesFromUrl task takes two arguments:

namedescriptionExample
uThe url of the json exposed by the targeted swaggerhttps://devfriends-backend.fly.dev/-json
oWhere to write our exposed types./src/api/types

Optionally, you can use -t flag if you're using importsNotUsedAsValues in your tsconfig compiler options. It will generate imports like so:

import type { ... } from ...

Our task will do a few things using these arguments when called:

āœ”ļø Fetch the json exposed by our swagger (exposed in our example at the `-json` path).
āœ”ļø Validate the json retrieved against [openapiv3 schema](https://github.com/APIDevTools/openapi-schemas).
āœ”ļø Extract models and generate typings from them.
āœ”ļø Write them on the path defined as second argument (./src/api/types/api-types.ts).
āœ”ļø For each route, create a file containing the endpoint path and re-exporting parameters / request body / responses types.
āœ”ļø Warn us if some specs are missing (missing response types, missing path parameters, etc.).

šŸ”¶ From a file

We can also generate types from a file:

{
  "scripts": {
    "api:sync": "generateTypesFromFile -i ./specs/swagger.json -o ./src/api/types [-t]"
  }
}

The generateTypesFromUrl task takes two arguments:

namedescriptionExample
iThe path of the swagger json file./specs/swagger.json
oWhere to write our exposed types./src/api/types

Optionally, you can use -t flag if you're using importsNotUsedAsValues in your tsconfig compiler options. It will generate imports like so:

import type { ... } from ...

Again, our task will do the following:

āœ”ļø Read the json file.
āœ”ļø Validate it against [openapiv3 schema](https://github.com/APIDevTools/openapi-schemas).
āœ”ļø Extract models and generate typings from it.
āœ”ļø Write them on the path defined as second argument (./api-types.ts).
āœ”ļø For each route, create a file containing the endpoint path and re-exporting parameters / request body / responses types.
āœ”ļø Warn us if some specs are missing (missing response types, missing path parameters, etc.).

āš” Generated files

Taking our example backend, let's check the files generated:

./api-types.ts

export interface SquadDto {
  id: number;
  name: string;
}
export interface AllSquadsResultDto {
  result: Array<SquadDto>;
}
export interface ApiResponseDto {
  statusCode: number;
  message: string;
}
export interface DevDto {
  id: number;
  idSquad: number;
  firstName: string;
  avatar: string;
}
export interface SquadsDevelopersResultDto {
  result: Array<DevDto>;
}
export interface BadRequestDto {
  statusCode: number;
  message: string | Array<string>;
  error: string;
}
export interface AllDevsResultDto {
  result: Array<DevDto>;
}
export interface ChangeSquadBodyDto {
  idDev: number;
  idSquad: number;
}
export interface ChangeSquadResultDto {
  result: string;
}
export interface DevelopersBySquadsBodyDto {
  idSquads: Array<number>;
}
export interface DevelopersBySquadsResultDto {
  result: Array<DevDto>;
}

Now let's check an endpoint:

./SquadsController/getSquadsDevelopers.ts

/*
 * method: get
 * summary: Get the developers belonging to a squad
 * description: Retrieves the squad developers
 */

import { SquadsDevelopersResultDto, BadRequestDto, ApiResponseDto } from './../api-types';

export const getPath = (id: number): string => `/squads/${id}/devs`;

export type GetSquadsDevelopersSuccess = SquadsDevelopersResultDto;
export type GetSquadsDevelopersError = BadRequestDto | ApiResponseDto;

āš” Api

On top of the cli, this package exposes the following functions:

šŸ”¶ Functions

šŸŒ€ generateTypesFromUrl

This function generates types from a swagger exposed online. Typical use:

const params = {
  swaggerJsonUrl: 'https://devfriends-backend.fly.dev/-json',
  outputPath './src/specs',
  importsNotUsedAsValues: false
};

const {
  typesGenerated, // boolean, specifies whether types have been extracted (./api-types.ts file)
  endpointsCount  // number of endpoints extracted
}: GenerationResult = await generateTypesFromUrl(params);

šŸŒ€ generateTypesFromFile

This function generates types from a swagger json file. Typical use:

const params = {
  inputPath: './src/api/swagger.json',
  outputPath './src/specs',
  importsNotUsedAsValues: false
};

const {
  typesGenerated, // boolean, specifies whether types have been extracted (./api-types.ts file)
  endpointsCount  // number of endpoints extracted
}: GenerationResult = await generateTypesFromFile(params);

šŸŒ€ validateSchema

This function validates some arbitrary json against the openapiv3 schema. Typically use:

const json: InputSwaggerJson = { ... };

const schema: ValidatedOpenaApiSchema = await validateSchema(data);

šŸŒ€ generateTypesDefinitions

This function extracts models from the swagger json and generates typings from them. Typical use:

const outPath = './src/api/types';
const schema: ValidatedOpenaApiSchema = { ... };
const importsNotUsedAsValues = true

await generateTypesDefinitions(outPath, schema, importsNotUsedAsValues);
3.0.8

1 year ago

3.0.4

1 year ago

3.0.3

1 year ago

3.0.7

1 year ago

3.0.6

1 year ago

3.0.5

1 year ago

3.0.2

2 years ago

3.0.1

2 years ago

3.0.0

2 years ago

2.2.1

2 years ago

2.2.0

2 years ago

2.1.8

2 years ago

2.1.7

2 years ago

2.1.4

2 years ago

2.1.6

2 years ago

2.1.5

2 years ago

2.1.2

3 years ago

2.1.1

3 years ago

2.1.3

3 years ago

2.1.0

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago