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

json-rpc-wrapper

v1.0.1

Published

A simple json rpc 2.0 wrapper for any object

Downloads

9

Readme

JSON-RPC Wrapper

Build Status npm Total alerts Language grade: JavaScript

This library provides a basic json rpc wrapper for any object class that needs to be exposed to the network. It builds a proxy with method validations and argument processing arround any variable that has methods. The provided library is infrastructure agnostic so it can be used on any possible transport layer.

Installing

npm install --save json-rpc-wrapper

Testing

npm run test

Usage

Wrapping a simple object through json rpc protocol would be similar to this:

const { RpcWrapper } = require('json-rpc-wrapper')
const myService = {
  add: (...params) => params.reduce((acc, curr) => acc + curr, 0),
  subtract: (a, b) =>  a - b,
  div: ({a, b}) => a / b
}

const rpcProxy = new RpcWrapper(myService)

const req = '{"jsonrpc":"2.0","method":"add","params":[1,2,3],"id":"1"}' // data received through some protocol
const res = await rpcProxy.callReq(req) // {jsonrpc:'2.0',id:'1',result:6}
const json = JSON.stringify(res) // or res.toString() -> '{"jsonrpc":"2.0","id":"1","result":6}'

The wrapper also supports functions with callbacks, we just have to specify which methods expect callback functions:

const service = {
  storeContent: (content, cb) => {
    fs.writeFile('test.log', content + '\n', { flag: 'a' }, (err, res) => {
      if (err) return cb(err)
      return cb(null, true)
    })
  }
}
const rpcProxy = new RpcWrapper(service)

const req = '{"jsonrpc":"2.0","method":"storeContent","params":["some content"],"id":56}'
const res = await rpcProxy.callReq(req) // {jsonrpc:'2.0',id:56,result:true}

In additional wrapper also works with promises and async/await functions without an issue:

const service = {
  store: async (order) => {
    await storeOrder(order)
    await updateStocks(order.products)
    return true
  }
}
const rpcProxy = new RpcWrapper(service)

const req = '{"jsonrpc":"2.0","method":"storeContent","params":{"user":1,"products":[{"id":1,"name":"p1"},{"id":2,"name":"p2"}]},"id":"xgsdoigh-dsgh-sdgjlsgj"}'
const res = await rpcProxy.callReq(req) // {jsonrpc:'2.0',id:'xgsdoigh-dsgh-sdgjlsgj',result:true}

Wrapper works also with any type of class instance without a problem. A special type of class that can be used is RpcServiceBase abstract class that provides also method parameter validation during method invocation. Here's a quick example of usage of this class:

class ProductService extends RpcServiceBase {
  constructor (products = []) {
    super()

    this.methods.push('create', 'find')
    this.products = products
  }

  create (item) { return this.products.push(item) }
  find (id) { return this.products.find(p => p.id === id) }
  remove (id) { this.products = this.products.filter(p => p.id !== id) }

  async areParamsValid (method, params) {
    switch (method) {
      case 'create':
        if (!params.id || typeof params.id !== 'number') return false
        if (!params.name || typeof params.name !== 'string') return false
        return true
      case 'find':
        return params[0] && typeof params[0] === 'number'
      default: return false
    }
  }
}

const myService = new ProductService([ { id: 1, name: 'Product 1' }, { id: 2, name: 'Product 2' } ])
const rpcProxy = new RpcWrapper(myService)

const req = JSON.stringify([
  { "jsonrpc": "2.0", "method": "create", "params": { "id": 4, "name": "Product 4" }, "id": "1" },
  { "jsonrpc": "2.0", "method": "remove", "params": [ 2 ], "id": "2" },
  { "jsonrpc": "2.0", "method": "find", "params": [ 1 ], "id": "3" },
  { "jsonrpc": "2.0", "method": "create", "params": { "id": 5, "name": "Product 4" } },
  { "jsonrpc": "2.0", "method": "find", "params": [ "abc" ], "id": 4 }
])

const rpcRes = await rpcProxy.callReq(req)
// [
//   { "jsonrpc": "2.0", "id": "1", "result": null },
//   { "jsonrpc": "2.0", "id": "2", "result": null },
//   { "jsonrpc": "2.0", "id": "3", "result": { "id": 1, "name": "Product 1" } },
//   { "jsonrpc": "2.0", "id": 4, "error": { "code": -32602, "message": "Invalid params" } }
// ]

Simple TCP JSONRPC 2.0 instance

const net = require('net')
const { RpcWrapper } = require('json-rpc-wrapper')

const service = {
  ping: () => Date.now(),
  echo: (params) => params
}
const rpcProxy = new RpcWrapper(service)

const server = net.createServer({ allowHalfOpen: true})

server.on('connection', async (socket) => {
  socket.on('data', (data) => {
    const raw = data.toString('utf-8')
    const res = await rpcProxy.callReq(raw)
    socket.write(JSON.stringify(res), () => socket.end())
  })
})

server.listen(7070, () => {
  console.log(`TCP server is listening on ::7070`)
})

Simple HTTP JSONRPC 2.0 instance

const http = require('http')
const { RpcWrapper } = require('json-rpc-wrapper')

const service = {
  ping: () => Date.now(),
  echo: (params) => params
}
const rpcProxy = new RpcWrapper(service)

const server = http.createServer((req, res) => {
  const chunks = []
  req.on('data', (data) => {
    chunks.push(data.toString('utf-8'))
  })

  req.on('end', async () => {
    const payload = chunks.join('')
    const rpcRes = await rpcProxy.callReq(payload)
    res.setHeader('Content-Type', 'application/json')
    res.write(JSON.stringify(rpcRes))
    res.end()
  })
})

server.listen(8080, () => {
  console.log(`HTTP server is listening on 8080`)
})

Typescript usage

The library can also be used directly into typescript without needing to install types package separately, all declaration files can be found in @types folder. Usage example:

import http = require('http')
import { RpcWrapper, RpcServiceBase } from 'json-rpc-wrapper';

interface Product { id: number; name: string; }

class ProductService extends RpcServiceBase {
  protected products: Array<Product>
  constructor(products: Array<Product> = []) {
    super()

    this.methods.push('create')
    this.products = products
  }

  create(item: Product) { this.products.push(item) }
  areParamsValid(method: string, params: any) {
    switch (method) {
      case 'create':
        if (!params.id || typeof params.id !== 'number') return false
        if (!params.name || typeof params.name !== 'string') return false
        return true
      default: return false
    }
  }
}

const myService = new ProductService([{ id: 1, name: 'Product 1' }])
const rpcProxy = new RpcWrapper(myService)

const server = http.createServer((req, res) => {
  const chunks: Array<string> = []
  req.on('data', (data) => {
    chunks.push(data.toString('utf-8'))
  })

  req.on('end', async () => {
    const payload = chunks.join('')
    const rpcRes = await rpcProxy.callReq(payload)
    res.write(JSON.stringify(rpcRes))
    res.end()
  })
})

server.listen(8080, () => {
  console.log(`HTTP server is listening on ::8080`)
})

Additional detailed examples can be found in examples folder.

Also full documentation related classes can be found in docs/DEFINITIONS.md

Authors