micro-problems

1.1.2 • Public • Published

micro-problems

NPM Travis Codecov Greenkeeper badge David David Dev

A companion library to micro which helps in responding to requests with application/json+problem

Installing

# npm
npm install -s micro-problems

# yarn
yarn add micro-problems

Usage

// out-of-credit.js
import declareProblem from "micro-problems";

// First off, you want to declare the type of problem your application could encounter.
const { handler, Problem, decorator } = declareProblem({
  type: "https://example.com/api/probs/out-of-credit",
  status: 403,
  title: "You do not have enough credit.",
  detail:
    "Your current balance is lower than the cost of what you are trying to purchase."
});

export { handler, Problem, decorator };

In the rest of this example, I leave it up to the reader to pick their preferred method of routing requests. Assume in this example that any file in the api folder would be routed as the corresponding route (minus the file extension).

// api/probs/out-of-credit.js

import { handler } from "../../out-of-credit";

// If you are the one serving the URI connected to the problem, you can use `handler` to respond to it.
export default handler;
// api/purchases.js

import {
  Problem as OutOfCreditProblem,
  decorator as withOutOfCreditProblem
} from "../out-of-credit";

// A handler which could encounter the problem, should use a combination of the Problem and decorator
export default withOutOfCreditProblem(async (req, res) => {
  const purchase = await json(req);
  const account = await determineAccount(req);
  if (account.credit < purchase.cost) {
    const notification = await account.addFailedPurchaseNotification(purchase)
    throw new OutOfCreditProblem(
      `Your current balance is ${account.credit}, but that costs ${purchase.cose}.`,
      {
        balance: account.credit,
        accounts: [account.uri, purchase.seller.uri]
      },
      notification.uri
    );
  }
});

Readme

Keywords

Package Sidebar

Install

npm i micro-problems

Weekly Downloads

0

Version

1.1.2

License

MIT

Unpacked Size

12.8 kB

Total Files

12

Last publish

Collaborators

  • call-a3