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

@bufferapp/buffer-rpc

v1.3.0

Published

Buffer RPC request handler

Downloads

81

Readme

deprecated

As of the 23rd of September 2024, buffer-rpc will be unmaintained and deprecated.

buffer-rpc

Build Status

Buffer RPC request handler

Quickstart

Create a RPC method to add 2 numbers:

// index.js
const express = require('express')
const { rpc, method } = require('@bufferapp/buffer-rpc')
const app = express()
app.use(bodyParser.json()) // this is required
app.post('/rpc/:method?', rpc(method('add', (a, b) => a + b)))
const port = 3000
app.listen(port, () => console.log(`App Is Listening On Port ${port}`))

Start the server

node index.js

Or you can use curl to call the add method:

curl -H "Content-Type: application/json" -X POST -d '{"args": "[2, 3]"}' localhost:3000/add | python -m json.tool

# {
#    "result": 5
# }

Note: it is recommended that you use the RPC client:

https://github.com/bufferapp/micro-rpc-client

To see a list of all available methods use the methods call:

curl -H "Content-Type: application/json" -X POST -d '{"name": "methods"}' localhost:3000 | python -m json.tool

# {
#   result: [
#     {
#       "docs": "add two numbers"
#       "name": "add"
#     },
#     {
#       "docs": "list all available methods",
#       "name": "methods"
#     }
#   ]
# }

Usage

Here's a few examples of how to hook up the handler methods:

const express = require('express')
const { rpc, method } = require('@bufferapp/buffer-rpc')
const app = express()
app.use(bodyParser.json()) // this is required

app.post(
  '/rpc/:method?',
  rpc(
    method('add', (a, b) => a + b),
    method(
      'addAsync',
      (a, b) =>
        new Promise(resolve => {
          resolve(a + b)
        }),
    ),
    method('addItems', ({ a, b }) => a + b),
    method(
      'addItemsAsync',
      ({ a, b }) =>
        new Promise(resolve => {
          resolve(a + b)
        }),
    ),
    method('throwError', () => {
      throw createError({ message: "I'm sorry I can't do that" })
    }),

    method(
      'throwErrorAsync',
      () =>
        new Promise((resolve, reject) => {
          reject(
            createError({
              message: 'Something is broke internally',
              statusCode: 500,
            }),
          )
        }),
    ),
    method(
      'documentation',
      `
  # documentation

  Document what a method does.
  `,
      () => 'documentation',
    ),
  ),
)

const port = 3000
app.listen(port, () => console.log(`App Is Listening On Port ${port}`))

Dependency Injection

To simplify the code in your RPC methods, you may want to pass some common utilities down via simple dependancy injection. To do this, you call the rpc() method with slightly different syntax.

Instead of this (seen in the other README examples):

rpc(methodOne, methodTwo, methodThree, ...);

Pass the methods as an Array and pass utils as a second parameter:

rpc([methodOne, methodTwo, methodThree], utils);

Where utils is an Object that will be exposed to your RPC methods as the last parameter. For example, you might use it like this (example is simplified):

// rpcHandler.js
const { rpc } = require('@bufferapp/buffer-rpc');

const PublishAPI = require('./publishAPI');
const myMethod = require('./myMethod');

module.exports = rpc([myMethod], { PublishAPI });

// myMethod.js
const { method } = require('@bufferapp/buffer-rpc');

module.exports = method(
  'myMethod',
  'myMethodDocs',
  (args, req, res, { PublishAPI }) => PublishAPI.fetch('/1/user.json')
);

Error Handling

Handled Flag

To help understand what the handled flag is for lets talk about a simplified distributed system.

client -> server

The server is the RPC endpoints and the client is the source of the request, perhaps a browser or another service.. When handled = true this means there is nothing more for the client to do, when handled = false this means there might be more work to resolve an issue. So handled = false is a maybe. An example of a definite handled = true is when you make a request to an RPC endpoint that does not exist. There's no partial state to resolve. An example of handled = false would be when you have to make multiple writes to a database, the first one passes and the second one fails. You've got a partially handled failure case. The client would be notified with a handled = false and then resolve the issue by either deleting the first record or writing the second -- depends on what the application does!

While this doesn't happen very often, it is more likely when we choose to use a NoSQL database since we don't have joins. That being said most of the time, you'll return an error with handled = true... especially if you're keeping RPC endpoints simple. Avoid distributed systems problems when you can!

createError handled = true (customizable)

errorMiddleware handled = false

method not found handled = true

Error Codes

These are the default error codes for error type responses

1000 - createError default (customizable)
4040 - method not found (404)
5000 - unhandled exception (500)

API

rpc

Takes a bunch of methods as arguments. Passes requests to right RPC endpoint

rpc(...methods)

...methods - method - rpc method (see below)

method

add a remote method

method(name, [docs], fn)

name - string - the name of the method
docs - string - documentation about a method
fn - function - the function to call and apply parameters the method is requested

createError

create an error to be thrown, optionally set the status code

createError({
  message,
  code = 1000,
  statusCode = 400,
  handled = true,
})

message - string - error message to return
code - integer - custom error code to add to response body HTTP status code (default to 1000)
statusCode - integer - HTTP status code (default to 400) handled - boolean - add if error was handled on backend to the response body (default to true)

errorMiddleware

express/connect error handling middleware that receives and unhandled error and returns a JSON response

app.post('/rpc', rpc(method('awake', () => 'OK')), errorHandler)

/*
statusCode = 500
body = {
  handled: false,
  code: 5000,
  error: 'some error message' // set from error.message
}
*/

Request and Response Objects

Request and response objects are always passed along as the last two arguments in case they're needed.

method('addWithSession', (a, b, req, res) => {
  if (!req.session) {
    throw createError({ message: 'a session is needed to add numbers', statusCode: 401})
  }
  return a + b
}