0.10.0 • Published 2 years ago

restiful v0.10.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

restiful

Beautifully RESTful.

Installation

npm install restiful --save

Simplified fetch

Cumbersome fetch:

// POST /users
fetch('/users', {
    method: 'post',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        name: 'admin',
        login: 'password',
    }),
}).then(function(response) {
    if (response.status >= 200 && response.status < 300) {
        return response.json();
    }
    throw new Error(response.statusText);
}).then(function(json) {
    // ...
});

restiful equivalent:

// POST /users
restiful('/users').post({
    name: 'admin',
    login: 'password'
}).then(function(json) {
    // ...
});

.get(), .put(), .patch() and .delete() methods are also available.

Environments

Supports both Node and browser environments. Makes use of node-fetch v2 for Node environments.

For the sake of real estate, node-fetch is externalized; therefore, must be installed separately.

Usage examples

import restiful from 'restiful';

var blog = restiful('/blog');

/* /blog/posts */
var posts = blog('posts');
posts.get();
posts.post({
    title: 'restiful',
});

/* /blog/posts?category=javascript */
posts.get({
    category: 'javascript',
});

/* /blog/posts/1 */
var firstPost = posts(1);
firstPost.get();
firstPost.put({ title: 'restiful is simple' });
firstPost.patch({ title: 'restiful is simple' });
firstPost.delete();

var firstPostComments = firstPost('1/comments');

/* /blog/posts/1/comments */
firstPostComments.get();

/* /blog/posts/1/comments/1 */
firstPostComments(1).get();

Easily converts to string:

String(restiful('/blog/posts')) // "/blog/posts"

To catch errors:

restiful('/posts')
  .get()
  .catch(function(err) {
    console.log(err);
});

You can also pass fetch options to restiful:

var posts = restiful('/blog/posts', fetchOptions);
var comments = posts('1/comments'); // Will inherit fetchOptions

Standard fetch options (e.g. enabling CORS):

var request = restiful('/', { mode: 'cors' });
var posts = request('posts');

Non-standard fetch options (e.g. changing response type):

var request = restiful('/', { responseAs: 'text' });
var posts = request('posts');

responseAs can be response (for full response), blob, text or json (default).

0.10.0

2 years ago

0.9.2

2 years ago

0.9.1

2 years ago

0.9.0

2 years ago