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

nextclient

v1.0.5

Published

use http request in very easy way

Downloads

343

Readme

NextClient API Documentation

Overview

The NextClient library provides a simple and consistent interface for interacting with RESTful APIs. It supports multiple HTTP methods (GET, POST, PUT, PATCH, DELETE) and includes helpers for working with query parameters, JSON data, and FormData.


Installation

Include the library in your project by importing the necessary classes:

import NextClient from "nextclient";

Usage

1. Initialize the Client

Create an instance of the NextClient by specifying the base URL of your API.

// init your client
const client = new NextClient("https://api.example.com", {
  headers: {
    Authorization: "Bearer YOUR_API_TOKEN",
  },
});

2. Available Methods

GET Requests

Use get() to fetch data. Optionally include query parameters.

client
  .get("/users", { limit: 10, page: 1 })
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

POST Requests

Use post() to send data as JSON.

client
  .post("/users")
  .json({ name: "John Doe", email: "[email protected]" })
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

PUT Requests

Use put() to update resources.

client
  .put("/users/1")
  .json({ email: "[email protected]" })
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

PATCH Requests

Use patch() for partial updates.

client
  .patch("/users/1")
  .json({ email: "[email protected]" })
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

DELETE Requests

Use delete() to remove a resource.

client
  .delete("/users/1")
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

3. Form Data Handling

If you need to send FormData instead of JSON, use the form() method.

client
  .post("/upload")
  .form({
    name: "example",
  })
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

You can also append files:

client
  .post("/upload")
  .form({
    name: "example",
  })
  .append("file", File)
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

You can also append multiple files:

const data = {
  name: "example",
};

const request = client.post("/upload").form(data);

// For List for files
[f1, f2, f2].forEach((file) => {
  request.append("files", File);
});

// for signal files
request.append("profile", ProfileFile);

// finally send request
request
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

4. Handling Errors

The library throws an HttpError for non-200 HTTP responses. Handle it like this:

client
  .get("/invalid-endpoint")
  .send()
  .catch((error) => {
    if (error instanceof HttpError) {
      console.error(`HTTP Error ${error.statusCode}:`, error.response);
    } else {
      console.error("Request failed:", error);
    }
  });

Classes Overview

NextClient

Main entry point to configure the API client.

  • Constructor

    • baseUrl: Base URL for all requests.
    • init: Default RequestInit settings (e.g., headers).
  • Methods

    • .get(path, query?)
    • .post(path, query?)
    • .put(path, query?)
    • .patch(path, query?)
    • .delete(path, query?)

ToPath

Intermediate handler for HTTP methods.

  • Methods
    • .form(data): Converts JSON to FormData.
    • .json(data): Sends JSON body.
    • .send(headers?): Executes the request.

JsonRequest

Handles sending JSON payloads with the Content-Type: application/json header.


FormRequest

Handles sending FormData, supporting file uploads.


HttpError

Custom error for non-200 responses.

  • Properties
    • statusCode: HTTP status code.
    • response: Error response text or object.

Examples

Fetch with Query Parameters /search?term=example&limit=5

client
  .get("/search", { term: "example", limit: 5 })
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

Create a Resource

client
  .post("/items")
  .json({ name: "New Item", description: "A test item" })
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

Update a Resource

client
  .put("/items/1")
  .json({ description: "Updated description" })
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

Upload a File

const file = new File(["Hello, world!"], "hello.txt", { type: "text/plain" });

client
  .post("/upload")
  .form({})
  .append("file", file)
  .send()
  .then((response) => console.log(response))
  .catch((error) => console.error(error));

Error Handling Example

client
  .get("/non-existent")
  .send()
  .catch((error) => {
    if (error instanceof HttpError) {
      console.error("Server responded with an error:", error.response);
    } else {
      console.error("An unexpected error occurred:", error);
    }
  });

License

MIT License. See LICENSE file for details.