Skip to content

Latest commit

 

History

History
127 lines (103 loc) · 2.86 KB

README.md

File metadata and controls

127 lines (103 loc) · 2.86 KB

grunt-swagger-vue

Swagger Codegen for Vue.js

fork of swagger-vue

Getting Started

Requirements

Installation

npm install grunt-swagger-vue --save-dev

Configuration

  grunt.initConfig({
    'swagger-vue': {
      options: {
        swagger: "client/swagger.json",
        className: "MyClassName",
        moduleName: "vue-api-client",
        dest: 'client/javascript'
      },
      dist: {

      }
    }
  });

Load task

grunt.loadNpmTasks('grunt-swagger-vue');

Example

Add in your package.json

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

Create Gruntfile.js

module.exports = function(grunt) {

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

      }
    }
  });

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

};

Execute in terminal

grunt vue

Generated client's usage

In Vue.js main file initialize the API plugin with domain param.

import MyClassName from './lib/vue-api-client.js'
Vue.use(MyClassName, {
  domain: 'http://localhost:3000/api'
})

Import API models into Vue.js component, for example import user model and use login method to generate a new token.

import { AccessToken, user } from '../lib/vue-api-client.js'

user.login({
  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}
}).catch(function (error) {
  console.log(error.response.data) // your error response
})

Then set the Authorization header for all future request.

var token = response.data
AccessToken.set(token) // now access token is set

You can also clear it for logout purpose

AccessToken.clear() // Authorization header is now empty

All requests use axinos module returning a promise, for more information about that follow axios documentation

Notes

Code generator is only compatible with Swagger v2 and generated client is exported in ES6

Links

License

MIT