项目作者: D3Portillo

项目描述 :
Vanilla JS Fetch API wrapper with goodies 🍒
高级语言: JavaScript
项目地址: git://github.com/D3Portillo/ira.git
创建时间: 2020-08-12T00:36:41Z
项目社区:https://github.com/D3Portillo/ira

开源协议:MIT License

下载








📝 Codepen
@d3portillo/ira-fetch-wrapper">🔬 Observable ・
📦 Npm


Ira Fetch: Vanilla JS Fetch API wrapper with goodies 🍒

Irajs is a small ~ 3kb function which enhances current Fetch API with more, more goodies. Ira code isn’t chopped, replaced with random chars or similar on .min.js version, it’s just minified.

Ira goodies include debug logs, persistent settings and custom currying to request functions with a set of options. The little wrapper tries to function using current JS Engine features, no babel or typescript used just plain vanilla Javascript.

Version
Size
Downloads

Npm Install

  1. npm install irajs

Yarn Install

  1. yarn add irajs

CDN Load

  1. <script src="https://d3portillo.github.io/ira/src/index.min.js"></script>

Usage

  1. import ira from "irajs"
  2. // Requires
  3. const ira = require("irajs")
  4. // Start playing around
  5. ira.get("/stuff")

👉 The complete API reference

Some examples

Getting data

  1. ira.get(`https://postman-echo.com/get?foo1=bar1&foo2=bar2`).then(({ data }) => {
  2. console.log(data.json, data.text, data.blob) // * Automatic response parsing
  3. })

Adding headers

  1. ira.config({
  2. headers: {
  3. "Content-type": "application/json",
  4. },
  5. })

Parsing blob to base64 string

  1. const blob = new Blob(["something"])
  2. ira.blobToBase64(blob).then((base64) => console.log(base64))

Including a base URL

  1. const request = ira.extend({
  2. baseURL: "https://yourendpoint.com/dev/branch",
  3. })
  4. // Now you can do
  5. request.get("/binary") //https://yourendpoint.com/dev/branch/binary

Extending a fork

A custom settings fork of main Ira function that’s gapped to provided - config

  1. const request = ira.extend({
  2. headers: {
  3. "x-api-key": "somsaltedencryptedawesomekey",
  4. },
  5. debug: true /* Shows Ira stuff on console */,
  6. parseBlob: false /* Do not include .blob on data */,
  7. })
  8. // Now you can make requests containing those settings
  9. request
  10. .get("https://something")
  11. .then(({ data: { blob } }) => console.info(null == blob))
  12. // The blob response inside data obj is null

This method extends from Ira Object

The Ira Instance

  1. RESPONSE = {
  2. data: { json: Object, text: String, blob: ?Blob }
  3. ok: Boolean,
  4. status: Number,
  5. statusText: String,
  6. statusCode: status<Number>,
  7. error: ?Error
  8. }
  9. ON_REQUEST_PROPS = {
  10. headers: {},
  11. body: ?String,
  12. debug: ?Boolean,
  13. parseBlob: ?Boolean,
  14. params: {},
  15. ...`https://developer.mozilla.org/en-US/docs/Web/API/Request`
  16. }
  17. IRA_SETTINGS = {
  18. headers: {},
  19. debug: Boolean,
  20. parseBlob: Boolean,
  21. baseURL: ?String,
  22. }
  23. HTTP_METHODS = {
  24. get: Function,
  25. put: Function,
  26. post: Function,
  27. head: Function,
  28. delete: Function,
  29. connect: Function,
  30. options: Function,
  31. trace: Function,
  32. }
  33. // Exported object { Main }
  34. ira = {
  35. ...HTTP_METHODS,
  36. default(): HTTP_METHODS.get,
  37. _settings: Object,
  38. config: Function,
  39. extend: Function() => ira /* Fork with provided config */,
  40. blobToBase64: Function
  41. }

Ira will return a void response if an error ocurred and status of 500.

Ira API Reference

Table of contents

HTTP Methods

This interface rules among many props and methods, ON_REQUEST_PROPS: ira#the-ira-instance


# ira([URL, CONFIG]) <>

  1. URL = "" // Your endpoint URL
  2. CONFIG = ON_REQUEST_PROPS

The GET method, ira("/something") is the same as fetch("/something"). The difference is ira.get returns a Promise which resolves to an Object including .json, .text and .blob methods.

ira().then(({data}) => { data.json | data.text | data.blob })

# ira.get([URL, CONFIG]) <>

  1. URL = "" // That stuff URL
  2. CONFIG = ON_REQUEST_PROPS

Same as ira() method.

# ira.post([URL, CONFIG]) <>

  1. URL = "" // An endpoint
  2. CONFIG = ON_REQUEST_PROPS

The POST method, ira.post("/something") is the same as fetch("/something", { method: "POST" }).

You can include a body doing:

  1. ira.post("/something", {
  2. body: "some-body",
  3. })

# ira.put([URL, CONFIG]) <>

  1. URL = "" // https://something
  2. CONFIG = ON_REQUEST_PROPS

The HTTP PUT method, ira.put("/api") is the same as fetch("/api", { method: "PUT" }).

You can include a body doing:

  1. ira.put("/something", {
  2. body: "some-body",
  3. })

You also can show some debug messages on console by adding debug: true.

  1. ira.put("/something", {
  2. body: "some-body",
  3. debug: true,
  4. })
  5. // This will log on request start messages and
  6. // When promise is resolved with your data

