From ca373e853c6ba8eb0c6f606ef1d3df2efc55ad46 Mon Sep 17 00:00:00 2001 From: ishibashi_y Date: Thu, 13 Jun 2019 18:44:43 +0900 Subject: [PATCH 1/3] fix: SecuritySchemeProps --- package.json | 3 ++- src/index.ts | 10 +++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 6c2daab..6a8fbb4 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "build": "tsc", "test": "jest", "lint": "prettier --check '{src,tests}/**/*.{js,ts}'", + "lint:format": "prettier --write '{src,tests}/**/*.{js,ts}'", "watch": "tsc -w", "generate:doc": "yarn typedoc --out docs", "eslint": "eslint -c ./.eslintrc.json 'src/**/*.{ts,tsx}'" @@ -47,7 +48,7 @@ "types": "./dist/index.d.ts", "husky": { "hooks": { - "pre-commit": "pretty-quick --staged" + "pre-commit": "pretty-quick --staged && yarn lint:format" } } } diff --git a/src/index.ts b/src/index.ts index 26722bc..c84d37c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -561,7 +561,7 @@ export class SecurityScheme { } static basic( - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ type: "http", @@ -573,7 +573,7 @@ export class SecurityScheme { static apiKey( in_: "query" | "header" | "cookie", name: string, - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ type: "apiKey", @@ -584,7 +584,7 @@ export class SecurityScheme { } static bearer( - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ type: "http", @@ -595,7 +595,7 @@ export class SecurityScheme { static openId( openIdConnectUrl: string, - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ type: "openIdConnect", @@ -606,7 +606,7 @@ export class SecurityScheme { static oauth2( flows: OAuthFlowsObject, - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ type: "oauth2", From 4d1b43c78be55ccb3ea050a04e1a3e0b6e185da9 Mon Sep 17 00:00:00 2001 From: ishibashi_y Date: Thu, 13 Jun 2019 18:45:21 +0900 Subject: [PATCH 2/3] refactor: we can Omit now --- src/index.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index c84d37c..e93da50 100644 --- a/src/index.ts +++ b/src/index.ts @@ -249,9 +249,6 @@ export interface ResponseProps { description: string; } -/** @private */ -type Omit = Pick>; - /** @private */ type HeaderProps = Omit; From 54cbdfa2cfd5a8d8c5d825fd541d5a457f57e5bb Mon Sep 17 00:00:00 2001 From: ishibashi_y Date: Thu, 13 Jun 2019 19:11:17 +0900 Subject: [PATCH 3/3] chore: set single-quote and format --- .prettierrc | 3 + jest.config.js | 21 ++-- package.json | 3 +- src/index.ts | 153 +++++++++++++++--------------- src/plugins/serverless.ts | 24 ++--- tests/petstore.spec.ts | 88 ++++++++--------- tests/security.test.ts | 30 +++--- tests/swagger.spec.ts | 195 +++++++++++++++++++++----------------- 8 files changed, 272 insertions(+), 245 deletions(-) create mode 100644 .prettierrc diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..92cde39 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,3 @@ +{ + "singleQuote": true +} \ No newline at end of file diff --git a/jest.config.js b/jest.config.js index c2db5e1..325372d 100644 --- a/jest.config.js +++ b/jest.config.js @@ -55,7 +55,11 @@ module.exports = { // globalTeardown: null, // A set of global variables that need to be available in all test environments - // globals: {}, + globals: { + 'ts-jest': { + diagnostics: false + } + }, // An array of directory names to be searched recursively up from the requiring module's location // moduleDirectories: [ @@ -63,10 +67,7 @@ module.exports = { // ], // An array of file extensions your modules use - moduleFileExtensions: [ - "js", - "ts", - ], + moduleFileExtensions: ['js', 'ts'], // A map from regular expressions to module names that allow to stub out resources with a single module // moduleNameMapper: {}, @@ -122,7 +123,7 @@ module.exports = { // snapshotSerializers: [], // The test environment that will be used for testing - testEnvironment: "node", + testEnvironment: 'node', // Options that will be passed to the testEnvironment // testEnvironmentOptions: {}, @@ -132,8 +133,8 @@ module.exports = { // The glob patterns Jest uses to detect test files testMatch: [ - // "**/__tests__/**/*.js?(x)", - "**/?(*.)+(spec|test).(js|ts)?(x)" + // "**/__tests__/**/*.js?(x)", + '**/?(*.)+(spec|test).(js|ts)?(x)' ], // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped @@ -158,8 +159,8 @@ module.exports = { // A map from regular expressions to paths to transformers transform: { - "^.+\\.tsx?$": "ts-jest" - }, + '^.+\\.tsx?$': 'ts-jest' + } // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation // transformIgnorePatterns: [ diff --git a/package.json b/package.json index 6a8fbb4..6c2daab 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,6 @@ "build": "tsc", "test": "jest", "lint": "prettier --check '{src,tests}/**/*.{js,ts}'", - "lint:format": "prettier --write '{src,tests}/**/*.{js,ts}'", "watch": "tsc -w", "generate:doc": "yarn typedoc --out docs", "eslint": "eslint -c ./.eslintrc.json 'src/**/*.{ts,tsx}'" @@ -48,7 +47,7 @@ "types": "./dist/index.d.ts", "husky": { "hooks": { - "pre-commit": "pretty-quick --staged && yarn lint:format" + "pre-commit": "pretty-quick --staged" } } } diff --git a/src/index.ts b/src/index.ts index e93da50..3023dfe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ -import * as fs from "fs"; -import * as yaml from "js-yaml"; -import * as commandpost from "commandpost"; -import * as express from "express"; +import * as fs from 'fs'; +import * as yaml from 'js-yaml'; +import * as commandpost from 'commandpost'; +import * as express from 'express'; /** * @private @@ -21,24 +21,24 @@ function mapToObj( export type SchemaInput = SchemaProps | Ref; export enum SchemaType { - INTEGER = "integer", - NUMBER = "number", - STRING = "string", - BOOLEAN = "boolean", - OBJECT = "object", - ARRAY = "array" + INTEGER = 'integer', + NUMBER = 'number', + STRING = 'string', + BOOLEAN = 'boolean', + OBJECT = 'object', + ARRAY = 'array' } export enum SchemaFormat { - INT32 = "int32", - INT64 = "int64", - FLOAT = "float", - DOUBLE = "double", - BYTE = "byte", - BINARY = "binary", - DATE = "date", - DATETIME = "datetime", - PASSWORD = "password" + INT32 = 'int32', + INT64 = 'int64', + FLOAT = 'float', + DOUBLE = 'double', + BYTE = 'byte', + BINARY = 'binary', + DATE = 'date', + DATETIME = 'datetime', + PASSWORD = 'password' } // The recursive element SchemaInput should be abstracted as type parameter @@ -62,6 +62,7 @@ export interface SchemaProps { not?: SchemaInput; additionalProperties?: boolean; default?: any; + nullable?: boolean; } /** @@ -196,7 +197,7 @@ export class Schema { } else if (props.type === SchemaType.INTEGER) { return 0; } else if (props.type === SchemaType.STRING) { - return ""; + return ''; } else if (props.type === SchemaType.ARRAY) { return [new Schema(props.items).example()]; } else { @@ -250,7 +251,7 @@ export interface ResponseProps { } /** @private */ -type HeaderProps = Omit; +type HeaderProps = Omit; export interface EncodingProps { contentType?: string; @@ -304,20 +305,20 @@ export class Response { } export enum ParameterLocation { - PATH = "path", - HEADER = "header", - QUERY = "query", - COOKIE = "cookie" + PATH = 'path', + HEADER = 'header', + QUERY = 'query', + COOKIE = 'cookie' } export enum ParameterStyle { - MATRIX = "matrix", - LABEL = "label", - FORM = "form", - SIMPLE = "simple", - SPACEDELIMITED = "spaceDelimited", - PIPEDELIMITED = "pipeDelimited", - deepObject = "deepObject" + MATRIX = 'matrix', + LABEL = 'label', + FORM = 'form', + SIMPLE = 'simple', + SPACEDELIMITED = 'spaceDelimited', + PIPEDELIMITED = 'pipeDelimited', + deepObject = 'deepObject' } export interface ParameterProps { @@ -409,7 +410,7 @@ export class Path { }, this); } - addRequestBody(requestBody: RequestBody): Path<"request_body"> { + addRequestBody(requestBody: RequestBody): Path<'request_body'> { this.requestBody = requestBody; return this; } @@ -438,7 +439,7 @@ export class Ref { } example(): any { - throw new Error("not implemented yet"); + throw new Error('not implemented yet'); } } @@ -500,26 +501,26 @@ export interface ServerProps { const literal = (v: V) => v; export const HttpMethod = { - GET: literal("get"), - PUT: literal("put"), - POST: literal("post"), - DELETE: literal("delete"), - OPTIONS: literal("options"), - HEAD: literal("head"), - PATCH: literal("patch"), - TRACE: literal("trace") + GET: literal('get'), + PUT: literal('put'), + POST: literal('post'), + DELETE: literal('delete'), + OPTIONS: literal('options'), + HEAD: literal('head'), + PATCH: literal('patch'), + TRACE: literal('trace') }; export type HttpMethod = (typeof HttpMethod)[keyof typeof HttpMethod]; export interface OAuthFlowsObject { implicit?: Pick< OAuthFlowObject, - "authorizationUrl" | "refreshUrl" | "scopes" + 'authorizationUrl' | 'refreshUrl' | 'scopes' >; - password?: Pick; + password?: Pick; clientCredentials?: Pick< OAuthFlowObject, - "tokenUrl" | "refreshUrl" | "scopes" + 'tokenUrl' | 'refreshUrl' | 'scopes' >; authorizationCode?: OAuthFlowObject; } @@ -532,12 +533,12 @@ export interface OAuthFlowObject { } export type SecuritySchemeProps = { - type: "apiKey" | "http" | "oauth2" | "openIdConnect"; + type: 'apiKey' | 'http' | 'oauth2' | 'openIdConnect'; description?: string; } & ( | { name: string; - in: "query" | "header" | "cookie"; + in: 'query' | 'header' | 'cookie'; } | { scheme: string; @@ -558,22 +559,22 @@ export class SecurityScheme { } static basic( - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ - type: "http", - scheme: "basic", + type: 'http', + scheme: 'basic', ...overrideProps }); } static apiKey( - in_: "query" | "header" | "cookie", + in_: 'query' | 'header' | 'cookie', name: string, - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ - type: "apiKey", + type: 'apiKey', in: in_, name: name, ...overrideProps @@ -581,21 +582,21 @@ export class SecurityScheme { } static bearer( - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ - type: "http", - scheme: "bearer", + type: 'http', + scheme: 'bearer', ...overrideProps }); } static openId( openIdConnectUrl: string, - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ - type: "openIdConnect", + type: 'openIdConnect', openIdConnectUrl, ...overrideProps }); @@ -603,10 +604,10 @@ export class SecurityScheme { static oauth2( flows: OAuthFlowsObject, - overrideProps?: Omit + overrideProps?: Omit ): SecurityScheme { return new SecurityScheme({ - type: "oauth2", + type: 'oauth2', flows, ...overrideProps }); @@ -646,7 +647,7 @@ export interface SwaggerOptions { * @class The core class of swagger-devkit. See `SwaggerOptions` for constructor options. */ export class Swagger { - private outfile: string = "openapi.yml"; + private outfile: string = 'openapi.yml'; private object: any = {}; private paths: Map>> = new Map(); private components: Map = new Map(); @@ -654,12 +655,12 @@ export class Swagger { private securityComponent: { [name: string]: SecurityScheme | object }; private command = commandpost - .create<{ mockServer: boolean; dryRun: boolean }, {}>("swagger-devkit") - .version(require("../package.json").version, "-v, --version") - .option("-s, --mock-server", "Start the mock server") + .create<{ mockServer: boolean; dryRun: boolean }, {}>('swagger-devkit') + .version(require('../package.json').version, '-v, --version') + .option('-s, --mock-server', 'Start the mock server') .option( - "--dry-run", - "Dry-run; not actually run the command but show the result" + '--dry-run', + 'Dry-run; not actually run the command but show the result' ) .action((opts, _args) => { this.evaluate(opts); @@ -667,12 +668,12 @@ export class Swagger { constructor(options?: SwaggerOptions) { if (options && options.openapi) { - this.addObject("openapi", options.openapi); + this.addObject('openapi', options.openapi); } else { - this.addObject("openapi", "3.0.0"); + this.addObject('openapi', '3.0.0'); } - this.addObject("paths", {}); + this.addObject('paths', {}); if (options && options.plugins) { this.plugins = options.plugins; @@ -711,14 +712,14 @@ export class Swagger { * Adds `info` section */ addInfo(props: InfoProps) { - this.addObject("info", props); + this.addObject('info', props); } /** * Adds `servers` section */ addServers(props: Array) { - this.addObject("servers", props); + this.addObject('servers', props); } /** @@ -730,8 +731,8 @@ export class Swagger { */ addPath( path: string, - method: method extends "request_body" - ? "put" | "post" | "delete" | "patch" + method: method extends 'request_body' + ? 'put' | 'post' | 'delete' | 'patch' : HttpMethod, object: Path, pluginOptions?: { [pluginName: string]: object } @@ -761,7 +762,7 @@ export class Swagger { pathObject[path][method] = object.render(); }); }); - this.object["paths"] = pathObject; + this.object['paths'] = pathObject; return Object.assign(this.object, { paths: pathObject, @@ -822,7 +823,7 @@ export class Swagger { */ startMockServer(options?: { interactionUrl?: string; port?: number }) { if (!options) options = {}; - if (!options.interactionUrl) options.interactionUrl = "/interactions"; + if (!options.interactionUrl) options.interactionUrl = '/interactions'; if (!options.port) options.port = 3000; const app = express(); @@ -835,7 +836,7 @@ export class Swagger { const statusCode = pathObject.responses.keys().next().value; const responseBody = pathObject.responses .get(statusCode) - .content.get("application/json") + .content.get('application/json') .example(); res.status(parseInt(statusCode, 10)).json(responseBody); diff --git a/src/plugins/serverless.ts b/src/plugins/serverless.ts index 55fa4de..a5a3ff6 100644 --- a/src/plugins/serverless.ts +++ b/src/plugins/serverless.ts @@ -1,5 +1,5 @@ -import * as devkit from "../index"; -import * as yaml from "js-yaml"; +import * as devkit from '../index'; +import * as yaml from 'js-yaml'; export interface ServerlessOptions { filepath: string; @@ -41,7 +41,7 @@ export class ServerlessPlugin extends devkit.Plugin { if ( this.options.aggregateByFunctionName && - (!pathOptions || !pathOptions["functionName"]) + (!pathOptions || !pathOptions['functionName']) ) { throw new Error( `Specify 'functionName' under aggregateByFunctionName mode for the path: ${method} ${url}` @@ -49,26 +49,26 @@ export class ServerlessPlugin extends devkit.Plugin { } const name = this.options.aggregateByFunctionName - ? pathOptions["functionName"] + ? pathOptions['functionName'] : `${url - .split("{") - .join("_") - .split("}") - .join("_") - .split("/") - .join("")}_${method}`; + .split('{') + .join('_') + .split('}') + .join('_') + .split('/') + .join('')}_${method}`; if (!object[name]) { object[name] = { events: [] }; } - object[name]["events"].push({ + object[name]['events'].push({ http: Object.assign( { path: url, method: method }, - pathOptions["apigateway"] + pathOptions['apigateway'] ) }); }); diff --git a/tests/petstore.spec.ts b/tests/petstore.spec.ts index dd5cd4c..6c6f94e 100644 --- a/tests/petstore.spec.ts +++ b/tests/petstore.spec.ts @@ -1,5 +1,5 @@ -import * as devkit from "../src/index"; -import * as yaml from "js-yaml"; +import * as devkit from '../src/index'; +import * as yaml from 'js-yaml'; const petstoreYaml = ` openapi: "3.0.0" @@ -112,18 +112,18 @@ components: message: type: string`; -test("test petstore.yml", () => { +test('test petstore.yml', () => { const swagger = new devkit.Swagger(); swagger.addInfo({ - version: "1.0.0", - title: "Swagger Petstore", - license: { name: "MIT" } + version: '1.0.0', + title: 'Swagger Petstore', + license: { name: 'MIT' } }); - swagger.addServers([{ url: "http://petstore.swagger.io/v1" }]); + swagger.addServers([{ url: 'http://petstore.swagger.io/v1' }]); - const petObject = new devkit.Component(swagger, "Pet", { - required: ["id", "name"], + const petObject = new devkit.Component(swagger, 'Pet', { + required: ['id', 'name'], properties: { id: devkit.Schema.int64(), name: devkit.Schema.string(), @@ -132,11 +132,11 @@ test("test petstore.yml", () => { }); const petsObject = new devkit.Component( swagger, - "Pets", + 'Pets', devkit.Schema.array(petObject) ); - const errorObject = new devkit.Component(swagger, "Error", { - required: ["code", "message"], + const errorObject = new devkit.Component(swagger, 'Error', { + required: ['code', 'message'], properties: { code: devkit.Schema.int32(), message: devkit.Schema.string() @@ -144,72 +144,72 @@ test("test petstore.yml", () => { }); const defaultResponse = new devkit.Response({ - description: "unexpected error" - }).addContent("application/json", errorObject); + description: 'unexpected error' + }).addContent('application/json', errorObject); swagger.addPath( - "/pets", + '/pets', devkit.HttpMethod.GET, new devkit.Path({ - summary: "List all pets", - operationId: "listPets", - tags: ["pets"] + summary: 'List all pets', + operationId: 'listPets', + tags: ['pets'] }) .addParameter({ - name: "limit", - in: "query", - description: "How many items to return at one time (max 100)", + name: 'limit', + in: 'query', + description: 'How many items to return at one time (max 100)', required: false, schema: devkit.Schema.int32() }) .addResponse( - "200", + '200', new devkit.Response({ - description: "A paged array of pets" + description: 'A paged array of pets' }) - .addHeader("x-next", { - description: "A link to the next page of responses", + .addHeader('x-next', { + description: 'A link to the next page of responses', schema: devkit.Schema.string() }) - .addContent("application/json", petsObject) + .addContent('application/json', petsObject) ) - .addResponse("default", defaultResponse) + .addResponse('default', defaultResponse) ); swagger.addPath( - "/pets", + '/pets', devkit.HttpMethod.POST, new devkit.Path({ - summary: "Create a pet", - operationId: "createPets", - tags: ["pets"] + summary: 'Create a pet', + operationId: 'createPets', + tags: ['pets'] }) - .addResponse("201", { description: "Null response" }) - .addResponse("default", defaultResponse) + .addResponse('201', { description: 'Null response' }) + .addResponse('default', defaultResponse) ); swagger.addPath( - "/pets/{petId}", + '/pets/{petId}', devkit.HttpMethod.GET, new devkit.Path({ - summary: "Info for a specific pet", - operationId: "showPetById", - tags: ["pets"] + summary: 'Info for a specific pet', + operationId: 'showPetById', + tags: ['pets'] }) .addParameter({ - name: "petId", - in: "path", + name: 'petId', + in: 'path', required: true, - description: "The id of the pet to retrieve", + description: 'The id of the pet to retrieve', schema: devkit.Schema.string() }) .addResponse( - "200", + '200', new devkit.Response({ - description: "Expected response to a valid request" - }).addContent("application/json", petsObject) + description: 'Expected response to a valid request' + }).addContent('application/json', petsObject) ) - .addResponse("default", defaultResponse) + .addResponse('default', defaultResponse) ); expect(swagger.render()).toEqual(yaml.safeLoad(petstoreYaml)); diff --git a/tests/security.test.ts b/tests/security.test.ts index 5ea8b03..16f3d22 100644 --- a/tests/security.test.ts +++ b/tests/security.test.ts @@ -1,24 +1,24 @@ -import * as devkit from "../src/index"; -import * as yaml from "js-yaml"; +import * as devkit from '../src/index'; +import * as yaml from 'js-yaml'; -describe("Operation Object", () => { - it("should add securitySchemes class", () => { +describe('Operation Object', () => { + it('should add securitySchemes class', () => { const swagger = new devkit.Swagger(); swagger.addSecurityComponent({ BasicAuth: devkit.SecurityScheme.basic(), BearerAuth: devkit.SecurityScheme.bearer(), - ApiKeyAuth: devkit.SecurityScheme.apiKey("header", "X-API-Key"), + ApiKeyAuth: devkit.SecurityScheme.apiKey('header', 'X-API-Key'), OpenID: devkit.SecurityScheme.openId( - "https://example.com/.well-known/openid-configuration" + 'https://example.com/.well-known/openid-configuration' ), OAuth2: devkit.SecurityScheme.oauth2({ authorizationCode: { - authorizationUrl: "https://example.com/oauth/authorize", - tokenUrl: "https://example.com/oauth/token", + authorizationUrl: 'https://example.com/oauth/authorize', + tokenUrl: 'https://example.com/oauth/token', scopes: { - read: "Grants read access", - write: "Grants write access", - admin: "Grants access to admin operations" + read: 'Grants read access', + write: 'Grants write access', + admin: 'Grants access to admin operations' } } }) @@ -55,12 +55,12 @@ describe("Operation Object", () => { expect(actual).toEqual(expect.objectContaining(expected)); }); - it("should add security", () => { + it('should add security', () => { const swagger = new devkit.Swagger(); const security = [ { Auth: [] as Array }, - { OAuth2: ["read", "write"] } + { OAuth2: ['read', 'write'] } ]; const expected = yaml.safeLoad(` @@ -74,11 +74,11 @@ describe("Operation Object", () => { `); swagger.addPath( - "/pets", + '/pets', devkit.HttpMethod.GET, new devkit.Path({ description: - "Returns all pets from the system that the user has access to", + 'Returns all pets from the system that the user has access to', security: security }) ); diff --git a/tests/swagger.spec.ts b/tests/swagger.spec.ts index 6c496dc..2233eb8 100644 --- a/tests/swagger.spec.ts +++ b/tests/swagger.spec.ts @@ -1,9 +1,32 @@ -import * as devkit from "../src/index"; -import * as yaml from "js-yaml"; +import * as devkit from '../src/index'; +import * as yaml from 'js-yaml'; + +describe('Schema', () => { + it('should be nullable', () => { + const swagger = new devkit.Swagger(); + + const expected = yaml.safeLoad(` + openapi: 3.0.0 + components: + schemas: + Foo: + type: string + nullable: true + `); + + new devkit.Component(swagger, 'Foo', { + type: 'string', + nullable: true + }); + const actual: any = swagger.render(); + + expect(actual).toEqual(expect.objectContaining(expected)); + }); +}); -describe("Swagger", () => { - describe("Info Object", () => { - it("should add info", () => { +describe('Swagger', () => { + describe('Info Object', () => { + it('should add info', () => { const swagger = new devkit.Swagger(); const expected = yaml.safeLoad(` @@ -22,19 +45,19 @@ describe("Swagger", () => { `); swagger.addInfo({ - title: "Sample Pet Store App", - description: "This is a sample server for a pet store.", - termsOfService: "http://example.com/terms/", + title: 'Sample Pet Store App', + description: 'This is a sample server for a pet store.', + termsOfService: 'http://example.com/terms/', contact: { - name: "API Support", - url: "http://www.example.com/support", - email: "support@example.com" + name: 'API Support', + url: 'http://www.example.com/support', + email: 'support@example.com' }, license: { - name: "Apache 2.0", - url: "https://www.apache.org/licenses/LICENSE-2.0.html" + name: 'Apache 2.0', + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' }, - version: "1.0.1" + version: '1.0.1' }); const actual: any = swagger.render(); @@ -43,8 +66,8 @@ describe("Swagger", () => { }); }); - describe("Servers Object", () => { - it("should add servers object", () => { + describe('Servers Object', () => { + it('should add servers object', () => { const swagger = new devkit.Swagger(); const expected = yaml.safeLoad(` @@ -59,16 +82,16 @@ describe("Swagger", () => { swagger.addServers([ { - url: "https://development.gigantic-server.com/v1", - description: "Development server" + url: 'https://development.gigantic-server.com/v1', + description: 'Development server' }, { - url: "https://staging.gigantic-server.com/v1", - description: "Staging server" + url: 'https://staging.gigantic-server.com/v1', + description: 'Staging server' }, { - url: "https://api.gigantic-server.com/v1", - description: "Production server" + url: 'https://api.gigantic-server.com/v1', + description: 'Production server' } ]); @@ -77,7 +100,7 @@ describe("Swagger", () => { expect(actual).toEqual(expect.objectContaining(expected)); }); - it("should add servers object with variables", () => { + it('should add servers object with variables', () => { const swagger = new devkit.Swagger(); const expected = yaml.safeLoad(` @@ -101,20 +124,20 @@ describe("Swagger", () => { swagger.addServers([ { - url: "https://{username}.gigantic-server.com:{port}/{basePath}", - description: "The production API server", + url: 'https://{username}.gigantic-server.com:{port}/{basePath}', + description: 'The production API server', variables: { username: { - default: "demo", + default: 'demo', description: - "this value is assigned by the service provider, in this example `gigantic-server.com`" + 'this value is assigned by the service provider, in this example `gigantic-server.com`' }, port: { - enum: ["8443", "443"], - default: "8443" + enum: ['8443', '443'], + default: '8443' }, basePath: { - default: "v2" + default: 'v2' } } } @@ -126,8 +149,8 @@ describe("Swagger", () => { }); }); - describe("Components Object", () => { - it("should define schemas", () => { + describe('Components Object', () => { + it('should define schemas', () => { const swagger = new devkit.Swagger(); const expected = yaml.safeLoad(` @@ -161,7 +184,7 @@ describe("Swagger", () => { new devkit.Component( swagger, - "GeneralError", + 'GeneralError', devkit.Schema.object({ code: devkit.Schema.int32(), message: devkit.Schema.string() @@ -169,7 +192,7 @@ describe("Swagger", () => { ); new devkit.Component( swagger, - "Category", + 'Category', devkit.Schema.object({ id: devkit.Schema.int64(), name: devkit.Schema.string() @@ -177,7 +200,7 @@ describe("Swagger", () => { ); new devkit.Component( swagger, - "Tag", + 'Tag', devkit.Schema.object({ id: devkit.Schema.int64(), name: devkit.Schema.string() @@ -189,12 +212,12 @@ describe("Swagger", () => { expect(actual).toEqual(expect.objectContaining(expected)); }); - it("key is already defined", () => { + it('key is already defined', () => { const swagger = new devkit.Swagger(); new devkit.Component( swagger, - "GeneralError", + 'GeneralError', devkit.Schema.object({ code: devkit.Schema.int32(), message: devkit.Schema.string() @@ -204,18 +227,18 @@ describe("Swagger", () => { expect(() => { new devkit.Component( swagger, - "GeneralError", + 'GeneralError', devkit.Schema.object({ id: devkit.Schema.int64(), name: devkit.Schema.string() }) ); - }).toThrow("DuplicateComponentKeyException"); + }).toThrow('DuplicateComponentKeyException'); }); }); - describe("Paths Object", () => { - it("should add paths object", () => { + describe('Paths Object', () => { + it('should add paths object', () => { const swagger = new devkit.Swagger(); const expected = yaml.safeLoad(` @@ -235,18 +258,18 @@ describe("Swagger", () => { `); swagger.addPath( - "/pets", + '/pets', devkit.HttpMethod.GET, new devkit.Path({ description: - "Returns all pets from the system that the user has access to" + 'Returns all pets from the system that the user has access to' }).addResponse( - "200", + '200', new devkit.Response({ - description: "A list of pets." + description: 'A list of pets.' }).addContent( - "application/json", - devkit.Schema.array(new devkit.Ref("#/components/schemas/pet")) + 'application/json', + devkit.Schema.array(new devkit.Ref('#/components/schemas/pet')) ) ) ); @@ -256,7 +279,7 @@ describe("Swagger", () => { expect(actual).toEqual(expect.objectContaining(expected)); }); - it("should add paths object with parameter", () => { + it('should add paths object with parameter', () => { const swagger = new devkit.Swagger(); const expected = yaml.safeLoad(` @@ -294,38 +317,38 @@ describe("Swagger", () => { `); swagger.addPath( - "/pets", + '/pets', devkit.HttpMethod.GET, new devkit.Path({ - description: "Returns pets based on ID", - summary: "Find pets by ID", - operationId: "getPetsById" + description: 'Returns pets based on ID', + summary: 'Find pets by ID', + operationId: 'getPetsById' }) .addParameter({ - name: "id", - in: "path", - description: "ID of pet to use", + name: 'id', + in: 'path', + description: 'ID of pet to use', required: true, schema: devkit.Schema.array(devkit.Schema.string(), { - style: "simple" + style: 'simple' }) }) .addResponse( - "200", + '200', new devkit.Response({ - description: "pet response" + description: 'pet response' }).addContent( - "*/*", - devkit.Schema.array(new devkit.Ref("#/components/schemas/Pet")) + '*/*', + devkit.Schema.array(new devkit.Ref('#/components/schemas/Pet')) ) ) .addResponse( - "default", + 'default', new devkit.Response({ - description: "error payload" + description: 'error payload' }).addContent( - "text/html", - new devkit.Ref("#/components/schemas/ErrorModel") + 'text/html', + new devkit.Ref('#/components/schemas/ErrorModel') ) ) ); @@ -353,8 +376,8 @@ describe("Swagger", () => { */ }); - describe("Operation Object", () => { - it("should add paths object with requestBody and responses", () => { + describe('Operation Object', () => { + it('should add paths object with requestBody and responses', () => { const swagger = new devkit.Swagger(); const expected = yaml.safeLoad(` @@ -402,56 +425,56 @@ describe("Swagger", () => { - read:pets`); swagger.addPath( - "/pets/{petId}", + '/pets/{petId}', devkit.HttpMethod.PUT, new devkit.Path({ - tags: ["pet"], - summary: "Updates a pet in the store with form data", - operationId: "updatePetWithForm", + tags: ['pet'], + summary: 'Updates a pet in the store with form data', + operationId: 'updatePetWithForm', security: [ { - petstore_auth: ["write:pets", "read:pets"] + petstore_auth: ['write:pets', 'read:pets'] } ] }) .addParameter({ - name: "petId", - in: "path", - description: "ID of pet that needs to be updated", + name: 'petId', + in: 'path', + description: 'ID of pet that needs to be updated', required: true, schema: devkit.Schema.string() }) .addRequestBody( new devkit.RequestBody().addContent( - "application/x-www-form-urlencoded", + 'application/x-www-form-urlencoded', { properties: { name: devkit.Schema.string({ - description: "Updated name of the pet" + description: 'Updated name of the pet' }), status: devkit.Schema.string({ - description: "Updated status of the pet" + description: 'Updated status of the pet' }) }, - required: ["status"] + required: ['status'] } ) ) .addResponse( - "200", + '200', new devkit.Response({ - description: "Pet updated." + description: 'Pet updated.' }) - .addContent("application/json", {}) - .addContent("application/xml", {}) + .addContent('application/json', {}) + .addContent('application/xml', {}) ) .addResponse( - "405", + '405', new devkit.Response({ - description: "Method Not Allowed" + description: 'Method Not Allowed' }) - .addContent("application/json", {}) - .addContent("application/xml", {}) + .addContent('application/json', {}) + .addContent('application/xml', {}) ) );