GithubHelp home page GithubHelp logo

swagger-vue's Introduction

swagger-vue

Swagger to JS & Vue & Axios Codegen

Installation

npm install swagger-vue --dev

Generate

Using NodeJS file

const swaggerGen = require('swagger-vue')
const jsonData = require('../api-docs.json')
const fs = require('fs')
const path = require('path')

let opt = {
  swagger: jsonData,
  moduleName: 'api',
  className: 'api'
}
const codeResult = swaggerGen(opt)
fs.writeFileSync(path.join(__dirname, '../dist/api.js'), codeResult)

Using Grunt task

Create Gruntfile.js

const fs = require('fs')
const path = require('path')
const swaggerGen = require('swagger-vue')

module.exports = function(grunt) {

  grunt.initConfig({
    'pkg': grunt.file.readJSON('package.json'),
    'swagger-vue-codegen': {
      options: {
        swagger: "<%= pkg.swagger.definition %>",
        className: "<%= pkg.swagger.className %>",
        moduleName: "vue-<%= pkg.swagger.moduleName %>",
        dest: 'client/javascript'
      },
      dist: {

      }
    }
  });

  grunt.registerMultiTask('swagger-vue-codegen', function() {
    var callback = this.async();
    var opt = this.options();
    var distFileName = path.join(opt.dest, opt.moduleName + '.js');

    fs.readFile(opt.swagger, function(err, data) {
      if (err) {
        grunt.log.error(err.toString());
        callback(false);
      } else {
        var parsedData = JSON.parse(data);

        var codeResult = swaggerGen({
          swagger: parsedData,
          moduleName: opt.moduleName,
          className: opt.className
        });

        fs.writeFile(distFileName, codeResult, function(err) {
          if (err) {
            grunt.log.error(err.toString());
            callback(false);
          } else {
            grunt.log.writeln('Generated ' + distFileName + ' from ' + opt.swagger);
          }
        })
      }
    });
  });

  grunt.registerTask('vue', ['swagger-vue-codegen']);

};

And set options in package.json

...
  "swagger": {
    "definition": "client/swagger.json",
    "className": "API",
    "moduleName": "api-client"
  }
...

Now you can use grunt vue to run build task

Generated client usage

In Vue.js main file set API domain

import { setDomain } from './lib/api-client.js'
setDomain('http://localhost:3000/api')

Import API function into Vue.js component, for example to log in

import { user_login as userLogin } from '../lib/api-client.js'

userLogin({
  credentials: {
    username: 'admin',
    password: 'admin'
  }
}).then(function (response) {
  console.log(response.data) // {id: "<token>", ttl: 1209600, created: "2017-01-01T00:00:00.000Z", userId: 1}
})

All requests use axios module with promise, for more information about that follow axios documentation

Links

License

MIT

swagger-vue's People

Contributors

chenweiqun avatar daaru00 avatar dependabot[bot] avatar jhuizy avatar miguel-aranda avatar qlio avatar shamrt avatar someone1 avatar

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

swagger-vue's Issues

set axios instance

Hi, I have an axios instance with request interceptors.
How can I set my axios instance?

insted of (api.js)

import axios from 'axios'

Add file to set the axios instance (index.js)

let axios
function setAxios (vueAxios) {
  axios = vueAxios
}

function getAxios () {
  return axios
}

export { getAxios }
export default setAxios

And then in my api.js , use the custom axios instance (api.js)

import { getAxios } from '../../index'
export default {
  getAlms () {
    return getAxios().get(pathAlms).then(response => {
      return response.data
    })
  }
}

Pass configuration to Axios

Hi chenweiqun!

I am trying to pass a configuration to axios to send credentials in a cross-site call. I've tried (by looking at the source code) this, but it doesn't work. I'm doing something wrong? I've also tried other axios parameters without success.

shopDeleteById({ id: shop.id, $config: { withCredentials: true } }).then(() => {

Thanks a lot! :)

Generate Models

Is it possible to generate models similar to the swagger-codegen for javascript?

Wrong replace thread_id by threadId

this YAML

  /thread/settings_sources_keywords:
    post:
      tags:
        - thread
      summary: ThreadSetSourcesKeywords
      description: ThreadSetSourcesKeywords
      operationId: ThreadSetSourcesKeywords
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - in: body
          name: body
          description: Thread settings - keywords
          required: true
          schema:
            $ref: '#/definitions/ThreadKeywords'
      responses:
        '200':
          description: Thread settings, set keywords
        '403':
          description: Access denied
        '405':
          description: Invalid input

generated this code

/**
 * ThreadGetSourcesKeywords
 * request: ThreadGetSourcesKeywords
 * url: ThreadGetSourcesKeywordsURL
 * method: ThreadGetSourcesKeywords_TYPE
 * raw_url: ThreadGetSourcesKeywords_RAW_URL
 * @param threadId - thread id
 */
export const ThreadGetSourcesKeywords = function(parameters = {}) {
  const domain = parameters.$domain ? parameters.$domain : getDomain()
  const config = parameters.$config
  let path = '/thread/settings_sources_keywords_get'
  let body
  let queryParameters = {}
  let form = {}
  if (parameters['threadId'] !== undefined) {
    body = parameters['threadId']
  }
  if (parameters['threadId'] === undefined) {
    return Promise.reject(new Error('Missing required  parameter: threadId'))
  }
  if (parameters.$queryParameters) {
    Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
      queryParameters[parameterName] = parameters.$queryParameters[parameterName]
    });
  }
  return request('post', domain + path, body, queryParameters, form, config)
}
export const ThreadGetSourcesKeywords_RAW_URL = function() {
  return '/thread/settings_sources_keywords_get'
}
export const ThreadGetSourcesKeywords_TYPE = function() {
  return 'post'
}

