Code Monkey home page Code Monkey logo

openapi-typescript's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

openapi-typescript's Issues

How to remove wrapper ?

In 1.5 version i could add {wrapper: false}, now i cant ?
I want use interfaces by just it name - UserRole without strings and nested interfaces -definitions['User']['role']

TypeError: swaggerToTS is not a function

I am trying to use this library to generate typescript from swagger definition but I am getting the following error. What am I missing here?
TypeError: swaggerToTS is not a function

const swaggerToTS = require("@manifoldco/swagger-to-ts");

const input = JSON.parse(readFileSync("src/buildSwagger/swagger.json", "utf8")); 
const output = swaggerToTS(input);  

Add paths support

Suggested in #112:

any plans for components.parameters?

Looking into it, parameters is part of components.paths, which is the same as Swagger 2.0’s paths. So adding support for v3 should also include v2. That said… what should the schema look like for this? I propose something like :

interface components {
  paths: {
    "/v1/checkout/sessions": {
      get: {
        parameters: {
          ending_before?: string;
          expand?: string[];
        }
      }
    }
  }
}

Aliasing that would look like;

type parameters = components["paths"]["/v1/checkout/sessions"]["get"]["parameters"];

This ticket is a proposal for implementation. This looks the most straightforward to me, but are there any other considerations when it comes to paths? Is this usage intuitive and does this work for most people?

I’d love to hear stories from using paths to confirm if this would help or if any additional info would be helpful.

connect ETIMEDOUT

hello, wen I run command npx @manifoldco/swagger-to-ts swagger_ac.yaml --output ac.ts (swagger_ac.yam is my swagger open Api file), it tips:

npm ERR! Unexpected end of JSON input while parsing near '....0","@types/jest":"^2'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2020-07-29T02_37_01_355Z-debug.log
Install for [ '@manifoldco/swagger-to-ts@latest' ] failed with code 1