# ira.delete([URL, CONFIG]) <>

  1. URL = "" // Place an URL here
  2. CONFIG = ON_REQUEST_PROPS

That DELETE Http Method, ira.delete("/api") is the same as fetch("/api", { method: "DELETE" }).

# ira.connect([URL, CONFIG]) <>

  1. URL = "" // The place you want data from
  2. CONFIG = ON_REQUEST_PROPS

Doin a CONNECT method ira.connect("/api") is same as fetch("/api", { method: "CONNECT" }).

You can include this config on your request:

  1. {
  2. headers: {}, // Your request headers
  3. body: ?String, // Your request body
  4. debug: ?Boolean, // if true shows some stuff on console
  5. parseBlob: ?Boolean, // if false .blob event wont execute
  6. params: {} // Your URL params ?reqid=3&something=data
  7. }

# ira.options([URL, CONFIG]) <>

  1. URL = "" // That URL you want data from
  2. CONFIG = ON_REQUEST_PROPS

When doing the OPTIONS Http method ira.options("/api") results to be same as doing fetch("/api", { method: "OPTIONS" }).

# ira.trace([URL, CONFIG]) <>

  1. URL = "" // Production or dev endpoint
  2. CONFIG = ON_REQUEST_PROPS

TRACE method, ira.trace("/api") is the same as fetch("/api", { method: "TRACE" }).

# ira.head([URL, CONFIG]) <>

  1. URL = "" // Some resource URL
  2. CONFIG = ON_REQUEST_PROPS

The HEAD method, ira.head("/api") is the same as fetch("/api", { method: "HEAD" }).

Yes, more cool methods

# ira.blobToBase64([Blob]) <>

  1. Blob = new Blob() // A JS Binary long object

You can parse any Blob into a base64 string by doing ira.blobToBase64. This returns a Promise which resolves into a String. This method will always resolve if there’s an error check out you console. If Promise fails will resolve to ""

# ira.on([Event]) <>

  1. Event = "request" | "response"

You can add a custom listener when ira or it’s forks perform a request or when a response is succeded. You can set this triggers like this ira.on("response", callback).

Example:

  1. ira.on("request", (request) => {
  2. const { url, statusCode, method, headers, config } = request
  3. if (statusCode == 200) {
  4. console.log("This will always succeed")
  5. /*
  6. This callback is made as soon as request is made
  7. so statusCode is 200, you can log config, check path and include some magic
  8. */
  9. }
  10. })
  11. ira.on("response", (response) => {
  12. const { url, statusCode, method, headers, config } = request
  13. // Lets say you want to kick user when it's forbidden
  14. if (statusCode == 403) killSession()
  15. })

# ira.extend([CONFIG]) <>

  1. CONFIG = {
  2. headers: {},
  3. debug: Boolean,
  4. parseBlob: Boolean,
  5. baseURL: ?String,
  6. } // @see https://github.com/D3Portillo/ira#the-ira-instance

This method returns a new Ira instance, you can replace default Settings with your custom ones. This can be helpfull if making request to API’s where headers are somewhat “persistent”, for example x-api-key’s or that.

Example:

  1. const request = ira.extend({
  2. headers: {
  3. "x-api-key": "somethingawesome",
  4. "Content-type": "application/json",
  5. },
  6. })
  7. // Then you can avoid rewriting those headers again
  8. request.get("/endpoint", {
  9. body: {
  10. user: "D3Portillo",
  11. base: "Somebass",
  12. },
  13. })
  14. // This will include those headers added on .extend call

# ira.config([CONFIG]) <>

  1. CONFIG = {
  2. headers: {},
  3. debug: Boolean,
  4. parseBlob: Boolean,
  5. baseURL: ?String,
  6. } // @see https://github.com/D3Portillo/ira#the-ira-instance

This method is used to replace current ira or fork settings. This replaces .extend method stuff with those new ones you provide.

  1. const req = ira.extend({
  2. baseURL: "https://google.com",
  3. })
  4. // Now, let's pretend you want to change that baseURL
  5. req.settings({
  6. baseURL: "https://duckduckgo.com",
  7. })
  8. // This will replace request's baseURL google.com with duckduck.go

Acces current config

# ira._config\ <>

  1. CONFIG = {
  2. headers: {},
  3. debug: Boolean,
  4. parseBlob: Boolean,
  5. baseURL: ?String,
  6. } // @see https://github.com/D3Portillo/ira#the-ira-instance

If you want to check current ira config do ira._config. This is supposed to be changed with ira.config(), still you can set ira.\_config.headers = {}

Config[._config] props

# ira._config.baseURL\ <>

You can add a baseURL to make your requests.

  1. ira.settings({
  2. baseURL: "https://localhost:5000",
  3. })
  4. ira.get("/anurl", {
  5. params: {
  6. somelikeparam: "somevalue",
  7. },
  8. }) // Fetches https://localhost:5000/anurl

# ira._config.params\ <>

You can add params on your request like this:

  1. ira.get("/anurl", {
  2. params: {
  3. somelikeparam: "somevalue",
  4. },
  5. }) // Fetches to /anurl?somelikeparam=somevalue

# ira._config.debug\ <>

If true will log stuff on console when a request is made and when a response is obtained.

# ira._config.parseBlob\ <>

If false any request you make wont perform a response.blob and your data will resolve with this as null

Some resources


Ira stands for: Go-to in spanish Ir-a. Can also mean rage or anger, That’s all the feelings you have while handling HTTP stuff : )