0.8.0 • Published 7 years ago

piggyback v0.8.0

Weekly downloads
66
License
MIT
Repository
github
Last release
7 years ago

Piggyback

Build Status

A resource-oriented wrapper over the window.fetch API. Defaults to the JSON content type.

Install

npm install --save piggyback

Usage

Resource Builder

The resource function constructs a complete set of CRUD methods to interact with a conventional HTTP API.

All methods return a promise that resolves the JSON body of the response.

import { resource } from 'piggyback';

const { getTasks, getTaskById, createTask, updateTask, deleteTask } = resource('tasks');

// GET /tasks
getTasks().then((json) => console.log(json));

// GET /tasks/{id}
getTaskById(id).then((json) => console.log(json));

// POST /tasks
createTask(task).then((json) => console.log(json));

// PUT /tasks/{id}
createTask(id, task).then((json) => console.log(json));

// DELETE /tasks/{id}
deleteTask(id);

Sending HTTP Requests

The following methods are provided to interact directly with JSON web APIs:

  • sendGet
  • sendPost
  • sendPut
  • sendPatch
  • sendDelete

All methods return a promise that resolves to a Response, including the Body mixin of the Fetch API.

import { sendGet, sendPost, sendPut, sendPatch, sendDelete } from 'piggyback';

export default function getTasks() {
  return sendGet('/tasks').then(function(response) {
    return response.json();
  });
}

export default function createTask(task) {
  return sendPost('/tasks', task).then(function(response) {
    return response.json();
  });
}

export default function replaceTask(id, task) {
  return sendPut('/tasks/' + id.toString(), task).then(function(response) {
    return response.json();
  });
}

export default function updateTask(id, task) {
  return sendPatch('/tasks/' + id.toString(), task).then(function(response) {
    return response.json();
  });
}

export default function deleteTask(id) {
  return sendDelete('/tasks/' + id.toString());
}

Notes

  • Depends on es6-promise and isomorphic-fetch polyfills (this is handled automatically).
  • Browser auth credentials are always sent with the request.
  • HTTP error codes result in a JavaScript Error being thrown by default.
  • How you handle resolving and rejecting is up to you.

If these defaults aren’t suitable for your use-case, consider using the isomorphic-fetch library directly.

0.8.0

7 years ago

0.7.0

7 years ago

0.6.0

9 years ago

0.5.0

10 years ago

0.4.1

10 years ago

0.4.0

10 years ago

0.3.1

10 years ago

0.3.0

10 years ago

0.2.1

10 years ago

0.2.0

10 years ago

0.1.0

10 years ago