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

gavins-cool-api-helper

v0.0.4

Published

Just some helper utilities

Downloads

1

Readme

api-helper

Just some clientside-friendly utilities for using APIs.

Quick start example

/**
 * Create the API instance with default origin and headers
 */
const origin = 'https://mydomain.com'
const defaultHeaders = {'x-tracking-id' : 'aaa-bbb-ccc-ddd'}
const api = new API(origin, defaultHeaders)

/**
 * Create a custom type and add a formatter to always return it. 
 */
type MyResponse = {
    status: number
    message: string
    success: boolean
    data: unknown
}
api.formatResponse(async res => {
    const json = await res.json()

    const data: MyResponse = {
        status: res.status,
        message: res.ok ? json.message : 'something went wrong',
        success: res.ok,
        data: json
    }

    return data
})

/**
 * Now we can make typed API requests 
 */
const userResponse = await api.GET<MyResponse>('/api/users/1234')
if(userRespnose.success){
    handleSuccess(userResponse.data)
}else{
    handleFailure(userResponse.data, userResponse.status)
}

Construction

When creating the class you can pass in optional base origin and headers that will be used for every request.

Note that if not provided the base origin will be window.location.origin.

Default headers always include Accept and Content-Type set to application/json unless overriden.

The default fetcher used is the global fetch or window.fetch. If neither of these are available, one should be provided in the constructor or by using .setFetch()

Example

import { fetch as fetcher} from 'node-fetch'
const origin = 'https://mydomain.com'
const headers = {'x-tracking-id' : 'aaaaa-bbbbb-ccccc-ddddd'}

const api = new API(
    origin,  // default: window.location.origin
    headers, // default: application/json accept & content-type headers
    fetcher  // default: fetch ?? window.fetch
)

Methods

.setFetch(fetch: FetchFunc): API

Optionally set the fetcher for the instance.

For example if you are using the class in an environment where window.fetch is not available

Example

api.setFetch(require('fetch'))

const res = await api
    .GET('/api/users/1234)

.setHeaders(headers: ApiHeaders): API

Add / Overwrite the default headers that are used on every request. Useful if you need to add headers after some requests are already made.

Example

const api = new API('https://mydomain.com')

// request some authorisation tokens
const authResponse = await api
    .withJson({grant_type: 'authorization_code', client_id, client_secret})
    .POST('/api/auth/tokens')
const tokens = await authResponse.json()

// set the token in the header so all subsequent requests will use it automatically
api.setHeaders({authorization: `Bearer ${tokens.access_token}`})

// now we can use endpoints that require auth headers to be used
const userResponse = await api.GET('/api/users/1234')
const userDetails = await userResponse.json()

.formatResponse(callback: ResponseFormatter): void

Optionally configure the shape of the response returned after making a request.

If not used, the returned response is always the fetch Response type.

Example

// ...
type MyResponse = {
    response: Response
    status: number
    message: string
}
api.formatResponse(async res => {
    const json = await res.json()

    const data: MyResponse = {
        response: res,
        status: res.status,
        message: res.ok ? 'success' : 'failure',
    }
})
// ...

.withHeaders(headers: ApiHeaders): API

Sets the headers for this request only.

This is in addition to the default headers.

Example

const response = api
    .withHeaders({Authorization: `Bearer ${authToken}`})
    .GET('/api/users/1234')

.withParams(params: GetParams): API

Sets the query string parameters for this request.

Example

const response = api
    .withParams({include: 'email,firstName,lastName'})
    .GET('/api/users/1234')

.withJson(body: JsonBody): API

Sets the json body for this request.

Example

const response = api
    .withJson({firstName: 'Alice', lastName: 'Aardvark'})
    .POST('/api/users')

.rawBody(body: string): API

Sets a raw body to be used for this request.

Example

const response = api
    .withHeaders({'content-type': 'text/html; charset=utf-8'})
    .rawBody('<p class="user-bio">This is some content to save! 🤣<p>')
    .POST('/api/users/1234/bio')

.<T>DELETE|GET|POST|PUT|PATCH(url: string): Promise<CustomResponse<T>>

Makes the actual request with the given method.

Note that if you provided a type you can type the response!

Example

const res = await api
    .withJson({email: '[email protected]', username: 'Big Babs'})
    .POST<MyResponse>('/api/users')

if(res.status === 201){
    console.log(res.message) // "user created!"
}