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

beautapi.js

v1.0.1

Published

Beautapi

Downloads

4

Readme

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

| Name | Type | Description | Default | | -------------- | --------------- | ---------------------------------------- | ---------------------------------------- | | endpointRegex | regex | Regex used to parsing endpoint parameters. | /(?:\:)([a-zA-Z]([a-zA-Z0-9]\|-\|_)*)/g | | endpointPrefix | string | String that will be added to every endpoint at the beginning. | "" | | fetchReference | function | Reference to the fetch function. If defined it will be used instead of default fetch function. | undefined | | fetchConfig | object | Config passed to fetch function. | {} | | thenChain | array[function] | Array 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))