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

rpc-reflector

v1.3.11

Published

Call methods on an object over RPC

Downloads

701

Readme

rpc-reflector

Node.js CI Coverage Status standard-readme compliant

Call methods on any object over RPC with minimal fuss.

Create a "mirror" of an object on the server in the client. You can call any methods on the server object by calling the same method name on the client object. You can also subscribe to events on the client as if you were subscribing to events on the original API. Synchronous methods on the server object become asynchronous methods on the client-side. Properties on the server object become asynchronous getter methods on the client, e.g. for a server object { foo: 'bar' } the property foo can be read on the client via await clientApi.foo().

Unlike other RPC libraries, this does not require any boilerplate to define methods that are available over RPC. All methods and properties on the server object are "reflected" in client API automatically. Any method called on the client object will return a Promise, but methods that are not defined on the server will throw with a ReferenceError.

Table of Contents

Background

Most RPC libraries I could find require a lot of boilerplate to define the methods that are available over RPC. I wanted an easy way for an API on the server to be used from a client in exactly the same way as it is on the server, without needing to setup any RPC methods. Under-the-hood this uses a Proxy object.

Install

npm install rpc-reflector

Usage

import { createClient, createServer } from 'rpc-reflector'
import DuplexPair from 'native-duplexpair'

const myApi = {
  syncMethod: () => 'result1',
  asyncMethod: () =>
    new Promise((resolve, reject) => {
      setTimeout(() => resolve('result2'), 200)
    }),
}

// Create two duplex sockets linked together
const { socket1, socket2 } = new DuplexPair({ objectMode: true })

const serverStream = socket1
const clientStream = socket2

const { close } = createServer(myApi, serverStream)
const myApiOnClient = createClient<typeof myApi>(clientStream)

;(async () => {
  const result1 = await myApiOnClient.syncMethod()
  const result2 = await myApiOnClient.asyncMethod()
  console.log(result1) // 'result1'
  console.log(result2) // 'result2'
})()

API

const { close } = createServer(api, channel)

api can be any object with any properties, methods and events that you want reflected in the client API.

channel can be a Duplex Stream, a browser MessagePort, a Node Worker MessagePort or a MessagePort-like object that defines a postMessage() method and implements an EventEmitter that emits an event named 'message'.

If channel is a MessagePort you will need to manually call port.start() to start sending messages queued in the port.

close() is used to remove event listeners from the channel. It will not close or destroy the MessagePort or Stream used as the channel.

const clientApi = createClient(channel)

channel: see above for createServer()

Returns clientApi which can be called with any method on the api passed to createServer(). Events on api can be subscribed to via clientApi.on(eventName, handler) on the client. Properties/fields on the server api can be access by calling a method with the same name on the client API, e.g. to access the property api.myProp, on the client call await clientApi.myProp().

When using Typescript, you can pass the type of the server API as a generic e.g.

const clientApi = createClient<ServerApi>(channel)

The returned clientApi will be correctly typed, with synchronous functions converted to synchronous.

createClient.close(clientApi)

The static method close() will remove all event listeners from the channel used to create the client. It will not close or destroy the MessagePort or Stream used as the channel.

const unencodedDuplex = createEncodeDecodeStream(duplex, opts)

createServer() and createClient() write messages to the Stream or MessagePort as objects, and they expect the messages read from the Stream or MessagePort to be objects. If you are using a socket or TCP stream as a transport for RPC messages, you will need to encode the objects as buffers. The createEncodeDecodeStream() helper will encode and decode messages over the duplex stream using MessagePack.

opts.encoding An encoding object that contains encode(value) and decode(buffer) functions for encoding values to and from buffers. Defaults to MessagePack encoding with support for encoding/decoding Buffers. See the default implementation

Maintainers

@gmaclennan

Contributing

PRs accepted.

Small note: If editing the README, please conform to the standard-readme specification.

License

MIT © 2020 Gregor MacLennan