1.0.1 • Published 8 years ago

beautapi.js v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
8 years ago

Beautapi-js

Manage your endpoints in elegant way. Built on top of fetch.

Installation

NPM

npm install beautapi-js

Bower

bower install beautapi-js

Getting started

import Beautapi from "beautapi-js";

Documentation

Beautapi.parse(model, config) : Api

model (Object)

Required

Model describes how api should look like. Beautapi will create endpoints based on model. It can be flat or multi-level object.

const Api = Beautapi.parse({
  "Posts": {
    "get":          "/posts/:id",
    "post":         "/posts",
    "put":          "/posts/:id",
    "patch":        "/posts/:id",
    "delete":       "/posts/:id",
    "getByUserId": ["/posts?userId=:userId", {"method": "GET"}],
    "Comments": {
      "get":  "/posts/:id/comments"
    }
  }
})

// Api.Posts.get({id: 10}).then((response) => { ... })
// Api.Posts.getByUserId({id: 99}).then((response) => { ... })
// Api.Posts.Comments.get({id: 53}).then((response) => { ... })

If leaf is a string beautapi will create reuqest method using value as path and key as a method (case innsensitive) and name. It will match methods like "DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH. Otherwise "GET" will be used.

If leaf is an array beautapi will create request method using first value as path, second value as fetch config and key as a name.

Path can take parameters preceded by a colon.

config (Object)

Optional

NameTypeDescriptionDefault
endpointRegexregexRegex used to parsing endpoint parameters./(?:\:)([a-zA-Z]([a-zA-Z0-9]\|-\|_)*)/g
endpointPrefixstringString that will be added to every endpoint at the beginning.""
fetchReferencefunctionReference to the fetch function. If defined it will be used instead of default fetch function.undefined
fetchConfigobjectConfig passed to fetch function.{}
thenChainarrayfunctionArray of functions that will be passed as callback of Promise.then method. So you don't have to call them manually every time.[]
import fetch from "fetch";

const model = {
  Users: {
    search: ["/users/{keyword}", {method: "GET"}] 
  }
}

const parseJSON = function(response) {
  return response.json()
}

const Api = Beautapi.parse(model, {
  endpointRegex:  /(?:\{)([a-zA-Z]([a-zA-Z0-9]|-|_)*)(?:\})/g
  endpointPrefix: "http://localhost:3000",
  fetchReference: fetch,
  fetchConfig: {
    headers: {
   		'Accept': 'application/json',
    	'Content-Type': 'application/json'
    }
  },
  thenChain: [parseJSON]
})

//Usage
Api.Users.search({keyword: "admin123"}) // GET http://localhost:3000/users/admin123
	// .then(parseJSON) will be called here because it has been added to thenChain array
	.then((response) => {
  		console.log(response);
	})

Return (Object)

Returned object has the same structure as model, but instead of strings and arrays at leaf positions it has functions.

const Api = Beautapi.parse({
  "Posts": {
    "get":          "/posts/:id",
    "post":         "/posts",
    "getByUserId": ["/posts?userId=:userId", {"method": "GET"}],
    "Comments": {
      "get":  "/posts/:id/comments"
    }
  }
})

// Api == {
//   Posts: {
//     get:         function([params, fetchConfig]),
//     post:        function([params, fetchConfig]),
//     getByUserId: function([params, fetchConfig]),
//     Comments: {
//       get: function([params, fetchConfig])
//     }
//   }
// }

Each function can take two parameters:

params (Object)

It allows you to pass values to the endpoint

const Api = Beautapi.parse({
  "Posts": {
    "get":          "/posts/:id",
  }
})

Api.Posts.get({id: 10})
fetchConfig (Object)

It allows you to assign something (or override) to the fetch configuration for this single invocation.

const Api = Beautapi.parse(...);

const data = {
  title: "Lorem ipsum",
  text: "abc"
};

Api.Posts.post({}, {
  body: data
});

Note that you don't have to stringify data object. Beautapi will convert it and it'll add Content-Type header.

Return (Promise)

Fetch function return is returned (Promise).

Helpers

Helpers are little functions that you would probably use as Promise.then callbacks.

parseJSON

Parse response to JSON

Api.Post.get({id: 1}).then(Beautapi.helpers.parseJSON)

throwErrors

Throw error when response status is not 2xx

Api.Post.get({id: 1}).then(Beautapi.helpers.throwErrors)

mapTo

It maps response array to class instances.

class Post {
  constructor({id, userId, title, body}) {
    this.id     = id;
    this.userId = userId;
    this.title  = title;
    this.body   = body;
    this.length = title.length + body.length;
  }
}

API.Posts.getAll().then(Beautapi.helpers.mapTo(Post))

decorateTo

Same as mapTo, but for single object (not array).

class Post {
  constructor({id, userId, title, body}) {
    this.id     = id;
    this.userId = userId;
    this.title  = title;
    this.body   = body;
    this.length = title.length + body.length;
  }
}

API.Posts.get({id: 1}).then(Beautapi.helpers.decorateTo(Post))
1.0.1

8 years ago

1.0.0

8 years ago