this is the log file contents, how can i resovle it ?:

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   '@manifoldco/swagger-to-ts@latest',
1 verbose cli   '--global',
1 verbose cli   '--prefix',
1 verbose cli   'C:\\Users\\Administrator\\AppData\\Roaming\\npm-cache\\_npx\\15112',
1 verbose cli   '--loglevel',
1 verbose cli   'error',
1 verbose cli   '--json'
1 verbose cli ]
2 info using [email protected]
3 info using [email protected]
4 verbose npm-session fa778542bb7e8a5d
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 silly fetchPackageMetaData error for @manifoldco/swagger-to-ts@latest request to https://registry.npmjs.org/@manifoldco%2fswagger-to-ts failed, reason: connect ETIMEDOUT 104.16.21.35:443
8 timing stage:rollbackFailedOptional Completed in 0ms
9 timing stage:runTopLevelLifecycles Completed in 133652ms
10 verbose type system
11 verbose stack FetchError: request to https://registry.npmjs.org/@manifoldco%2fswagger-to-ts failed, reason: connect ETIMEDOUT 104.16.21.35:443
11 verbose stack     at ClientRequest.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-fetch-npm\src\index.js:68:14)
11 verbose stack     at ClientRequest.emit (events.js:310:20)
11 verbose stack     at TLSSocket.socketErrorListener (_http_client.js:426:9)
11 verbose stack     at TLSSocket.emit (events.js:310:20)
11 verbose stack     at emitErrorNT (internal/streams/destroy.js:92:8)
11 verbose stack     at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
11 verbose stack     at processTicksAndRejections (internal/process/task_queues.js:84:21)
12 verbose cwd D:\work\monitor\acs_server\doc\v1
13 verbose Windows_NT 10.0.18363
14 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "@manifoldco/swagger-to-ts@latest" "--global" "--prefix" "C:\\Users\\Administrator\\AppData\\Roaming\\npm-cache\\_npx\\15112" "--loglevel" "error" "--json"
15 verbose node v12.16.2
16 verbose npm  v6.14.4
17 error code ETIMEDOUT
18 error errno ETIMEDOUT
19 error network request to https://registry.npmjs.org/@manifoldco%2fswagger-to-ts failed, reason: connect ETIMEDOUT 104.16.21.35:443
20 error network This is a problem related to network connectivity.
20 error network In most cases you are behind a proxy or have bad network settings.
20 error network
20 error network If you are behind a proxy, please make sure that the
20 error network 'proxy' config is set properly.  See: 'npm help config'
21 verbose exit [ 1, true ]
```

Invalid character. SearchResult«Share»

The » character is causing me problems with this package:

The error message looks like:

Invalid character. (65:30)

export interface SearchResult«Share» {

Seems like the Typescript doesn't like the » symbol.

Cannot find name 'ref'

I have an OpenAPI json like that:

{
  "swagger": "2.0",
  "definitions": {
    "Messages": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/definitions/Message"
      }
    },
    "Message": {
      "type": "object",
      "properties": {
        "code": {
          "type": "integer"
        },
        "text": {
          "type": "string"
        }
      }
    }
  }
}

Which results in typescript:

export interface definitions {
  Messages: { [key: string]: ref }
  Message: { code?: number; text?: string }
}

It is not valid, because of ref. What is ref, and why it is not defined?

Cannot read property 'items' of undefined

Release 1.6.1 introduced a bug. When running the generator we get:

Error: TypeError: Cannot read property 'items' of undefined

Related code:

    if ($ref) {
      const [refName, refProperties] = getRef($ref);
      const convertedRefName = spacesToUnderscores(refName);

      if (refProperties.items && refProperties.items.$ref) {
        return getType(refProperties, refName);
      }

Works fine for us in 1.6.0 and 1.5.x.

Breaks when there are spaces in models names

My swagger.json is autogenerated and some of the models are "placeholder models" for irrelevant responses. By default, they contain spaces in their names i.e. "Model 1", "Model 2" etc.
Unfortunately, currently this is not handled by swagger-to-ts and the following error is thrown:

'{' expected. (2:24)
  1 | declare namespace OpenAPI {
> 2 | export interface Model 99 {

Suggested solution would be to replace spaces with _ or similar symbol.

Your .dependabot/config.yml contained invalid details

Dependabot encountered the following error when parsing your .dependabot/config.yml:

Automerging is not enabled for this account. You can enable it from the [account settings](https://app.dependabot.com/accounts/drwpow/settings) screen in your Dependabot dashboard.

Please update the config file to conform with Dependabot's specification using our docs and online validator.

Support `$ref`-type parameters, as well as components.parameters

Followup from #236.

We don’t yet support the following schema:

paths:
  '/some/path':
    get:
      parameters:
        - "$ref": "#/components/parameters/since"
        - "$ref": "#/components/parameters/per_page"
        - "$ref": "#/components/parameters/page"

Add support for $ref parameters as well as add the components.parameters object to the final response.

There’s an existing spec which illustrates this: tests/v3/specs/github.yaml.

swagger-to-ts considers components mandatory

When running swagger-to-ts on a specification without components, it immediately fails.
However, components is an optional part of the api schema and I can think of at least two scenarios where it would not be present:

  1. All schemas are inline in paths
  2. All schemas are put in separate file(s) such as schemas.yml

My specifications are quite large and I tend to split them up into separate files as per 2). This means that operations reference schemas such as {$ref: './schemas/foo.yml#/Foo'}.
Neither of these two approaches seem to work with swagger-to-ts since it requires components to be present (and, I assume, also ignores any schemas outside of components)?

  1. Would it be possible to invoke swagger-to-ts with a raw schema file, i.e., one that simply contains the schemas instead of requiring a full OpenAPI document?
  2. Would it be possible to properly support OpenAPI documents without components? It should be possible to fetch all externally referenced schemas using standard json-ref-parser etc?

Boolean array

With this swagger 2.0 schema:

MyObject:
  properties:
    myArray:
      type: "array"
      items:
        type: "boolean"

I am seeing this typescript output.

export interface MyObject {
  myArray?: MyObjectMyArray[];
}
export interface MyObjectMyArray {}

Expected output:

export interface MyObject {
  myArray?: boolean[];
}

Is this a known issue? Thanks in advance.

Types are not sent to stdout if `-o` is omitted

Steps to reproduce

npx @manifoldco/swagger-to-ts https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.json

What I expect to happen

See TS types printed to the screen as documented

What I observe

No TS types are shown

npx @manifoldco/swagger-to-ts https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.json
This library has been updated to 2.0 with improved generation. If you experience issues you can use the deprecated v1 with `npx @manifoldco/swagger-to-ts@1 …`
🤞 Loading spec from https://raw.githubusercontent.com/stripe/openapi/master/openapi/spec3.json…

Camelcase does not work with definitions / properties.

Here is a sample from my swagger.yml ...

definitions:
  business_object:
    type: object
    properties:
      id:
        type: string
      type:
        type: string
      attributes:
        "$ref": "#/definitions/business_attributes"
    required:
    - id
    - type
    - attributes
  business_attributes:
    type: object
    properties:
      id:
        type: integer
      title:
        type: string
    required:
    - id
    - title

Converting using:

npx @manifoldco/swagger-to-ts swagger.yaml  --wrapper "declare namespace OpenAPI" --output schema.d.ts --camelcase

The output is:

export interface businessObject {
    id: string;
    type: string;
    attributes: business_attributes;
  }
  export interface businessAttributes {
    id: number;
    title: string;
  }

businessObject -> attributes is still using the none camelCase name business_attributes

Expected results:

export interface businessObject {
    id: string;
    type: string;
    attributes: businessAttributes;
  }
  export interface businessAttributes {
    id: number;
    title: string;
  }

--prettier-config throws misleading error if custom config isn't JSON

When I used --prettier-config .prettierrc.js I've got an an error Prettier: couldn’t find '.prettierrc.js' in .... It turned out that the error is misleading, as the exception was about config not being a valid JSON.

In general, I see more and more people prefer .eslintrc.js and prettierrc.js over JSON, as JavaScript allows sharing configurations through import / export (and it's just nicer than JSON). Haven't found Prettier exposing any API for reading the config file, but it does state in the docs it uses cosmiconfig. It would be great if swagger-to-ts also used cosmiconfig to read any Prettier config file.

3.0 Support: “not?”

So the one 3.0 feature I’m thinking about not supporting is not. The reason is… I’m not sure how!

According to the definition:

The not keyword does not exactly combine schemas, but as all of the keywords mentioned above it helps you to modify your schemas and make them more specific.

The example given is:

    PetByType:
      type: object
      properties:
        pet_type:
          not:
            type: integer

While that can be done in JavaScript at runtime (typeof PetByType !== 'number'), I don’t think it’s possible in TypeScript to create a type that’s equal to anything but the given type.

Am I wrong? Is this possible?

Support for Dictionaries, HashMaps and Associative Arrays

Swagger has support for describing the types for HashMaps but currently swagger-to-ts only types these as object.

Swaggerdocs on this: https://swagger.io/docs/specification/data-models/dictionaries/

Example

Given this json:

{
  "swagger": "2.0",
  "info": {
    "description": "Api Documentation",
    "version": "1.0",
    "title": "Api Documentation",
    "termsOfService": "urn:tos",
    "contact": {},
    "license": {
      "name": "Apache 2.0",
      "url": "http://www.apache.org/licenses/LICENSE-2.0"
    }
  },
  "host": "localhost:8080",
  "basePath": "/",
  "definitions": {
    "CamundaFormField": {
      "type": "object",
      "required": ["displayType", "id", "label", "options", "responseType"],
      "properties": {
        "displayType": {
          "type": "string",
          "enum": ["radio", "date", "select", "textfield", "unknown"]
        },
        "id": { "type": "string" },
        "label": { "type": "string" },
        "options": {
          "type": "object",
          "additionalProperties": { "type": "string" }
        },
        "responseType": {
          "type": "string",
          "enum": [
            "booleanField",
            "stringField",
            "longField",
            "enumField",
            "dateField",
            "customTypeField",
            "unknownFieldType"
          ]
        },
        "value": { "type": "string" }
      },
      "title": "CamundaFormField"
    }
  }
}

Created from this Java class

@ApiModel("CamundaFormField")
public class CamundaFormFieldDto {

    @ApiModelProperty(required = true)
    private String id;

    @ApiModelProperty(required = true)
    private CamundaFormFieldTypeEnum responseType;

    @ApiModelProperty(required = true)
    private String label;

    @ApiModelProperty(required = true)
    private CamundaFormFieldDisplayTypeEnum displayType;

    @ApiModelProperty(required = true)
    private Map<String, String> options;

    private String value;
     /* ... more */ 
}

I get this result where the option property gets typed as object

export interface CamundaFormField {
  displayType: 'radio' | 'date' | 'select' | 'textfield' | 'unknown';
  id: string;
  label: string;
  options: object
  responseType:
    | 'booleanField'
    | 'stringField'
    | 'longField'
    | 'enumField'
    | 'dateField'
    | 'customTypeField'
    | 'unknownFieldType';
  value?: string;
}

The result I wanted in this case was:

export interface CamundaFormField {
  displayType: 'radio' | 'date' | 'select' | 'textfield' | 'unknown';
  id: string;
  label: string;
  options: Record<string, string>
  responseType:
    | 'booleanField'
    | 'stringField'
    | 'longField'
    | 'enumField'
    | 'dateField'
    | 'customTypeField'
    | 'unknownFieldType';
  value?: string;
}

Or if you want to support Typescript lower than 2.1:

export interface CamundaFormField {
  displayType: 'radio' | 'date' | 'select' | 'textfield' | 'unknown';
  id: string;
  label: string;
  options: {[key:string]: string}
  responseType:
    | 'booleanField'
    | 'stringField'
    | 'longField'
    | 'enumField'
    | 'dateField'
    | 'customTypeField'
    | 'unknownFieldType';
  value?: string;
}

I'm happy to provide a PR if you want. Great library!

Add option to change name of exported interface

A minor improvement that should be quite easy, but I've started using this library to automatically generate TS definitions for several APIs consumed by our client and because they're all exported as definitions it would require code consuming them to do import { definitions as XYZApi } from 'models/xyz.ts or something like it.

For now I'm solving this by using a regex to rename all instances of definitions to another word, so it would be very useful to have this as an option passed to the swaggerToTS function.

I might have some time to contribute this if it's something you're interested in adding.

Edit

I've just seen the No Wrappers section of the Readme and realised that it can also be solved that way! So feel free to close this if that's the preferred solution :)

Cannot re-export type definitions

I'm sure this is user-error, as I would think this is the most common use-case for this library.

I generate TS from spec, with output

 namespace MyLib {
    export interface ...
 }

Then compile & publish this as my own internal types definition to be included in other projects. However, I can't re-import - when importing the file I see "file is not a module"

To fix I manually add in an "export " at the start of the file:

export namespace MyLib { ... }

And this works.

Is this appropriate? Is there a better way to resolve this?

Bug: integer enum type is converted into string enum type wrongly

Hi, in my swagger.json file, I have this definition:

        "jobStatus": {
          "type": "integer",
          "format": "int32",
          "description": "0: created, 1: uploading, 2: uploading failed, 3: ingesting, 4: ingestion failed, 5: successful",
          "enum": [
            0,
            1,
            2,
            3,
            4,
            5
          ]
        },

But after I processed it by swagger-to-ts, I got something like this:

    jobStatus?: "0" | "1" | "2" | "3" | "4" | "5";

which is supposed to be

    jobStatus?: 0 | 1 | 2 | 3 | 4 | 5;

Could you kindly help to fix this bug? 😊

How about export all of the properties of definitions?

After upgrade to V2, definitions should be used by definitions['property']. It seems something odd because people prefer to using definitions in form of definitions.property or

import {property} from 'typing.ts'; 
let a:property;

Therefore, could you kindly export the type alias of these prosperities? Just by adding some codes like

export type property = definition['property'];

😊

All fields optional

We're trying this out with our own swagger.json file and seeing that all generated TypeScript fields are optional. Any idea how we can mark fields as required?

Cannot find name 'array'.

Generated: Swagger

export interface definitions {
  IFormFile: {
    contentType?: string;
    contentDisposition?: string;
    headers?: { [key: string]: array };
    length?: number;
    name?: string;
    fileName?: string;
  };
....

Results in


src/myapp/interfaces/myapp.ts:10:32 - error TS2304: Cannot find name 'array'.

10     headers?: { [key: string]: array };
                                  ~~~~~

Generated with

npx @manifoldco/swagger-to-ts https://myapp.com/v1/swagger.json --output myapp.ts

anyOf produces invalid output

Given the following spec (which is valid/correct per https://www.jsonschemavalidator.net)

{
  "openapi": "3.0",
  "components": {
    "schemas": {
      "scalar_map": {
        "type": "object",
        "additionalProperties": {
          "oneOf": [
            {
              "type": "string"
            },
            {
              "type": "number"
            },
            {
              "type": "boolean"
            }
          ]
        }
      }
    }
  }
}

swagger-to-ts outputs

/**
 * This file was auto-generated by swagger-to-ts.
 * Do not make direct changes to the file.
 */

export interface components {
  schemas: {
    scalar_map: { [key: string]: oneOf };
  };
}

which is malformed. The test case added in #201 works correctly, but it seems like maybe that's a unique/happy path? Seems like anyOf support still has some issues.

If you point me in the right direction I'd be happy to take a stab at fixing this, but at first pass not really sure where to start.

Create types from URL

As far as I see, this library doesn't support creating specs based on the remote resources yet. Reasoning would be that in microservices environment, there are many modules which expose spec on given URL, but not all of them publish it as a package to some internal package registries.

For example, one could imagine the following API:

npx @manifoldco/swagger-to-ts --url https://remote.com/specs.json --output schema.d.ts

Can I try introducing such a PR? How do we feel about such an improvement? How the ideal flow would look like?

support for x-nullable (and other x- props)

This library works great, but the swagger endpoints i'm using it against use the x-nullable property to indicate optional parameters (why it's doing that is another issue, don't ask).

I think it's easier to change the code generation than it is changing a lot of swagger defs, so I would really appreciate if this library had an option to support various x-flags.

What I'm thinking is an option to provide a mapper to the generator, something along the lines of


interface SwaggerProps {
 [string]: any //not sure how "unknown" props should be typed
}

interface Parameter {
  name: string;
  type: Type;
  required: boolean;
  //etc...
}


const mapper = (swaggerProps: SwaggerProps, parameter: Parameter): Parameter => {
    return {...parameter, required: !swaggerProps['x-nullable']};
}

swaggerToTS(cleanedSwaggerDefinition, {wrapper: false, mapper: mapper})

Does this sound like something you would consider including? I could try to implement it and submit a PR, but I would like a discussion up front in order to know it's something that will be considered for inclusion

TypeError: swaggerToTS is not a function

I ran this as described in the readme:

const swaggerToTS = require("@manifoldco/swagger-to-ts");
const { readFileSync, writeFileSync } = require("fs");
const input = JSON.parse(readFileSync("swagger.json", "utf8")); // Input can be any JS object (OpenAPI format)
// console.log(typeof swaggerToTS)
const output = swaggerToTS(input); 
writeFileSync("swagger-types.ts", output);

But I got the following error:

const output = swaggerToTS(input); 
               ^

TypeError: swaggerToTS is not a function

Two-dimensional arrays not handled?

Hi, it looks like two-dimensional arrays are not being handled, which I noticed in my own project but I've replicated the behavior here by modifying example/input.yaml:

  Provider:
    type: object
    properties:
      id: { $ref: '#/definitions/ID' }
      version: { type: integer, enum: [1] }
      type: { type: string, enum: ['provider'] }
      body: { $ref: '#/definitions/ProviderBody' }
      twoDimArray:
        type: array
        items:
          type: array
          items: { $ref: '#/definitions/ProviderBody' }
    additionalProperties: false
    required:
      - id
      - version
      - type
      - body

I would expect the generated type to be:

export interface Provider {
  id: string;
  version: 1;
  type: 'provider';
  body: ProviderBody;
  twoDimArray?: ProviderBody[][];
}

But it ends up generating this:

export interface Provider {
  id: string;
  version: 1;
  type: 'provider';
  body: ProviderBody;
  twoDimArray?: ProviderTwoDimArray[];
}
export interface ProviderTwoDimArray {}

Does this look like a valid bug?
Thanks

Converting error

What can we do with this error?

λ npx @manifoldco/swagger-to-ts swagger.json --namespace OpenAPI --output schema.ts
npx: installed 63 in 9.204s
Property or signature expected. (330:1)
  328 | export interface UserList {
  329 | // The index of the last item returned on the page.
> 330 | end-index?: number;
      | ^
  331 | // The list of items.
  332 | items?: User[];
  333 | // The maximum number of results that could be on the page.

Incorrect Output for Referencing Schemas from Other Schemas

When referencing schemas from other schema values, which I believe is allowed from what I've seen, the referenced schema is generated to { [key: string]: any } in the corresponding Typescript.

Here's an example swaggerfile:

  "components": {
     "schemas": {
         "userEmail": {
            "type": "string",
            "format": "email",
            "example": "[email protected]"
         },
         "CancelationStatus": {
            "type": "object",
            "required": [
               "userUUID",
               "userEmail",
               "dateTime",
               "status"
            ],
            "properties": {
               "userEmail": {
                  "schema": {
                     "$ref": "#/components/schemas/userEmail"
                  }
               },
               "status": {
                  "type": "string",
                  "enum": [
                     "Initiated",
                     "Complete",
                     "Error"
                  ],
                  "example": "Initiated."
               }
            }
         }
     }
  }

And the output TS:

schemas: {
    userEmail: string;
    CancelationStatus: {
      userEmail: { [key: string]: any };
      userUUID: { [key: string]: any };
      dateTime: { [key: string]: any };
      status: "Initiated" | "Complete" | "Error";
    };
}

Unknown option --output

I installed the latest from npm and followed the examples, without success (it looks like this page is for the upcoming 2.0 release already?).

$ npx @manifoldco/swagger-to-ts spec.yml --output schema.ts
error: unknown option '--output'

$ npx @manifoldco/swagger-to-ts spec.yml
[INFO]: 下载 Swagger..., apiUrl: 
[ERROR]: 下载 Swagger 失败
Error: Expected a file path, URL, or object. Got undefined

Remote $ref used like in the Swagger documentation does not work

As seen here: https://swagger.io/docs/specification/using-ref/ JSON Reference supports remote references with an element selector.

Using this test setup:

index.yaml

openapi: 3.0.3

info:
  version: '1.0'
  title: Test

paths:
  /:
    summary: Test

components:
  schemas:
    test:
      $ref: 'test.yaml#/test'

test.yaml

test:
  type: object
  properties:
    id:
      type: integer

I get the following error:

✨ swagger-to-ts 2.0
This library has been updated to 2.0 with improved generation. If you experience issues you can use the deprecated v1 with `npx @manifoldco/swagger-to-ts@1 …`
🤞 Loading spec from index.yaml…
SyntaxError: Invalid character. (9:23)
   7 | export interface components {
   8 |     schemas: {
>  9 |     "test": test.yaml#["test"];
     |                       ^
  10 | 
  11 |   }
  12 |     
    at e (/home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/node_modules/prettier/parser-typescript.js:1:322)
    at Object.parse (/home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/node_modules/prettier/parser-typescript.js:14:2893509)
    at Object.parse (/home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/node_modules/prettier/index.js:13565:19)
    at coreFormat (/home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/node_modules/prettier/index.js:14841:25)
    at format (/home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/node_modules/prettier/index.js:15063:14)
    at formatWithCursor (/home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/node_modules/prettier/index.js:15080:12)
    at /home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/node_modules/prettier/index.js:54672:12
    at Object.format (/home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/node_modules/prettier/index.js:54692:12)
    at swaggerToTS (/home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/dist-node/index.js:394:19)
    at /home/tester/.npm/_npx/21480/lib/node_modules/@manifoldco/swagger-to-ts/bin/cli.js:49:18

Add license

I tested this library and it would work like a charm for our project, but I noticed that license is missing. Could it be added that we could utilize it?

Thank you in advance!

Missing array types

Some types are missing in Typescript output.
Example swagger 2.0 input:

definitions:
  MyObject:
    properties:
      foo:
        $ref: "#/definitions/FloatArray
  FloatArray:
    type: "array"
    items:
      type: "number"
      format: "float"

Output:

export interface MyObject {
  foo?: FloatArray;
}

The FloatArray definition is missing.

Support 'additionalProperties'

https://swagger.io/docs/specification/data-models/dictionaries/

"ItemDto": {
  ...
},
"CollectionDto": {
    "type": "object",
    "properties": {
      "tables": {
        "type": "object",
        "additionalProperties": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/ItemDto"
          }
        }
      }
    },
    "title": "CollectionDto"
},

This outputs an invalid type interface like this:

CollectionDto: { tables?: { [key: string]: array } };

Whereas it should be:

CollectionDto: { tables?: { [key: string]: definitions["ItemDto"][] } };

Enum value with single quote causes syntax error

Hello,

I've encountered a bug where if an enum value contains a single quote, a syntax error is thrown.

            "enum": [
              "",
              "Cash",
              "Insurance",
              "Insurance Out of Network",
              "Auto Accident",
              "Worker's Comp"
            ],

https://app.drchrono.com/openapi-schema has a download link for the schema which contains this issue.

Loading spec from .\openapi-schema.json…
SyntaxError: ')' expected. (1796:123)
  1794 |   * One of `""`, `"Cash"`, `"Insurance"`, `"Insurance Out of Network"`, `"Auto Accident"` or `"Worker's Comp"`.<br>**Note:** Patient must already have either `primary_insurance` or `secondary_insurance` or new `primary_insurance` or `secondary_insurance` is passed in request if `Insurance`, `Auto Accident` or `Worker's Comp` payment profiles are chosen.
  1795 |   */
> 1796 | "patient_payment_profile"?: ('') | ('Cash') | ('Insurance') | ('Insurance Out of Network') | ('Auto Accident') | ('Worker's Comp');

Not following nested refs

I found that in swagger files having deep nested refs swagger-to-ts fails to recursively follow definitions and generates wrong schemas as a result.

For example, swagger generates following incorrect schema (see input swagger.json below):

export interface Metadata {
  status?: string;
  title: string;
}

When it should've resulted in union type if it followed all refs to the end (possibly creating interfaces for Status and Title as well along the way):

export interface Metadata {
  status?: 'editing' | 'pending' | 'accepted' | 'rejected';
  title: string;
}

From what I could gather from the source code, string type is a default of a sort, so if a ref actually leads to a non-string type, schema type will default to string.

Minimal reproducible example swagger.json:

{
    "swagger": "2.0",
    "info": {
        "contact": {
            "email": "",
            "name": ""
        },
        "version": "",
        "title": ""
    },
    "definitions": {
        "Status": {
            "type": "string",
            "enum": [
                "editing",
                "pending",
                "accepted",
                "rejected"
            ]
        },
        "Title": {
            "type": "string"
        },
        "Metadata": {
            "required": [
                "title"
            ],
            "type": "object",
            "properties": {
                "status": {
                    "$ref": "#/definitions/Status"
                },
                "title": {
                    "$ref": "#/definitions/Title"
                }
            }
        }
    },
    "paths": {
        "/test": {
            "get": {
                "summary": "",
                "responses": {
                    "200": {
                        "schema": {
                            "required": [
                                "mydata"
                            ],
                            "type": "object",
                            "properties": {
                                "mydata": {
                                    "items": {
                                        "minItems": 1,
                                        "items": [
                                            {
                                                "$ref": "#/definitions/Metadata"
                                            }
                                        ],
                                        "maxItems": 1,
                                        "type": "array"
                                    },
                                    "type": "array"
                                }
                            }
                        },
                        "description": ""
                    }
                },
                "produces": [
                    "application/json;charset=utf-8"
                ],
                "parameters": [
                    {
                        "required": true,
                        "in": "query",
                        "name": "cookie-auth"
                    }
                ],
                "tags": [
                    "test"
                ]
            }
        }
    },
    "tags": [
        {
            "name": "test",
            "description": ""
        }
    ]
}

Export broken on Windows

Again, what seems to be a pebkac error, but...

In my latest update/install, type generation failed completely. I traced the error to the following line: https://github.com/manifoldco/swagger-to-ts/blob/c24b3efaf466cb6e60961476c3930e963cb3e880/src/swagger-2.ts#L226

I'm not sure where that type should come from, but I don't have it on my imported thingies. Here is my complete script:

const { readFileSync, writeFileSync } = require('fs');
const swaggerToTS = require('@manifoldco/swagger-to-ts').default;
const yaml = require('js-yaml');
const path = require('path');

const yaml_path = ...;
file = readFileSync(yaml_path, 'utf8');
const input = yaml.safeLoad(file); // Input be any JS object (OpenAPI format)
const output = swaggerToTS(input, { 
    wrapper: false,
    injectWarning: true,
  }); // Outputs TypeScript defs as a string (to be parsed, or written to a file)

I fixed it by replacing with
if (typeof entry[1] === 'object') {

However I haven't tested vs your repo, so not sure if this works in places where the old code worked. My deps are as shown here:

"devDependencies": {
    "@manifoldco/swagger-to-ts": "^1.1.1",
    "js-yaml": "^3.13.0"
  },

Publish new release

A number of new features have been added since the last release.

Alternatively, make changes so that it can be installed directly from the git repo

Cannot convert undefined or null to object

What version of OpenAPI is supported? Running npx @manifoldco/swagger-to-ts test.yaml --output schema.d.ts on

openapi: 3.0.0
info:
  version: "0.2"
  title: test
paths:
  /test:
    get:
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Response"
        "201":
          content:
            application/json:
              schema:
                $ref: "#/components/platform/schemas/Nope"
components:
  schemas:
    Response:
      type: object
      properties:
        type: array
        items:
          type: string
  platform:
    schemas:
      Nope:
        type: object
        required:
          - type
        properties:
          type:
            type: string

results in Cannot convert undefined or null to object.

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.