0.0.3 • Published 4 years ago

vfesk-http v0.0.3

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

Vue Http

Author: Audren GUILLAUME for LIST.

Version: 0.0.2

Updated on: 09/04/20

Vue HTTP is a plugin responsible for handling HTTP calls to one or more HTTP clients for Web application in Vue.js.

It can be compared as an interface that organize and structures HTTP calls in a consistent manner.

In broad terms, the plugin provides a set of functions in their own namespaces which follow the URL path structure of the HTTP client calls.

Such a namespace is identified by a name and defined by a domain, an options object and a set of functions. Those functions implement the call interface for the HTTP client, i.e. they perform the actual HTTP requests.

// example
const authNamespace = {
  domain: "http://the-url-to-reach.com/api/auth",
  options: { ... },
  myAuthFuncA() {},
  myAuthFuncB() {},
  ...
};
const userNamespace = { ... }
export default new VueHttp({
  auth: authNamespace,
  user: userNamespace,
  ...
})

This plugin was created to simplify the HTTP call management by replacing complex HTTP requests by simple JS/TS function calls and by managing the authentication token, among other things. It is also accessible within the entire scope of the Vue.js application. That is within the "src/" folder.

A typical call of the Vue HTTP client look like that:

this.$http.auth.myAuthFuncA(...params);

Examples are written in Typescript but Javascript is also a valid choice.

Table of Contents

Prerequisites

  • Node 10.x or higher (with NPM)
  • A Vue.js project 2.x or higher

Getting Started

Installation

In your Vue.js project, the first step is to download the plugin.

$ npm install vfesk-http

Note for developers:

The plugin is available on npmjs.com instead of our repository manager Artifactory. The reason is quite simple, you cannot generate an npm access_token from our current Artifactory version.

Thus, the package is unavailable in a docker container.

Initialisation

The initialisation of this plugin requires the creation of a folder and some files in the source folder ("src/").

You should have something similar to the example below:

Folders end with a slash "/" and files with a file extension.

.
src/
 ├── main.ts # The plugin is loaded here
 └── plugins/
      └── vue-http/
           └── index.ts # The plugin is initialized here
           └── auth.ts # One namespace configuration [1]
           └── user.ts

1 The auth.ts file is the namespace that groups all the HTTP calls related to the auth business-logic

// index.ts

/** Import the plugin and all the namespaces configuration */
import VueHttp from "vfesk-http";

import authNamespace from "./auth";
import userNamespace from "./user";

/** Initialize the plugin with the namespaces configuration */
export default new VueHttp({
  auth: authNamespace,
  user: userNamespace,
});

A namespace configuration must include 2 named properties "domain", "options" and a least one call function.

  • domain is the client URL to reach by the call function
  • options are an object where you can put whatever you want that is related to this namespace.
  • call functions are functions that perform the actual HTTP request on the domain URL. We recommend to always return a Promise to be consistent with modern javascript programming.
// auth.ts

export default {
  domain: "http://itd-docker.private.list.lu:9001/auth",
  options: {
    api_key: null,
    ContentType: "application/json"
    ...
  },
  signIn(login, password) {
    const body = JSON.stringify({login, password});

    /**
     * It is recommended to use the Fetch API instead of Axios
     * or any other kind of HTTP client library. Fetch is
     * build-in library for the majority of browsers.
     *
     * Moreover, Fetch API offers extra capabilities for
     * Progressive Web Application (PWA).
     */

    // The HTTP request that will be triggered when the signIn function is called.
    return fetch(`${this.domain}/login`, {
      method: "POST",
      headers: {
        "Content-Type": this.options.ContentType
      },
      body: body
    })
    // Before returning, format the raw Response object in json.
    .then((response) => response.json())
    // Add the token from the credentials to the options object and return the credentials object.
    .then((credentials) => {
      this.options.api_key = credentials.token;
      return credentials;
    })
  }
  signOut(){

    // return true or an error
    return fetch(`${this.domain}/logout`,{
      method: "POST",
      headers: {
        authorization: this.options.api_key
      }
    })
  }
}

See Related documentation for more information on Response object and Fetch API.

// main.ts

import Vue from "vue";
import http from "./plugins/vue-http/index";

// This line will load the plugin in the Vue.js global scope.
Vue.use(http);

const vm = new Vue({ ... }).mount("#app");

// Allow to use the Vue Http plugin in other plugins/modules.
// For example: Vuex
export const $http = vm.$http

Usage

Simple usage example:

Here is a simple sign-in form with 2 input fields (username, password).

Once the user fills the 2 inputs and clicks on the submit button, the login method is triggered. Inside the login method, the Vue Http plugin executes the signIn request of the auth namespace.

The important line here. this.$http.auth.signIn(this.username, this.password);

The format to use the plugin is always the same:

  • this.$http.[namespace].[call function]
<template>
  <div>
    <h2>Using Vue Http</h2>
    <p>User is authenticated: {{isAuthenticated}}</p>

    <input v-model="username" placeholder="Username" />
    <input v-model="password" placeholder="Password" />
    <button @click="login" :disabled="isAuthenticated">Submit</button>
    <button @click="logout" :disabled="!isAuthenticated">Sign out</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        username: "",
        password: "",
        isAuthenticated: false,
      };
    },
    methods: {
      login() {
        const self = this;

        // username and password must not be empty
        if (username !== "" && password !== "") {
          // Call the signIn function of the auth namespace.
          // Note: auth namespace is defined in the previous section (#initialisation)
          this.$http.auth
            .signIn(this.username, this.password)
            .then((token) => {
              if (token) self.isAuthenticated = true;
              else self.isAuthenticated = false;
            })
            .catch((error) =>
              console.log("Error in the signIn method:", error)
            );
        }
      },
      logout() {
        const self = this;
        this.$http.auth
          .signOut()
          .then((response) => {
            self.isAuthenticated = false;
          })
          .catch((error) => {
            console.error(error);
          });
      },
    },
  };
</script>

Related documentation

License

MIT

Copyrith (c) 2020, Audren Guillaume for the Luxembourg Institute of Science and Technology (LIST)

0.0.3

4 years ago

0.0.2

4 years ago