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

@nvtx/vue-http

v1.0.2

Published

Reactive http utils for Vue 3

Downloads

3

Readme

@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.