Coder Social home page Coder Social logo

kenkougmbh / vuex-module-with-http-calls Goto Github PK

View Code? Open in Web Editor NEW
2.0 6.0 0.0 29 KB

A helper function to automatically create vuex modules with http calls as actions and optionally map the results to the store.

License: MIT License

JavaScript 100.00%
vuex vue http axios

vuex-module-with-http-calls's Introduction

NPM npm

vuex-module-with-http-calls

A helper function to automatically create vuex modules with http calls as actions.

Install

with yarn:

yarn add vuex-module-with-http-calls

with npm:

npm install --save vuex-module-with-http-calls

Usage

Let's suppose that we want to define a vuex module called profile. We can, for instance, create a file file profile-vuex-module.js and put some content inside:

import { withHttpCalls } from 'vuex-module-with-http-calls'

const baseURL = 'https://example.com/api'

const httpCalls = [
  // results in an action `DeleteUserProfile` that calls
  // `GET https://example.com/api/DeleteUserProfile`
  // notice that GET is the default method
  { url: 'DeleteUserProfile' },
  // results in an action `DeleteUserProfile` that calls 
  // `DELETE https://example.com/api/DeleteUserProfile`
  { url: 'DeleteUserProfile', method: 'delete' },
  // results in a named action `getProfile` that calls 
  // `POST https://example.com/api/GetUserProfile`
  // the result of the call will be stored in `state.profile` property
  // you can call the generated action with some argument
  //    getProfile({ uid: "137faa4c-e8d7-4a98-8945-37dd7fe21af8" })
  {
    name: 'getProfile',
    url: 'GetUserProfile',
    method: 'post',
    resultToStateField: 'profile',
    onSuccess: data => console.log('request went fine, result:', data),
    onError: {
      // keys are the http status response
      '401': error => console.log('Unauthorized', error),
      '500': error => console.log('internal server error', error)
    }
  }
]

// you can either provide state, getters, mutations and extra actions
// or choose not to, in the last case empty objects will be created and used
const profileModule = withHttpCalls({
  baseURL,
  httpCalls
})

export default profileModule

Notice that the action arguments will be passed as the data property to the underlying axios.request method while performing the http call. If no name property is passed then the url is used as the action name. The httpCalls examples are organized in an ascending complexity way here to point out the many options we may pass but the only required field is the url one. All the actions created to perform the http calls are marked as async.

Then you can later register the vuex module profileModule by doing:

import profileModule from './profile-vuex-module'
...
// here `store` is the `vuex` store instance
// register the module dynamically
store.registerModule('profile', profileModule)
...

or

// or at store creation time
...
const store = new Vuex.Store({
  modules: {
    profile: profileModule
  }
})
...

somewhere in your code.

Default content of the module

The module by default has:

  • namespaced = true.
  • state = { requesting: false, token: '' }. The requesting field will be set to true when a http call starts and false when completed and it can be used to display loaders while requesting, for example.
  • getters = {}.
  • A mutation set which just update the correspondent key in the state with the passed value.
  • An action setToken which can be used to set the authentication jwt token header, see next section.

Any additional state, gettters, actions and mutations provided to the withHttpCalls function:

const profileModule = withHttpCalls({
  baseURL,
  httpCalls,
  state,
  getters,
  mutations,
  actions,
  namespaced: true // or false as needed
})

will be merged with these.

Authentication

You can configure to send an Authorization: Bearer token header on each http request by setting the token in the module state using the built in setToken action. Let's assume that somewhere in your app you authenticate against your authentication server and you get a valid JWT token in exchange, then you can dispacth the setToken action, for instance from another vuex module action body, by doing:

store.dispatch('profile/setToken', { token: 'ey...' }, { root: true })

From now on your module request will have the Authorization: Bearer ey... header.

Sponsors

Kenkou GmbH

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.