BUT
this

  /thread/settings_periods_get:
    post:
      tags:
        - thread
      summary: ThreadGetPeriods
      description: Get thread periods
      operationId: ThreadGetPeriods
      consumes:
        - application/json
      produces:
        - application/json
      parameters:
        - in: body
          name: body
          required: true
          description: thread id
          schema:
            $ref: '#/definitions/ThreadId'
      responses:
        '200':
          description: Thread settings, get time periods
          schema:
            $ref: '#/definitions/ThreadSettingsPeriods'
        '403':
          description: Access denied
        '405':
          description: Invalid input

generated this code

/**
 * Get thread periods
 * request: ThreadGetPeriods
 * url: ThreadGetPeriodsURL
 * method: ThreadGetPeriods_TYPE
 * raw_url: ThreadGetPeriods_RAW_URL
 * @param body - thread id
 */
export const ThreadGetPeriods = function(parameters = {}) {
  const domain = parameters.$domain ? parameters.$domain : getDomain()
  const config = parameters.$config
  let path = '/thread/settings_periods_get'
  let body
  let queryParameters = {}
  let form = {}
  if (parameters['body'] !== undefined) {
    body = parameters['body']
  }
  if (parameters['body'] === undefined) {
    return Promise.reject(new Error('Missing required  parameter: body'))
  }
  if (parameters.$queryParameters) {
    Object.keys(parameters.$queryParameters).forEach(function(parameterName) {
      queryParameters[parameterName] = parameters.$queryParameters[parameterName]
    });
  }
  return request('post', domain + path, body, queryParameters, form, config)
}

Why in one case it create threadId (unnecessary behavior) and in another make normal body parameter?

schemes

  ThreadId:
    type: object
    required:
      - thread_id
    properties:
      thread_id:
        type: string
        description: thread_id
  ThreadKeywords:
    type: object
    required:
      - thread_id
      - keywords
      - stopkeywords
    properties:
      thread_id:
        type: string
      keywords:
        type: array
        items:
          type: string
      stopkeywords:
        type: array
        items:
          type: string

Sen cookies only to POST, not to GET requests

I add two lines (19,20) in generated code for work with cookies.

  config = config || {};
  config.withCredentials = true;

but when i use GET requests, cookie not send to server, but with POST all OK.

P.S. Post request generate another OPTIONS request.

TypeError when used OpenAPI 3.0 specification

The module works well for OAS 2 but not with OAS 3.
Are there any upcoming releases or is it an issue from my side?
Thanks!

/Users/nagnath.masali/Swagger/For Vue/node_modules/swagger-vue-axios/node_modules/swagger-vue/lib/parse.js:152
  swagger.apis.forEach(function (api) {
               ^

TypeError: Cannot read property 'forEach' of undefined
    at getViewForSwagger1 (/Users/nagnath.masali/Swagger/For Vue/node_modules/swagger-vue-axios/node_modules/swagger-vue/lib/parse.js:152:16)
    at parse (/Users/nagnath.masali/Swagger/For Vue/node_modules/swagger-vue-axios/node_modules/swagger-vue/lib/parse.js:206:74)
    at module.exports (/Users/nagnath.masali/Swagger/For Vue/node_modules/swagger-vue-axios/node_modules/swagger-vue/index.js:4:14)
    at Object.<anonymous> (/Users/nagnath.masali/Swagger/For Vue/node_modules/swagger-vue-axios/node_modules/swagger-vue/example/create_api/index.js:10:20)
    at Module._compile (internal/modules/cjs/loader.js:1151:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
    at Module.load (internal/modules/cjs/loader.js:1000:32)
    at Function.Module._load (internal/modules/cjs/loader.js:899:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

Importing API

Hello chenweiqun,

I found this project when I was searching someway of integrating an swagger api to vue. I'm able with your code, to generate the api.js code, but I have no idea how to integrate that into vue.

Can you explain briefly how to do it? (How to use the generated file)

Thanks!

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.