@1stquad/swagger-typescript-codegen 中文文档教程
Swagger to Typescript Codegen
此包从 swagger 规范文件 生成一个 TypeScript 类。 代码是使用 mustache 模板 生成的,并由 jshint 并通过 js-beautify。
typescript 生成器基于 superagent,可以通过 browserify/webpack 用于 nodejs 和浏览器。
制作此分支是为了简化某些部分,添加更多功能,并针对特定用例进行更多定制。
Installation
npm install @1stquad/swagger-typescript-codegen
Example
var fs = require('fs');
var CodeGen = require('swagger-typescript-codegen').CodeGen;
var file = 'swagger/spec.json';
var swagger = JSON.parse(fs.readFileSync(file, 'UTF-8'));
var tsSourceCode = CodeGen.getTypescriptCode({ className: 'Test', swagger: swagger, imports: ['../../typings/tsd.d.ts'] });
console.log(tsSourceCode);
Custom template
var source = CodeGen.getCustomCode({
moduleName: 'Test',
className: 'Test',
swagger: swaggerSpec,
template: {
class: fs.readFileSync('my-class.mustache', 'utf-8'),
method: fs.readFileSync('my-method.mustache', 'utf-8'),
type: fs.readFileSync('my-type.mustache', 'utf-8')
}
});
Options
除了下面列出的常用选项之外,getCustomCode()
需要 template
字段:
template: { class: "...", method: "..." }
getTypescriptCode()
, < code>getCustomCode() 每个都支持以下选项:
moduleName:
type: string
description: Your module name
className:
type: string
lint:
type: boolean
description: whether or not to run jslint on the generated code
esnext:
type: boolean
description: passed through to jslint
beautify:
type: boolean
description: whether or not to beautify the generated code
beautifyOptions:
type: object
description: Options to be passed to the beautify command. See js-beautify for all available options.
mustache:
type: object
description: See the 'Custom Mustache Variables' section below
imports:
type: array
description: Typescript definition files to be imported.
swagger:
type: object
required: true
description: swagger object
Template Variables
以下数据被传递到 mustache 模板:
isES6:
type: boolean
description:
type: string
description: Provided by your options field: 'swagger.info.description'
isSecure:
type: boolean
description: false unless 'swagger.securityDefinitions' is defined
moduleName:
type: string
description: Your module name - provided by your options field
className:
type: string
description: Provided by your options field
domain:
type: string
description: If all options defined: swagger.schemes[0] + '://' + swagger.host + swagger.basePath
methods:
type: array
items:
type: object
properties:
path:
type: string
pathFormatString:
type: string
className:
type: string
description: Provided by your options field
methodName:
type: string
description: Generated from the HTTP method and path elements or 'x-swagger-js-method-name' field
method:
type: string
description: 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLINK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND'
enum:
- GET
- POST
- PUT
- DELETE
- PATCH
- COPY
- HEAD
- OPTIONS
- LINK
- UNLINK
- PURGE
- LOCK
- UNLOCK
- PROPFIND
isGET:
type: string
description: true if method === 'GET'
summary:
type: string
description: Provided by the 'description' or 'summary' field in the schema
externalDocs:
type: object
properties:
url:
type: string
description: The URL for the target documentation. Value MUST be in the format of a URL.
required: true
description:
type: string
description: A short description of the target documentation. GitHub-Markdown syntax can be used for rich text representation.
isSecure:
type: boolean
description: true if the 'security' is defined for the method in the schema
version:
type: string
description: Version part of the path, if the path starts with the prefix '/api/vXXX/'.
intVersion:
type: integer
description: Integer part of the version string.
isLatestVersion:
type: boolean
description: True iff this is the latest version of the method.
parameters:
type: array
description: Includes all of the properties defined for the parameter in the schema plus:
items:
camelCaseName:
type: string
isSingleton:
type: boolean
description: true if there was only one 'enum' defined for the parameter
singleton:
type: string
description: the one and only 'enum' defined for the parameter (if there is only one)
isBodyParameter:
type: boolean
isPathParameter:
type: boolean
isQueryParameter:
type: boolean
isPatternType:
type: boolean
description: true if *in* is 'query', and 'pattern' is defined
isHeaderParameter:
type: boolean
isFormParameter:
type: boolean
successfulResponseType:
type: string
description: The type of a successful response. Defaults to any for non-parsable types or Swagger 1.0 spec files
successfulResponseTypeIsRef:
type: boolean
description: True iff the successful response type is the name of a type defined in the Swagger schema.
Custom Mustache Variables
你还可以通过添加 mustache
对象为 mustache 模板传递您自己的变量:
var source = CodeGen.getCustomCode({
...
mustache: {
foo: 'bar',
app_build_id: env.BUILD_ID,
app_version: pkg.version
}
});
Swagger Extensions
x-proxy-header
一些代理和应用程序服务器将 HTTP 标头注入到请求中。 服务器端代码 可以使用这些字段,但它们在客户端 API 中不是必需的。
例如:https:
/locations:
get:
parameters:
- name: X-AppEngine-Country
in: header
x-proxy-header: true
type: string
description: Provided by AppEngine eg - US, AU, GB
- name: country
in: query
type: string
description: |
2 character country code.
If not specified, will default to the country provided in the X-AppEngine-Country header
...
Development
//cloud.google.com/appengine/docs/go/requests#GoRequestheaders 要在源文件运行时运行打字稿编译器。 这将在源上启动监视进程并将它们构建到 lib
文件夹中。
npm run build:watch
此外,您可以在单独的选项卡中运行测试观察器,以观察模式对 lib
文件夹中的文件运行测试。
npm run test:watch
Swagger to Typescript Codegen
This package generates a TypeScript class from a swagger specification file. The code is generated using mustache templates and is quality checked by jshint and beautified by js-beautify.
The typescript generator is based on superagent and can be used for both nodejs and the browser via browserify/webpack.
This fork was made to simplify some parts, add some more features, and tailor it more to specific use cases.
Installation
npm install @1stquad/swagger-typescript-codegen
Example
var fs = require('fs');
var CodeGen = require('swagger-typescript-codegen').CodeGen;
var file = 'swagger/spec.json';
var swagger = JSON.parse(fs.readFileSync(file, 'UTF-8'));
var tsSourceCode = CodeGen.getTypescriptCode({ className: 'Test', swagger: swagger, imports: ['../../typings/tsd.d.ts'] });
console.log(tsSourceCode);
Custom template
var source = CodeGen.getCustomCode({
moduleName: 'Test',
className: 'Test',
swagger: swaggerSpec,
template: {
class: fs.readFileSync('my-class.mustache', 'utf-8'),
method: fs.readFileSync('my-method.mustache', 'utf-8'),
type: fs.readFileSync('my-type.mustache', 'utf-8')
}
});
Options
In addition to the common options listed below, getCustomCode()
requires a template
field:
template: { class: "...", method: "..." }
getTypescriptCode()
, getCustomCode()
each support the following options:
moduleName:
type: string
description: Your module name
className:
type: string
lint:
type: boolean
description: whether or not to run jslint on the generated code
esnext:
type: boolean
description: passed through to jslint
beautify:
type: boolean
description: whether or not to beautify the generated code
beautifyOptions:
type: object
description: Options to be passed to the beautify command. See js-beautify for all available options.
mustache:
type: object
description: See the 'Custom Mustache Variables' section below
imports:
type: array
description: Typescript definition files to be imported.
swagger:
type: object
required: true
description: swagger object
Template Variables
The following data are passed to the mustache templates:
isES6:
type: boolean
description:
type: string
description: Provided by your options field: 'swagger.info.description'
isSecure:
type: boolean
description: false unless 'swagger.securityDefinitions' is defined
moduleName:
type: string
description: Your module name - provided by your options field
className:
type: string
description: Provided by your options field
domain:
type: string
description: If all options defined: swagger.schemes[0] + '://' + swagger.host + swagger.basePath
methods:
type: array
items:
type: object
properties:
path:
type: string
pathFormatString:
type: string
className:
type: string
description: Provided by your options field
methodName:
type: string
description: Generated from the HTTP method and path elements or 'x-swagger-js-method-name' field
method:
type: string
description: 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'COPY', 'HEAD', 'OPTIONS', 'LINK', 'UNLINK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND'
enum:
- GET
- POST
- PUT
- DELETE
- PATCH
- COPY
- HEAD
- OPTIONS
- LINK
- UNLINK
- PURGE
- LOCK
- UNLOCK
- PROPFIND
isGET:
type: string
description: true if method === 'GET'
summary:
type: string
description: Provided by the 'description' or 'summary' field in the schema
externalDocs:
type: object
properties:
url:
type: string
description: The URL for the target documentation. Value MUST be in the format of a URL.
required: true
description:
type: string
description: A short description of the target documentation. GitHub-Markdown syntax can be used for rich text representation.
isSecure:
type: boolean
description: true if the 'security' is defined for the method in the schema
version:
type: string
description: Version part of the path, if the path starts with the prefix '/api/vXXX/'.
intVersion:
type: integer
description: Integer part of the version string.
isLatestVersion:
type: boolean
description: True iff this is the latest version of the method.
parameters:
type: array
description: Includes all of the properties defined for the parameter in the schema plus:
items:
camelCaseName:
type: string
isSingleton:
type: boolean
description: true if there was only one 'enum' defined for the parameter
singleton:
type: string
description: the one and only 'enum' defined for the parameter (if there is only one)
isBodyParameter:
type: boolean
isPathParameter:
type: boolean
isQueryParameter:
type: boolean
isPatternType:
type: boolean
description: true if *in* is 'query', and 'pattern' is defined
isHeaderParameter:
type: boolean
isFormParameter:
type: boolean
successfulResponseType:
type: string
description: The type of a successful response. Defaults to any for non-parsable types or Swagger 1.0 spec files
successfulResponseTypeIsRef:
type: boolean
description: True iff the successful response type is the name of a type defined in the Swagger schema.
Custom Mustache Variables
You can also pass in your own variables for the mustache templates by adding a mustache
object:
var source = CodeGen.getCustomCode({
...
mustache: {
foo: 'bar',
app_build_id: env.BUILD_ID,
app_version: pkg.version
}
});
Swagger Extensions
x-proxy-header
Some proxies and application servers inject HTTP headers into the requests. Server-side code may use these fields, but they are not required in the client API.
eg: https://cloud.google.com/appengine/docs/go/requests#GoRequestheaders
/locations:
get:
parameters:
- name: X-AppEngine-Country
in: header
x-proxy-header: true
type: string
description: Provided by AppEngine eg - US, AU, GB
- name: country
in: query
type: string
description: |
2 character country code.
If not specified, will default to the country provided in the X-AppEngine-Country header
...
Development
To run the typescript compiler on the source files run. This will start a watch process on the sources and build them into the lib
folder.
npm run build:watch
In addition you can run the test watcher in a separate tab to run the tests in watch mode on the files in the lib
folder.
npm run test:watch