Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

irajs

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

irajs - npm Package Compare versions

Comparing version 0.0.5 to 0.0.6

10

CHANGELOG.md

@@ -5,2 +5,12 @@ # Changelog

## [0.0.6] - 2020-08-30
### Added
- `on()` event listeners, currently functioning with on "request" and "response" events occur.
### Fixed
- `.text` method will return `""` if text is from a binary.
## [0.0.5] - 2020-08-16

@@ -7,0 +17,0 @@

2

package.json
{
"name": "irajs",
"version": "0.0.5",
"version": "0.0.6",
"description": "Ira - Vanilla JS Fetch API wrapper with goodies 🍒",

@@ -5,0 +5,0 @@ "main": "src/index.min.js",

@@ -19,5 +19,5 @@ <p align="center">

Ira is a window.fetch API wrapper with some extra stuff. Debug logs, persistent settings and custom currying to request functions with a set of options.
Ira 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.
This little wrapper tries to function using current JS Engine features, no babel or typescript used. It's plain vanilla Javascript.
This 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. It's plain vanilla Javascript.

@@ -27,3 +27,3 @@ ## Npm Install

```
npm install --save irajs
npm install irajs
```

@@ -53,14 +53,8 @@

## Playground
[👉 The complete API reference](#Ira-API-Reference)
Observable playground, live examples with the power of reactivity.
## Some examples
> Recommended as start point
### Getting data
https://observablehq.com/@d3portillo/ira-fetch-wrapper
## Examples
### GET Method
```js

@@ -72,3 +66,3 @@ ira.get(`https://postman-echo.com/get?foo1=bar1&foo2=bar2`).then(({ data }) => {

### Set global headers
### Adding headers

@@ -83,3 +77,3 @@ ```js

### Parse blob to base64
### Parsing blob to base64 string

@@ -91,3 +85,3 @@ ```js

### Base URL
### Including a base URL

@@ -102,3 +96,3 @@ ```js

### Extend Ira fork
### Extending a fork

@@ -123,14 +117,4 @@ A custom settings fork of main Ira function that's gapped to provided - config

### Fetching with params
> This method extends from Ira Object
```js
ira.get("https://anendpoint", {
params: {
token: 222,
"another-token": 354,
},
})
// https://anendpoint/?token=222&another-token=354
```
## The Ira Instance

@@ -152,5 +136,6 @@

parseBlob: ?Boolean,
params: {},
...`https://developer.mozilla.org/en-US/docs/Web/API/Request`
}
GLOBAL_SETTINGS = {
IRA_SETTINGS = {
headers: {},

@@ -174,7 +159,7 @@ debug: Boolean,

ira = {
...IRA_HTTP_METHODS,
default(): IRA_HTTP_METHODS.get,
...HTTP_METHODS,
default(): HTTP_METHODS.get,
_settings: Object,
config: Function,
extend: Function() => ira /* Fork with provided settings */,
extend: Function() => ira /* Fork with provided config */,
blobToBase64: Function

@@ -186,4 +171,306 @@ }

## Ira API Reference
### Table of contents
- [ira()](#default)
- [ira.get()](#get)
- [ira.post()](#post)
- [ira.put()](#post)
- [ira.delete()](#delete)
- [ira.connect()](#connect)
- [ira.options()](#options)
- [ira.trace()](#trace)
- [ira.head()](#head)
- [ira.blobToBase64()](#blobtobase64)
- [ira.on()](#onevent)
- [ira.extend()](#extend)
- [ira.config()](#config)
- [ira.\_config](#getconfig)
- [{ baseURL }](#baseurl)
- [{ params }](#params)
- [{ debug }](#debug)
- [{ parseBlob }](#parseblob)
### HTTP Methods
This interface rules among many props and methods, **`ON_REQUEST_PROPS:` [ira#the-ira-instance](https://github.com/D3Portillo/ira#the-ira-instance)**
---
<a href="#default" id="default"># </a><b>ira</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L41 "Source")
```js
URL = "" // Your endpoint URL
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 })`
<a href="#get" id="get"># </a>ira<b>.get</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L169 "Source")
```js
URL = "" // That stuff URL
CONFIG = ON_REQUEST_PROPS
```
Same as `ira()` method.
<a href="#post" id="post"># </a>ira<b>.post</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L178 "Source")
```js
URL = "" // An endpoint
CONFIG = ON_REQUEST_PROPS
```
The POST method, `ira.post("/something")` is the same as `fetch("/something", { method: "POST" })`.
You can include a body doing:
```js
ira.post("/something", {
body: "some-body",
})
```
<a href="#put" id="put"># </a>ira<b>.put</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L179 "Source")
```js
URL = "" // https://something
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:
```js
ira.put("/something", {
body: "some-body",
})
```
You also can show some debug messages on console by adding `debug: true`.
```js
ira.put("/something", {
body: "some-body",
debug: true,
})
// This will log on request start messages and
// When promise is resolved with your data
```
<a href="#delete" id="delete"># </a>ira<b>.delete</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L175 "Source")
```js
URL = "" // Place an URL here
CONFIG = ON_REQUEST_PROPS
```
That DELETE Http Method, `ira.delete("/api")` is the same as `fetch("/api", { method: "DELETE" })`.
<a href="#connect" id="connect"># </a>ira<b>.connect</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L180 "Source")
```js
URL = "" // The place you want data from
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:
```js
{
headers: {}, // Your request headers
body: ?String, // Your request body
debug: ?Boolean, // if true shows some stuff on console
parseBlob: ?Boolean, // if false .blob event wont execute
params: {} // Your URL params ?reqid=3&something=data
}
```
<a href="#options" id="options"># </a>ira<b>.options</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L181 "Source")
```js
URL = "" // That URL you want data from
CONFIG = ON_REQUEST_PROPS
```
When doing the OPTIONS Http method `ira.options("/api")` results to be same as doing `fetch("/api", { method: "OPTIONS" })`.
<a href="#trace" id="trace"># </a>ira<b>.trace</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L41 "Source")
```js
URL = "" // Production or dev endpoint
CONFIG = ON_REQUEST_PROPS
```
TRACE method, `ira.trace("/api")` is the same as `fetch("/api", { method: "TRACE" })`.
<a href="#head" id="head"># </a>ira<b>.head</b>([<i>URL, CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L182 "Source")
```js
URL = "" // Some resource URL
CONFIG = ON_REQUEST_PROPS
```
The HEAD method, `ira.head("/api")` is the same as `fetch("/api", { method: "HEAD" })`.
### Yes, more cool methods
<a href="#blobtobase64" id="blobtobase64"># </a>ira<b>.blobToBase64</b>([<i>Blob</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L207 "Source")
```js
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 `""`
<a href="#onevent" id="onevent"># </a>ira<b>.on</b>([<i>Event</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L233 "Source")
```js
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:
```js
ira.on("request", (request) => {
const { url, statusCode, method, headers, config } = request
if (statusCode == 200) {
console.log("This will always succeed")
/*
This callback is made as soon as request is made
so statusCode is 200, you can log config, check path and include some magic
*/
}
})
ira.on("response", (response) => {
const { url, statusCode, method, headers, config } = request
// Lets say you want to kick user when it's forbidden
if (statusCode == 403) killSession()
})
```
<a href="#extend" id="extend"># </a>ira<b>.extend</b>([<i>CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L244 "Source")
```js
CONFIG = {
headers: {},
debug: Boolean,
parseBlob: Boolean,
baseURL: ?String,
} // @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:
```js
const request = ira.extend({
headers: {
"x-api-key": "somethingawesome",
"Content-type": "application/json",
},
})
// Then you can avoid rewriting those headers again
request.get("/endpoint", {
body: {
user: "D3Portillo",
base: "Somebass",
},
})
// This will include those headers added on .extend call
```
<a href="#config" id="config"># </a>ira<b>.config</b>([<i>CONFIG</i>]) [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L194 "Source")
```js
CONFIG = {
headers: {},
debug: Boolean,
parseBlob: Boolean,
baseURL: ?String,
} // @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.
```js
const req = ira.extend({
baseURL: "https://google.com",
})
// Now, let's pretend you want to change that baseURL
req.settings({
baseURL: "https://duckduckgo.com",
})
// This will replace request's baseURL google.com with duckduck.go
```
### Acces current config
<a href="#getconfig" id="getconfig"># </a>ira<b>.\_config</b><i>\<CONFIG></i> [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L188 "Source")
```js
CONFIG = {
headers: {},
debug: Boolean,
parseBlob: Boolean,
baseURL: ?String,
} // @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
<a href="#baseurl" id="baseurl"># </a>ira<b>.\_config.baseURL</b><i>\<Boolean></i> [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L74 "Source")
You can add a baseURL to make your requests.
```js
ira.settings({
baseURL: "https://localhost:5000",
})
ira.get("/anurl", {
params: {
somelikeparam: "somevalue",
},
}) // Fetches https://localhost:5000/anurl
```
<a href="#params" id="params"># </a>ira<b>.\_config.params</b><i>\<Object></i> [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L76 "Source")
You can add params on your request like this:
```js
ira.get("/anurl", {
params: {
somelikeparam: "somevalue",
},
}) // Fetches to /anurl?somelikeparam=somevalue
```
<a href="#debug" id="debug"># </a>ira<b>.\_config.debug</b><i>\<Boolean></i> [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L140 "Source")
If `true` will log stuff on console when a request is made and when a response is obtained.
<a href="#parseblob" id="parseblob"># </a>ira<b>.\_config.parseBlob</b><i>\<Boolean></i> [<>](https://github.com/D3Portillo/ira/blob/master/src/index.js#L105 "Source")
If `false` any request you make wont perform a **response.blob** and your data will resolve with this as `null`
### Some resources
- Source: [/src/index.js](./src/index.js)

@@ -193,2 +480,4 @@ - Changelog: [/CHANGELOG.md](./CHANGELOG.md)

> **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 : )
---
**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 : )

@@ -6,6 +6,12 @@ /**

* @see https://github.com/d3portillo/ira
* @version 0.0.5
* @version 0.0.6
*/
function f(){const INIT_IRA_CONFIG={headers:{},debug:false,parseBlob:true,baseURL:undefined};const IRA_METHODS={get:"GET",put:"PUT",post:"POST",head:"HEAD",delete:"DELETE",connect:"CONNECT",options:"OPTIONS",trace:"TRACE"};const IRA_LOG="IraFetch >>>";let persistentIraConfig={};function makeIraFetch(method="POST",options={acceptsBody:true}){
function f(forkConfig={}){const IRA_CONFIG={headers:{},debug:false,parseBlob:true,baseURL:undefined};const IRA_METHODS={get:"GET",put:"PUT",post:"POST",head:"HEAD",delete:"DELETE",connect:"CONNECT",options:"OPTIONS",trace:"TRACE"};const IRA_LOG="IraFetch >>>";const deepify=(obj={})=>{const json={};Object.keys(obj).forEach(prop=>{const V=obj[prop];json[prop]=typeof V!="string"?JSON.stringify(V):V});return json}
/**
* Ira.get Method
* @param { String } url
* @param { IRA_CONFIG } extra
*/
function ira(url="/",extra){return makeIraFetch(IRA_METHODS.get,{acceptsBody:false})(url,extra)}function makeIraFetch(method="POST",opt={acceptsBody:true}){
/**
* Ira Response Object

@@ -23,11 +29,11 @@ * @typedef { Object } IraResponse

* @param {{ headers: {}, body: ?String, params: {}, debug: Boolean, parseBlob: Boolean }} extra - Your normal fetch opts
* @param { INIT_IRA_CONFIG } config - Custom Ira config
* @return { Promise<IraResponse> }
*/
const fetchPromise=(url,extra={},config={})=>{config={...INIT_IRA_CONFIG,...extra,...config,...persistentIraConfig};let{headers:headers={},body:body="",params:params={}}=extra;const deepify=(obj={})=>{const json={};Object.keys(obj).forEach(prop=>{let value=obj[prop];json[prop]=typeof value!="string"?JSON.stringify(value):value});return json};headers=deepify({...config.headers,...headers});const contentType=headers["Content-Type"]||headers["Content-type"]||"";if(contentType.includes("json"))body=deepify(body);try{let{baseURL:baseURL,parseBlob:parseBlob}=config;url=baseURL?`${baseURL}${url}`:url;const paramsChain=new URLSearchParams(params).toString();if(paramsChain.length){const lastChar=url.charAt(url.length-1);if(lastChar!="/")url=`${url}/`;url=`${url}?${paramsChain}`}const{fetch:fetch}=window;if(!fetch)throw new Error("Not inside a browser");if(!url)throw new Error("URL not provided");return new Promise(send=>{if(config.debug)console.info(`${IRA_LOG} URL='${url}' >>> SENT ⚡`);fetch(url,{...extra,method:method,headers:headers,...options.acceptsBody?{body:body}:{}}).then(response=>{const{ok:ok,status:status,statusText:statusText}=response;const clone=response.clone();Promise.all([response.text(),parseBlob?clone.blob():null]).then(([t,b])=>{if(typeof b=="string"){[t,b]=[b,t]}let json={};try{json=JSON.parse(t);if(typeof json=="string")json={}}catch(_){}if(parseBlob){const BIN_TYPES=/video|image|audio|application/g;const isBinary=BIN_TYPES.test(b.type);if(isBinary)t=""}const data={json:json,text:t,blob:b};send({data:data,ok:ok,status:status,statusText:statusText,statusCode:status,error:null});if(config.debug){console.info(`🍃 ${IRA_LOG} URL='${url}' >>> RESPONSE: `,{headers:headers,body:body,config:config,responseData:{data:data}})}})}).catch(error=>{const statusCode=500;console.error(`${IRA_LOG} - Got error on request ⛔, URL='${url}' >>> ${error}`);send({data:{json:{},text:"",blob:null},ok:false,status:statusCode,statusText:error,statusCode:statusCode,error:error})})})}catch(e){console.error(`${IRA_LOG} >>> ${e}`)}};return fetchPromise}function ira(url="string",extra=INIT_IRA_CONFIG){return makeIraFetch(IRA_METHODS.get,{acceptsBody:false})(url,extra)}
// * Attach methods to Ira obj
ira.get=makeIraFetch(IRA_METHODS.get,{acceptsBody:false});ira.head=makeIraFetch(IRA_METHODS.head,{acceptsBody:false});ira.delete=makeIraFetch(IRA_METHODS.delete,{acceptsBody:false});ira.post=makeIraFetch();ira.put=makeIraFetch(IRA_METHODS.put);ira.connect=makeIraFetch(IRA_METHODS.connect);ira.options=makeIraFetch(IRA_METHODS.options);ira.trace=makeIraFetch(IRA_METHODS.trace)
const fetchPromise=(url="/",extra={})=>{const config={...IRA_CONFIG,...extra,...forkConfig,...ira._config};let{headers:headers={},body:body="",params:params={}}=extra;headers=deepify({...config.headers,...headers});const cType=headers["Content-Type"]||headers["Content-type"]||"";if(cType.includes("json"))body=deepify(body);try{let{baseURL:baseURL,parseBlob:parseBlob}=config;url=baseURL?`${baseURL}${url}`:url;const paramsChain=new URLSearchParams(params).toString();if(paramsChain.length){const lastChar=url.charAt(url.length-1);if(lastChar!="/")url=`${url}/`;url=`${url}?${paramsChain}`}const{fetch:fetch}=window;if(!fetch)throw new Error("Not inside a browser");if(!url)throw new Error("URL not provided");return new Promise(send=>{ira.__exec_on.request({url:url,statusCode:200,method:method,headers:new Headers(headers),config:config});if(config.debug)console.info(`${IRA_LOG} URL='${url}' >>> SENT ⚡`);fetch(url,{...extra,method:method,headers:headers,...opt.acceptsBody?{body:body}:{}}).then(response=>{const{ok:ok,status:status,statusText:statusText}=response;const clone=response.clone();Promise.all([response.text(),parseBlob?clone.blob():null]).then(([t,b])=>{if(typeof b=="string"){[t,b]=[b,t]}let json={};try{json=JSON.parse(t);if(typeof json=="string")json={}}catch(_){}if(parseBlob){const BIN_TYPE=/video|image|audio|ogg|pdf|rar|zip|font|7z|flash|x-/g;
// Posible blob types to binaries - this will be too ugly parsed
// to utf-8 string from resposne.text
const isBinary=BIN_TYPE.test(b.type);const isUTF8=/utf8|utf-8/gi.test(b.type);if(isBinary&&!isUTF8)t=""}const data={json:json,text:t,blob:b};const statusCode=status;send({data:data,ok:ok,status:status,statusText:statusText,statusCode:statusCode,error:null});ira.__exec_on.response({url:url,statusCode:statusCode,method:method,headers:response.headers,config:config});if(config.debug){console.info(`🍃 ${IRA_LOG} URL='${url}' >>> RESPONSE: `,{config:config,responseData:{data:data}})}})}).catch(error=>{console.error(`⛔ ${IRA_LOG} - Got error on request, URL='${url}' >>> ${error}`,{config:config});send({data:{json:{},text:"",blob:null},ok:false,status:500,statusText:error,statusCode:500,error:error})})})}catch(e){console.error(`${IRA_LOG} >>> ${e}`)}};return fetchPromise}ira.get=makeIraFetch(IRA_METHODS.get,{acceptsBody:false});ira.head=makeIraFetch(IRA_METHODS.head,{acceptsBody:false});ira.delete=makeIraFetch(IRA_METHODS.delete,{acceptsBody:false});ira.post=makeIraFetch();ira.put=makeIraFetch(IRA_METHODS.put);ira.connect=makeIraFetch(IRA_METHODS.connect);ira.options=makeIraFetch(IRA_METHODS.options);ira.trace=makeIraFetch(IRA_METHODS.trace)
/**
* Acces Ira persistent config
* @type { INIT_IRA_CONFIG }
* Acces your current Ira config
* @type { IRA_CONFIG }
*/

@@ -37,7 +43,7 @@ ira._config={}

* Sets persisten config headers or body for future requests
* @param { INIT_IRA_CONFIG } config
* @param { IRA_CONFIG } config
*/
ira.config=(config={})=>{if(!Object.entries(config).length){
// We reset config if *empty { } , is provided
config={...INIT_IRA_CONFIG}}persistentIraConfig={...config};ira._config=persistentIraConfig}
config={...IRA_CONFIG}}ira._config={...config}}
/**

@@ -48,10 +54,18 @@ * Returns a base64 String from a blob

*/
ira.blobToBase64=blob=>new Promise(returns=>{try{const reader=new FileReader;reader.onload=()=>returns(reader.result);reader.readAsDataURL(blob)}catch(e){console.error(`${IRA_LOG} - Got error on Blob parse >>> ${e}`);returns("")}})
ira.blobToBase64=blob=>new Promise(cb=>{try{const rdr=new FileReader;rdr.onload=()=>cb(rdr.result);rdr.readAsDataURL(blob)}catch(e){console.error(`${IRA_LOG} - Got error on Blob parse >>> ${e}`);cb("")}});ira.__exec_on={request:()=>null,response:()=>null}
/**
* Sets config and returns a modded Ira function
* @param { INIT_IRA_CONFIG } config
* @callback cbFunction
* @param {{ url: String, statusCode: ?Number, method: String, headers: {}, config: {} }} callbackObject
*/
/**
* Add your custom callbacks on response and request events
* @param {("request" | "response")} event
* @param { cbFunction } callback - Request or Response Objects Callback
*/
ira.on=(event,callback)=>{if(typeof callback=="function"&&ira.__exec_on[event]){ira.__exec_on[event]=callback}}
/**
* Sets config and returns a custom Ira Fork
* @param { IRA_CONFIG } config
* @returns { ira }
*/
ira.extend=config=>{const myMethods={};Object.keys(IRA_METHODS).map(name=>{myMethods[name]=(url,extra)=>ira[name](url,extra,config)});return{...myMethods,_config:config,extend:ira.extend,blobToBase64:ira.blobToBase64,config:ira.config}};return ira}
// Trying to export function
"object"==typeof exports&&"object"==typeof module?module.exports=f():"object"==typeof exports?exports.ira=f():this.ira=f();
ira.extend=(conf={})=>{conf.headers=conf.headers?conf.headers:{};const iH=ira._config.headers;conf.headers=iH?{...iH,...conf.headers}:conf.headers;const __ira=f(conf);__ira.config({...ira._config,...conf});return __ira};return ira}"object"==typeof exports&&"object"==typeof module?module.exports=f():"object"==typeof exports?exports.ira=f():this.ira=f();
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc