sk-fetch-wrapper

A wrapper around isomorphic fetch that makes dealing with JSON/FormData/GraphQL a bit simpler

Usage no npm install needed!

<script type="module">
  import skFetchWrapper from 'https://cdn.skypack.dev/sk-fetch-wrapper';
</script>

README

sk-fetch-wrapper

A wrapper around isomorphic fetch that makes dealing with JSON/FormData/GraphQL a bit simpler.

Install

npm install --save sk-fetch-wrapper

Usage

JSON

// Alternatively import from 'sk-fetch-wrapper/lib/json'
import { getJSON, postJSON, putJSON, deleteJSON } from 'sk-fetch-wrapper';

getJSON('/fake/endpoint').then(res => {
  // do stuff with parsed JSON response
});

postJSON('/fake/endpoint', {
  name: 'Sam',
  age: 24
}).then(res => {
  // do stuff with parsed JSON response
});

putJSON('/fake/endpoint', {
  name: 'John'
}).then(res => {
  // do stuff with parsed JSON response
});

deleteJSON('/fake/endpoint', {
  name: 'John'
}).then(res => {
  // do stuff with parsed JSON response
});

FormData

// Alternatively import from 'sk-fetch-wrapper/lib/form-data'
import { postForm } from 'sk-fetch-wrapper';

const formData = new FormData(myForm);

postForm('/fake/endpoint', formData).then(res => {
  // do stuff with parsed JSON response
});

GraphQL

// Alternatively import from 'sk-fetch-wrapper/lib/graphQL'
import { postGraphQL } from 'sk-fetch-wrapper';

const graphQLQuery = `
  query HeroNameAndFriends($episode: Episode) {
    hero(episode: $episode) {
      name,
      friends {
        name
      }
    }
  }`;

const graphQLVariables = `
  {
    "episode": "JEDI"
  }`;

postGraphQL('/fake/graphql-endpoint', graphQLQuery, graphQLVariables)
  .then(res => {
    // do stuff with successful graphQL query parsed JSON response
  })
  .catch(err => {
    // If your graphQL query returns with errors, these will be caught in `err`

    console.log(err.message);
    // GraphQL responded with error(s)

    console.log(err.graphQL);
    // [
    //   {
    //     "message": "Some graphQL error message",
    //     "locations": [
    //       {
    //         "line": 2,
    //         "column": 3
    //       }
    //     ]
    //   }
    // ]
  })