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

fetch-rails

v0.8.3

Published

wrapper fetch with rails CSRF token.

Downloads

83

Readme

fetch-rails

dockerize Use GitHub's fetch library with Ruby on Rails. Based heavily on this wrapper to encapsulate some of the callback handling of HTTP status codes.

Installation

npm install fetch-rails --save

Javascript vainilla

  • All responses in JSON
fetch(url, options).then((response) => response.json()).catch((response) => response.json())
  • GET with params
// params = { q: { name: "Jhon" } }
fetch("apiUrl?q%5Bname%5D=Jhon", options).then((response) => response.json()).catch((response) => response.json())
  • POST, PUT, DELETE request
fetch(url, {
  method: 'POST',
  body: JSON.stringify(body),
}).then((response) => response.json()).catch((response) => response.json())

With fetch-rails, it's more simple and you can getCSRF, encodeParams, checkStatus, set default json headers, set default credentials, and you can override all of this.

global override

import Fetch from "fetch-rails"
Fetch.defaultHeaders = () => ({
  "X-Requested-With": 'XMLHttpRequest',
  'Accept': 'application/json',
  'Content-Type': 'application/json',
  'Authorization': 'Bearer 1234',
})

or override by request

import Fetch from "fetch-rails"
Fetch.json("apiUrl", {}, {headers: { ...Fetch.defaultHeadersJSON, "Authorization": 'Bearer 1234'} })

Usage

JSON GET request

Fetch.json('https://jsonplaceholder.typicode.com/posts')
  .then( function( posts ){
    console.log( posts ) // response in json
  });

Send params without encoding

Fetch.json('https://jsonplaceholder.typicode.com/posts', { search: { name: "Jhon" }})
  .then( function( posts ){
    console.log( posts ) // response in json
  });

JSON POST request

Fetch.postJSON('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1
  })
  .then( function( response ){
    console.log(response) // response in json
  }).catch( function( error ){
    console.log(error) // error in json
  });

JSON PUT request

Fetch.putJSON('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1
  })
  .then( function( response ){
    console.log(response) // response in json
  }).catch( function( error ){
    console.log( error ) // error in json
  });

JSON DELETE request

Fetch.deleteJSON('https://jsonplaceholder.typicode.com/posts')
  .then( function( response ){
    console.log(response) // response in json
  }).catch( function( error ){
    console.log(error) // error in json
  });

HTML GET request

Fetch.html('/api/get-html')
  .then( function( response ){
    document.body.innerHTML = response.data;
  });

Text GET request

Fetch.text('/api/get-text')
  .then( function( text ){
    document.querySelector('.item').innerText = text;
  });

Fetch.checkStatus

The checkStatus function return a Promise and parse the error in json.

  import Fetch from 'fetch-rails'

  Fetch.postJSON('/comment', comment)
  .then( (comment) => {
    console.log(comment) // { text: "Hi" }
  })
  .catch( (errors) => {
    console.log(errors)  // { text: ["can't be blank] }
  })

  function checkStatus(response) {
    return new Promise( (resolve, reject) => {
      if(response.status >= 200 && response.status < 300) {
        resolve(response)
      }else {
        response.json().then( (response_json) => {
          reject(response_json)
        })
      }
    })
  }

You can override checkStatus function like this

  import Fetch from 'fetch-rails'

  Fetch.checkStatus = myFunction

Support

Rails

  • Rails 4.0+

Browsers

  • Chrome latest
  • Safari latest
  • Firefox latest
  • Opera latest
  • IE 9+
  • Safari mobile latest
  • Chrome mobile latest