question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Types with additionalProperties are not generated correctly

See original GitHub issue

Hi, i just updated to version 2.0.0 and now my types with additionalProperties do not get generated correctly. Here is an example based on your tests for additionalProperties. Within the tests of swagger-typescript-codegen it seems to work, but in my project and my test project it doesn’t. What am i doing wrong?

swagger.json:

{
  "swagger": "2.0",
  "info": {
    "version": "0.0.1",
    "title": "your title"
  },
  "paths": {
    "/persons": {
      "get": {
        "operationId": "get_person",
        "description": "Gets `Person` object.",
        "responses": {
          "200": {
            "description": "empty schema"
          }
        }
      }
    }
  },
  "definitions": {
    "some_def": {
      "type": "object",
      "properties": {
        "some_def": {
          "type": "string"
        }
      },
      "additionalProperties": false
    },
    "test_add_props_01": {
      "type": "object",
      "properties": {
        "some_prop": {
          "type": "string"
        }
      }
    },
    "test_add_props_02": {
      "type": "object",
      "properties": {
        "some_prop": {
          "type": "string"
        }
      },
      "additionalProperties": false
    },
    "test_add_props_03": {
      "type": "object",
      "properties": {
        "some_prop": {
          "type": "string"
        }
      },
      "additionalProperties": true
    },
    "test_add_props_04": {
      "type": "object",
      "properties": {
        "some_prop": {
          "type": "string"
        }
      },
      "additionalProperties": {
        "type": "string"
      }
    },
    "test_add_props_05": {
      "type": "object",
      "properties": {
        "some_prop": {
          "type": "string"
        }
      },
      "additionalProperties": {
        "type": "object",
        "properties": {
          "nested_prop": {
            "type": "string"
          }
        }
      }
    },
    "test_add_props_06": {
      "type": "object",
      "properties": {
        "some_prop": {
          "type": "string"
        }
      },
      "additionalProperties": {
        "$ref": "#/definitions/some_def"
      }
    },
    "test_add_props_07": {
      "type": "object"
    },
    "test_add_props_08": {
      "type": "object",
      "additionalProperties": false
    },
    "test_add_props_09": {
      "type": "object",
      "additionalProperties": true
    },
    "test_add_props_10": {
      "type": "object",
      "additionalProperties": {
        "type": "string"
      }
    },
    "test_add_props_11": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "properties": {
          "nested_prop": {
            "type": "string"
          }
        }
      }
    },
    "test_add_props_12": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/definitions/some_def"
      }
    }
  }
}

output.ts:

// tslint:disable

import * as request from "superagent";
import {
    SuperAgentStatic,
    SuperAgentRequest,
    Response
} from "superagent";

export type RequestHeaders = {
    [header: string]: string;
}
export type RequestHeadersHandler = (headers: RequestHeaders) => RequestHeaders;

export type ConfigureAgentHandler = (agent: SuperAgentStatic) => SuperAgentStatic;

export type ConfigureRequestHandler = (agent: SuperAgentRequest) => SuperAgentRequest;

export type CallbackHandler = (err: any, res ? : request.Response) => void;

export type some_def = {
    'some_def' ? : string;
};

export type test_add_props_01 = {
    'some_prop' ? : string;
};

export type test_add_props_02 = {
    'some_prop' ? : string;
};

export type test_add_props_03 = ;

export type test_add_props_04 = ;

export type test_add_props_05 = ;

export type test_add_props_06 = ;

export type test_add_props_07 = {};

export type test_add_props_08 = {};

export type test_add_props_09 = ;

export type test_add_props_10 = ;

export type test_add_props_11 = ;

export type test_add_props_12 = ;

export type Logger = {
    log: (line: string) => any
};

export interface ResponseWithBody < S extends number, T > extends Response {
    status: S;
    body: T;
}

export type QueryParameters = {
    [param: string]: any
};

export interface CommonRequestOptions {
    $queryParameters ? : QueryParameters;
    $domain ? : string;
    $path ? : string | ((path: string) => string);
    $retries ? : number; // number of retries; see: https://github.com/visionmedia/superagent/blob/master/docs/index.md#retrying-requests
    $timeout ? : number; // request timeout in milliseconds; see: https://github.com/visionmedia/superagent/blob/master/docs/index.md#timeouts
    $deadline ? : number; // request deadline in milliseconds; see: https://github.com/visionmedia/superagent/blob/master/docs/index.md#timeouts
}

/**
 * 
 * @class TestApi
 * @param {(string)} [domainOrOptions] - The project domain.
 */
export class TestApi {

    private domain: string = "";
    private errorHandlers: CallbackHandler[] = [];
    private requestHeadersHandler ? : RequestHeadersHandler;
    private configureAgentHandler ? : ConfigureAgentHandler;
    private configureRequestHandler ? : ConfigureRequestHandler;

    constructor(domain ? : string, private logger ? : Logger) {
        if (domain) {
            this.domain = domain;
        }
    }

    getDomain() {
        return this.domain;
    }

    addErrorHandler(handler: CallbackHandler) {
        this.errorHandlers.push(handler);
    }

    setRequestHeadersHandler(handler: RequestHeadersHandler) {
        this.requestHeadersHandler = handler;
    }

    setConfigureAgentHandler(handler: ConfigureAgentHandler) {
        this.configureAgentHandler = handler;
    }

    setConfigureRequestHandler(handler: ConfigureRequestHandler) {
        this.configureRequestHandler = handler;
    }

    private request(method: string, url: string, body: any, headers: RequestHeaders, queryParameters: QueryParameters, form: any, reject: CallbackHandler, resolve: CallbackHandler, opts: CommonRequestOptions) {
        if (this.logger) {
            this.logger.log(`Call ${method} ${url}`);
        }

        const agent = this.configureAgentHandler ?
            this.configureAgentHandler(request.default) :
            request.default;

        let req = agent(method, url);
        if (this.configureRequestHandler) {
            req = this.configureRequestHandler(req);
        }

        req = req.query(queryParameters);

        if (body) {
            req.send(body);

            if (typeof(body) === 'object' && !(body.constructor.name === 'Buffer')) {
                headers['Content-Type'] = 'application/json';
            }
        }

        if (Object.keys(form).length > 0) {
            req.type('form');
            req.send(form);
        }

        if (this.requestHeadersHandler) {
            headers = this.requestHeadersHandler({
                ...headers
            });
        }

        req.set(headers);

        if (opts.$retries && opts.$retries > 0) {
            req.retry(opts.$retries);
        }

        if (opts.$timeout && opts.$timeout > 0 || opts.$deadline && opts.$deadline > 0) {
            req.timeout({
                deadline: opts.$deadline,
                response: opts.$timeout
            });
        }

        req.end((error, response) => {
            // an error will also be emitted for a 4xx and 5xx status code
            // the error object will then have error.status and error.response fields
            // see superagent error handling: https://github.com/visionmedia/superagent/blob/master/docs/index.md#error-handling
            if (error) {
                reject(error);
                this.errorHandlers.forEach(handler => handler(error));
            } else {
                resolve(response);
            }
        });
    }

    get_personURL(parameters: {} & CommonRequestOptions): string {
        let queryParameters: QueryParameters = {};
        const domain = parameters.$domain ? parameters.$domain : this.domain;
        let path = '/persons';
        if (parameters.$path) {
            path = (typeof(parameters.$path) === 'function') ? parameters.$path(path) : parameters.$path;
        }

        if (parameters.$queryParameters) {
            queryParameters = {
                ...queryParameters,
                ...parameters.$queryParameters
            };
        }

        let keys = Object.keys(queryParameters);
        return domain + path + (keys.length > 0 ? '?' + (keys.map(key => key + '=' + encodeURIComponent(queryParameters[key])).join('&')) : '');
    }

    /**
     * Gets `Person` object.
     * @method
     * @name TestApi#get_person
     */
    get_person(parameters: {} & CommonRequestOptions): Promise < ResponseWithBody < 200, void >> {
        const domain = parameters.$domain ? parameters.$domain : this.domain;
        let path = '/persons';
        if (parameters.$path) {
            path = (typeof(parameters.$path) === 'function') ? parameters.$path(path) : parameters.$path;
        }

        let body: any;
        let queryParameters: QueryParameters = {};
        let headers: RequestHeaders = {};
        let form: any = {};
        return new Promise((resolve, reject) => {

            if (parameters.$queryParameters) {
                queryParameters = {
                    ...queryParameters,
                    ...parameters.$queryParameters
                };
            }

            this.request('GET', domain + path, body, headers, queryParameters, form, reject, resolve, parameters);
        });
    }

}

export default TestApi;

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
devpiecommented, Aug 21, 2019

Yes it works again. You are the best. Thank you very much. 😄

1reaction
mtennoecommented, Aug 15, 2019

Hi!

There was a recent PR that improved the way additionalProperties work, see #86. Are you using a custom mustache template, or the default ones?

@Kosta-Github - Were you able to compile a migration guide for this?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Swagger schema with additionalProperties fails - Stack Overflow
Essentially, while your original schema is perfectly valid according to the Swagger specification, the swagger-core Java library won't process it correctly.
Read more >
Schema allows additional properties
If you are using combining operations for primitives with no properties, additionalProperties can be false and the combining operations still work. If you...
Read more >
juniper - npm
Juniper does not provide any JSON Schema validation. ... of the logic resolves around generating correct types associated with each schema.
Read more >
OpenAPI Specification - Version 3.0.3 - Swagger
Types that are not accompanied by a format property follow the type definition in the JSON Schema. Tools that do not recognize a...
Read more >
Modifying data during validation - Ajv JSON schema validator
removeAdditional - to remove properties not defined in the schema object. ... type keywords, both to pass the validation and to use the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found