npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

vue-fast-axios

v1.0.2

Published

Solution to remove and simplify axios in components vue

Downloads

4

Readme

Vue fast axios

Solution to remove and simplify axios in components vue

Dependencies:

  • Only Vue.js 2.x

Before install

Before installing, you must install and configure some packages to make use of the plugin.

First, install the babel-polyfill package to allow use async and await keywords:

npm install babel-polyfill --save

To allow, edit the webpack.config.js, replacing the line:

entry: './src/main.js',

To:

entry: ['babel-polyfill', './src/main.js'],

If your want use arrow function in your services, please install transform-class-properties plugin:

npm install babel-plugin-transform-class-properties --save-dev

In your .babelrc file, register this plugin:

{
  ...
  "plugins": [
    "transform-class-properties"
  ]
}

Installation

To install this plugin run:

npm install vue-fast-axios --save

After it, register he in Vue application, in main.js file:

import VueFastAxios from 'vue-fast-axios'
Vue.use(VueFastAxios)

Creating services

An service is compound with follow definitions:

  • base:function | string : return root url for your API

  • headers:function | object : return object with headers for api, use style of axios

  • routes:function | object : return object with routes for api, each route has properties 'methods' and 'path'

  • methods:function | object : return object with alias for async request to route, each method has properties 'method' and 'route'

  • defaultVMessage:function | string : return default message of error to validations

  • validation:function | object : return object with properties to validate, each property has properties 'validator' and 'message'

    See an example:

'use strict'

// Export service skeleton class
export default class PeoplesService {
    // define base url to requests
    base = () => 'https://xxx.firebaseio.com/'

    headers = () => ({
        'Content-Type': 'application/json' // but vue-fast-axios use application/json as default header
    })

    // define routes
    routes = () => ({
        root: { // route name
            methods: 'get,post', // methods accepted in route
            path: 'peoples.json' // path to route, url is: base + prepend + path + append
        },
        peoples: { // route name
            methods: 'put,delete' // methods accepted in route
            // default path route is route name (peoples)
        }
    })

    // methods to call in service instance
    methods = () => ({
        list: { // method name
            method: 'get', // method to htpp request
            route: 'root' // route to call with method
        },
        create: {
            method: 'post',
            route: 'root'
        }
    })

    defaultVMessage = () => 'Error to handle peoples'

    // validations
    validation = () => ({
        name: { // property to validate
            validator: (value) => value.length > 2, // validation
            message: 'Name is invalid' // message to error case
        },
        // simple validator, the error message is 'Error to handle peoples'
        key: (value) => key > 0
    })
}

Using services

In your vue componentes, use method $serviceFactory to create an service with skeleton created before:

<template>
  ...
</template>

<script>
import PeoplesService from './services/PeoplesService' // your service

export default {
  name: 'app',
  data: () => ({
    service: null, // store my service handler
    ...
  }),
  // create my service with PeoplesService rules and pass this to call handle methods
  mounted() {
    this.service = this.$serviceFactory(new PeoplesService, this)
  },
  ...
  }
}
</script>

Now you have an service object, you can run call and execute methods, they has an simple difference:

  • execute(routeName, parameters = {}) | bool : use this to simples and manual requests. To use, you must have the methods serviceSuccess and serviceError, they as called when promise is resolved and receive an object with error or response.
  • call(methodName, parameters = {}) | object: use this for async/await requests. Is an way for execute request and capture response in one line! Erros as exceptions are throwed in console.

To use this methods, your component must have validationError method, they is called when an validation has failed, and receive an message as parameter.

See an metaphorical example:

<template>
  <div id="app">
    <button @click="createPeople">Create people</button>

    <button @click="updatePeople">Update pople</button>

    <ul>
      <li v-for="(people, key) in peoples" :key="key">
        <button @click="deletePeople(key)">Delete</button>
        {{ people.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import PeoplesService from './services/PeoplesService'

export default {
  name: 'app',
  data: () => ({
    service: null, // store my service handler
    peoples: [], // list of peoples
    newPeople: 'Leonardo', // store name from new people
    peopleToUpdate: {key: 1, name: 'New Leonardo'} // people to update
  }),
  // create my service with PeoplesService rules and pass this to call handle methods
  mounted() {
    this.service = this.$serviceFactory(new PeoplesService, this)
    this.load()
  },
  methods: {
    // call list method from PeopleService, with route root and method get
    async load() {
      this.peoples = await this.service.call('list')
    },

    // call create method from PeopleService, with route root and method post, pass object to register
    // this object is validate with 'name' rule from PeopleService
    async createPeople() {
      await this.service.call('create', { name: this.newPeople })
      this.load()
    },

    // append key.json to url, and set delete method. Execute this settings in peoples route
    deletePeople(key) {
      this.service.append(`/${key}.json`).del().execute('peoples')
    },

    // append key.json to url, and set post method. Execute this settings in peoples route with name data to validation
    updatePeople() {
      const {key, name} = this.peopleToUpdate
      this.service.append(`/${key}.json`).put().execute('peoples', {name})
    },

    // this method is called after response rigth from request make by execute method
    serviceSuccess(data) {
      this.load()
    },

    // this method is called after response wrong from request make by execute method
    serviceError(error) {
      alert(error)
    },

    // this method is called why has valitation error, message error is pass in param
    validationError(message) {
      alert(message)
    }
  }
}
</script>

Note the use from helpers methods. See follow they...

Helpers methods

We have some methods to help you!

To execute method, use this methods to define type of request:

  • this.service.get().execute(...) : define GET http method
  • this.service.pos().execute(...) : define POST http method
  • this.service.put().execute(...) : define PUT http method
  • this.service.del().execute(...) : define DELETE http method

To methods execute ou call, use this methods for change url of request:

  • this.service.append('foo').execute(...) : add 'foo' in url request. Result: url + path + 'foo'
  • this.service.append('bar').execute(...) : add 'bar' in url request. Result: url + bar + path

Contributing

To contribute this plugin, fork, edit and send an PR for me. Before send PR, run npm run build to transpile source to ES5.