0.1.1 • Published 1 year ago

@labyrinthos/http v0.1.1

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

Labyrinthos HTTP

Simple library for doing http requests in node and the browser.

Installation

Script Tag

<script src="https://cdn.jsdelivr.net/npm/@labyrinthos/http/lib/browser.mjs"></script>

Node

import http from "@labyrinthos/http/node"

Bundled for browser

import http from "@labyrinthos/http"

Browser API

http`<method>`(url)
http`<method>`(options)

http.use(useOptions)

Options

method is the HTTP method to use (get, post, etc.). url is the relative url to fetch. options is an object of options (including the url)

  • url same as the url argument
  • data data to send in its raw form (ex: an object for json or form-encoded)
  • dataType the type of data being sent, default is "json". some types have a built in converter documented below.
  • headers any headers to include with the request. Content-Type will be set automatically if the dataType has a built in converter.
  • query an object with any parameters to send in the query string.
  • credentials fetch credentials option.
  • type response type to parse as. See the fetch Response Instance methods for details.

use & useOptions

The use function returns a new http instance that can be used in the same way as the base http export, but with the configuration given.

useOptions can set a default value for any option in addition to having its own props to setup other parts of the request.

  • baseURL the base URL to use for all requests. Can be either an absolute URL as a string, or a URL object.

Examples

//  urls for the base export are relative to the current page
await http`get`({
    url: "/browser.mjs",
    type: "text"
})

const echo = http.use({ baseURL: "https://echo.axel669.net" })
await echo`get`({
    url: "/",
    query: {
        a: 10,
        b: 12
    }
})

Node API

const local = http({ baseURL: "http://localhost:45067" })
local`<method>`(options)

The node API is nerly identical to the browser API with 2 differences: 1. All instances need to be initialized using the same call signature as http.use (there is no location object to be the default). 2. The options accepts an agent property that is a node http agent

Examples

const local = http({ baseURL: "http://localhost:45067" })
const response = await local`get`({
    url: "/browser.mjs",
    type: "text",
})

const echo = http({ baseURL: "https://postman-echo.com/get" })
const echoRes = await echo`get`({
    url: "/",
    query: { a: 10 }
})
0.1.1

1 year ago

0.1.0

1 year ago