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

extracts-api

v0.1.1

Published

a package that extracts your api request with type definitions

Downloads

14

Readme

npm downloads License

Installation

Installation with latest version

npm install extracts-api@latest

or

yarn add extracts-api@latest

Usage

Class Approach

The package provides a class-based approach to interact with the API. You can create an instance of the main class, and then extend it for specific endpoints or functionalities.

import { Extracts } from "extracts-api";
import { UserLoginType, Users } from "./types";

class CoreAPI extends Extracts {
  private customGetToken() {
    // your token from client side auth or serverside auth
    const { token } = getToken();

    return `Bearer ${token}`;
  }

  public setToken(token: string) {
    jsCookie.set("key", token, {
      expires: 7,
      secure: true,
      sameSite: "Lax",
    });
  }

  constructor() {
    super({ baseURL: "https://api.example.com" });

    // Override for get method token
    this.getToken = this.customGetToken;
  }
}

class UserAPI extends CoreAPI {
  // isPrivate API that need a token authorization Bearer

  getUsers = async () => {
    return await this.fetch<Users>("/users", "GET", { isPrivate: true });
  };

  // authorization
  login = async (data: UserLoginType) => {
    const res = await this.fetch<LoginResponse>("/auth/login", "POST", {
      json: { ...data },
    });

    if (res.data.token) {
      this.setToken(res.data.token);
    }

    return res;
  };
}

const userAPI = new UserAPI();

// get a users data
userAPI.getUsers().then(res => console.log(res));

Function Approach

You can also use a function approach to interact with the API. This way, you can customize headers and options for individual API calls.

import { Extracts } from "extracts-api";
import { Users } from "./types";

const extracts = ({ isPrivate }: { isPrivate: boolean }) => {
  function getAuthToken() {
    const { token } = getToken();

    return `Bearer ${token}`;
  }

  const customHeaders = {
    Authorization: isPrivate ? `Bearer ${getAuthToken()}` : null,
  };

  // create a instance
  const instance = new Extracts({
    baseURL: "https://api.example.com",
    headers: customHeaders,
  });

  return instance;
};

export const userAPI = {
  getUsers: async () => {
    // need authorization
    return await extracts({ isPrivate: true }).fetch<Users>("/users", "GET");
  },
};

Direct ex Usage

You can also use the ex instance provided by the package directly to make API calls.

import { ex } from "extracts-api";
import { Users } from "./types";

export async function getUsers() {
  const res = await ex.get<Users>("https://api.example.com");

  return res;
}

API Reference

Class: Extracts

The main class for interacting with the API.

Constructor: new Extracts(options: ExtractsOptions)

Create a new instance of the Extracts class.

  • options (optional): An object containing configuration options for the instance.
    • baseURL (string, optional): The base URL for the API. Default is an empty string.
    • headers (object, optional): Custom headers to be included in every request. Default is an empty object.

Method: fetch<T>(path: string, method: string, options?: FetchOptions): Promise<T>

Make a fetch request to the API.

  • path (string): The path of the API endpoint to be appended to the base URL.
  • method (string): The HTTP method for the request (e.g., "GET", "POST", "PUT", etc.).
  • options (optional): Additional options for the fetch request.
    • body (FormData | null | string, optional): The request body. Default is null.
    • json (object, optional): A JSON object to be sent as the request body.
    • params (object, optional): URL parameters to be included in the request URL.
    • headers (object, optional): Custom headers to be included in the request. These headers will override the instance's default headers.
    • isPrivate (boolean, optional): Set to true if the request requires authorization. Default is false.
    • manualUrl (boolean, optional): Set to true if you want to manually provide the full request URL. Default is false.

Method: getToken(): string

Get the access token used for authorization. Override this method to provide custom token retrieval logic.

Class: CoreAPI extends Extracts

An extended class for specific endpoints or functionalities.

Constructor: new CoreAPI()

Create a new instance of the CoreAPI class.

Method: customGetToken(): string

A custom method to retrieve the access token used for authorization. Override this method to provide custom token retrieval logic.

Class: UserAPI extends CoreAPI

An extended class for additional functionalities based on CoreAPI.

Method: getUsers(): Promise<Users>

Make a fetch request to get a list of users. This method uses the fetch method of the CoreAPI class.

Function: extracts(options: { isPrivate: boolean }): Extracts

A function to create an instance of the Extracts class with custom headers.

  • options: An object containing the options for customizing the instance.
    • isPrivate (boolean): Set to true if the request requires authorization.

Returns an instance of the Extracts class with custom headers based on the provided options.

Global Variable: ex

An instance of the Extracts class with default options.

Method: get<T>(url: string): Promise<T>

Make a GET request to the specified URL using the default ex instance.

  • url (string): The URL to make the GET request to.

Returns a promise that resolves to the response data.

License

This project is licensed under the MIT License.