Giter VIP home page Giter VIP logo

swagger-js-codegen's Introduction

#Swagger to JS Codegen Build Status NPM version Code Climate

This package generates a nodejs or angularjs class from a swagger specification file. The code is generated using mustache templates and is quality checked by jshint and beautified by js-beautify.

##Installation

npm install swagger-js-codegen

##Example

var fs = require('fs');
var CodeGen = require('swagger-js-codegen').CodeGen;

var file = 'swagger/spec.json';
var swagger = JSON.parse(fs.readFileSync(file, 'UTF-8'));
var nodejsSourceCode = CodeGen.getNodeCode({ className: 'Test', swagger: swagger });
var angularjsSourceCode = CodeGen.getAngularCode({ className: 'Test', swagger: swagger });
console.log(nodejsSourceCode);
console.log(angularjsSourceCode);

##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'),
        request: fs.readFileSync('my-request.mustache', 'utf-8')
    }
});

##Options In addition to the common options listed below, getCustomCode() requires a template field:

template: { class: "...", method: "...", request: "..." }

getAngularCode(), getNodeCode(), and getCustomCode() each support the following options:

  moduleName:
    type: string
    description: Your AngularJS 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
  mustache:
    type: object
    description: See the 'Custom Mustache Variables' section below
  swagger:
    type: object
    required: true
    properties:
      swagger:
        description: |
          For Swagger Specification version 2.0 value of field 'swagger' must be a string '2.0'
        type: string
        enum:
        - 2.0
        - 1.2
      info:
        type: object
        properties:
          description:
            type: string
            description: Made available to templates as '{{&description}}'
      securityDefinitions:
        type: object
        description:
      parameters:
        type: array
        items:
          type: object
          properties:
            name:
              type: string
              required: true
            enum:
              type: array
            in:
              type: string
              enum:
              - body
              - path
              - query
              - header
              - formData

###Template Variables The following data are passed to the mustache templates:

isNode:
  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 AngularJS 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
      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', 'UNLIK', 'PURGE', 'LOCK', 'UNLOCK', 'PROPFIND'
        enum:
        - GET
        - POST
        - PUT
        - DELETE
        - PATCH
        - COPY
        - HEAD
        - OPTIONS
        - LINK
        - UNLIK
        - PURGE
        - LOCK
        - UNLOCK
        - PROPFIND
      isGET:
        type: string
        description: true if method === 'GET'
      summary:
        type: string
        description: Provided by the 'description' field in the schema
      isSecure:
        type: boolean
        description: true if the 'security' is defined for the method in the schema
      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
      bodySchema:
        type: object
        properties:
          type: array
          description: the schema for a body parameter, null if no body parameter is defined.
          items:
            name:
              type: string
              description: the name of the property
            type:
              type: string
              description: the type of the property
            description:
              type: string
              description: the description of the property
            required:
              type: boolean
              description: true if the property is required

####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-swagger-js-method-name

By default, javascript method names are generated by concatenating the HTTP method name and path segments. Generally, the generated names read well, but sometimes they turn out wrong:

// A PUT to this path in a swagger schema:  /records/{id}/meta
// is intended to update a "meta" property on a specific "Record" entity.
// ...swagger-js-codegen generates a method named:
MyApi.prototype.putEntitiesByIdMeta = function(parameters) {

If you would like to provide your own method names, use the x-swagger-js-method-name field at the method level

  /records/{id}/meta:
    put:
      x-swagger-js-method-name: updateRecordMetaData
      parameters:
      - name: id
       in: path
       ...

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#Go_Request_headers

  /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
      ...

Grunt & Gulp task

There is a grunt task that enables you to integrate the code generation in your development pipeline. This is extremely convenient if your application is using APIs which are documented/specified in the swagger format.

And example of gulp task is available here.

##Who is using it? The CellStore project.

28.io is using this project to generate their nodejs and angularjs language bindings.

swagger-js-codegen's People

Contributors

wcandillon avatar borisirota avatar nalbion avatar mahnunchik avatar hawaiianspork avatar rajit avatar mdautry avatar pieterjandesmedt avatar bradygaster avatar

Watchers

timball avatar Walt Askew avatar Skipper Seabold avatar James Cloos avatar Dan Wagner avatar Aziz Shallwani avatar Jesse Stinebring avatar Michelangelo D'Agostino avatar Chris George avatar Roberto Vidal avatar  avatar  avatar Tony avatar  avatar  avatar Nick Lee avatar Chris Perry avatar Melissa Roemmele avatar Chas Jhin avatar Jenna Colazzi avatar John avatar  avatar Brian Fritton avatar Masa Aida avatar Paul avatar Salil Gupta avatar Ali Vanderveld avatar Devin McGinty avatar Elliott Evans avatar Leanne Miller avatar Paul Suda avatar  avatar  avatar  avatar Adrianna Misterka avatar Rachel Connolly avatar  avatar  avatar Bernard Bergmann avatar  avatar  avatar James Michelson avatar  avatar Kelli-Jean Chun avatar  avatar  avatar Evelyn Ting avatar  avatar Natnaell avatar Max Winston avatar  avatar  avatar Mike Revelle avatar Alex Chin avatar  avatar April Chen avatar Cullen Tanoue avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar Abhiti Prabahar avatar  avatar Crystal Son avatar  avatar  avatar Clara avatar Zheng Liu avatar  avatar  avatar  avatar  avatar  avatar Daniel Silva-Inclán avatar Franklin Marsh avatar  avatar  avatar  avatar  avatar  avatar Wade Johnston avatar  avatar  avatar Gustavo Sanchez avatar  avatar  avatar Nik (Anna) Bladey avatar  avatar Carrie Utter avatar  avatar Madison Hobbs avatar  avatar John Means avatar  avatar  avatar  avatar

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.