1.0.2 • Published 12 months ago

@nvtx/vue-http v1.0.2

Weekly downloads
-
License
ISC
Repository
gitlab
Last release
12 months ago

@nvtx/vue-http

A Vue.js library for making reactive HTTP requests.

Installation

npm install @nvtx/vue-http

Usage

To use the library, import the following modules:

import {useHttpGet, useHttpPost, useHttpPut, useHttpDelete, useClient, httpConfigurator} from "@nvtx/vue-http";

Each returns an object with the following properties:

  • state: A reactive state object that contains the response data, error, loading status, and HTTP status code.
  • request: A function that can be used to make the HTTP request.

Here is an example of how to use the useHttpGet hook to make a GET request:

import {useHttGet} from "@nvtx/vue-http";
import {watch} from "vue";

const {state, request} = useHttpGet("/api/users");

request() // Call this function in any place at any moment.

watch(() => state.response, (data) => { //Listen for changes in the response data
  console.log("Data:", data);
});

Optionally, an ID can be passed as parameter to the request function. It will result with an HTTP GET request to the route /api/users/:id.

<script setup>
  import {useHttGet} from "@nvtx/vue-http";
  import {watch} from "vue";

  const {state, request} = useHttpGet("/api/users");

  watch(() => state.response, (data) => { //Listen for changes in the response data
    console.log("Data:", data);
  });
</script>

<template>
  <button v-for="i in [1, 2, 3, 4, 5]" :key="i" @click="request(id)">
    {{i}}
  </button>
</template>

The request function returned by the useHttpPost takes a required parameter for the data that will be sent on the request. Similarly, the requestfunction for the PUT request hook takes one required argument for the data, and other optional for an ID. The request function behavior of the useHttpDelete hook is similar to the one for the GET requests, it takes an optional parameter for an ID.

Configurators

The library itself uses the axios api to make the HTTP requests. As a result, it is possible to provide the hooks with a custom configuration following the axios standards.

import {useHttpGet} from "@nvtx/vue-http";

const requestConfig = {
  headers: {
    "Authorization": "Bearer 1234567890",
    "Content-Type": "application/json",
  },
  params: {
    page: 1,
    limit: 10,
  },
  withCredentials: true,
  timeout: 10000,
  responseType: "json",
}

const {state, request} = useHttpGet("/api/users/friends", requestConfig); // It will use the provided configuration for the axios request.

Additionally, a reactive configuration builder can be imported from the library. It would be helpful if some of the needed information for the config is asynchronous. Here it's an example:

<script setup>
  import {useHttpGet, useHttpPost, httpConfigurator} from "@nvtx/vue-http";
  import {onMounted, watch} from "vue";
  import {dummyArticle} from "./mocks";
  
  const edition = useHttpGet("/api/editions");
  
  const articleConfigBuilder = httpConfigurator();
  
  const {state, request} = useHttpPost("/api/articles", articleConfigBuilder);
  
  onMounted(() => {
    edition.request();
  });
  
  watch(() => edition.state.response, (data) => {
    const editionId = data[0].id;
    
    // Even though at this point the request has already been declared,
    // the httpConfigurator is a reactive object whose value will be read at the
    // time the `request` function is called.
    articleConfigBuilder.addParam("edition", editionId);
    articleConfigBuilder.withCredentials(true);
    articleConfigBuilder.withAuthorization("myToken", "Basic");
    
    request(dummyArticle); // Calls the request with the current configuration value.
  });
</script>

The resulting configuration used for the request will be:

{
  params: {
    edition: "someDummyEditionId",
  },
  headers: {
    Authorization: "Basic myToken",
  },
  withCredentials: true,
}

Clients

When needed, the library provides a useClient hook, which is a way to consume the same resource with any of the supported HTTP protocols. Internally, the useClient composable uses each of the HTTP hooks provided by the library. In addition, the composable handles the configurators in the same way described above.

<script setup>
  import {useClient, httpConfigurator} from "@nvtx/vue-http";
  
  // Creates the configurator that will be used.
  const config = httpConfigurator()
  
  // Creates a client to consume the resource.
  const {
    loading, // True when any of the protocols is in action.
    getLoading,
    get,
    getResponse,
    postloading,
    post,
    putLoading,
    put,
    removeLoading,
    remove,
  } = useClient("/api/auth", config);
  
  const submitInfo = () => {
    // At this point the configurator has already the required authorization token.
    post({
      ...myResource
    });
  }
  
  onMounted(() => {
    get();
  });
  
  watch(getLoading, (newValue) => {
    if (newValue) return; // The old value was false, so it just started loading.
    const token = getResponse.value.token
    localStorage.setItem("token", token);
    httpConfigurator.withAuthorization(token); // The default authorization type is Bearer
  });
  
  watch(postloading, (newValue) => {
    if (newValue) return; // The old value was false, so it just started loading.
    
    alert("Item created successfully");
  });
</script>

<template>
  <loading-component v-if="loading" />
  <button v-else @click="submitInfo">Submit info</button>
</template>

Types

The library was build in typescript, there is an example of the usage when using typescript:

<script setup lang="ts">
  import {useHttpGet, useHttpPost, useHttpPut, useHttpDelete} from "@nvtx/vue-http";
  import {onMounted} from "vue";

  interface Edition {
    id: string,
    title: string,
    description: string,
  }
  
  interface EditionResource {
    title: string,
    description: string,
  }
  
  const editions = useHttpGet<Edition[]>("/api/editions");

  // The first generic argument indicates the response type, and the seond indicates the request data type.
  const createEdition = useHttpPost<Edition, EditionResource>("/api/editions");
  // The first generic argument indicates the response type, and the seond indicates the request data type.
  const updateEdition = useHttpPut<Edition, EditionResource>("/api/editions");

  const deleteEdition = useHttpDelete<Edition>("/api/editions");
  
  onMounted(() => {
    const resource: EditionResource = {
      title: "dummyTitle",
      description: "dummyDescription",
    }
    
    createEdition.request(resource);
  });
</script>

Warming: The use of generic types is not supported currently in the useClient composable.

To-do

Pending

  • Allow override response type when ID parameter is included in HTTP GET request function.

Completed

  • Create a client to instantiate the GET, POST, PUT, and DELETE requests when using the same url.
1.0.2

12 months ago

1.0.1

12 months ago

0.0.11

12 months ago

0.0.10

12 months ago

0.0.9

12 months ago

0.0.8

12 months ago

0.0.7

12 months ago

0.0.6

12 months ago

0.0.5

12 months ago

0.0.4

12 months ago

0.0.3

12 months ago

0.0.2

12 months ago

0.0.1

12 months ago