0.1.1 • Published 2 years ago

hobby-rpc.server v0.1.1

Weekly downloads
-
License
0BSD
Repository
github
Last release
2 years ago

Introduction

It is to create Hobby-RPC servers with Node.js. To install: npm i hobby-rpc.server.

Usage

Either require or import:

{ Server } = require 'hobby-rpc.server'
import { Server } from 'hobby-rpc.server'

Server is a function which returns an http.Server. It takes an object which must have the functions property.

Here is a simple server providing SomeNullaryFunction and SomeUnaryFunction:

server = Server
  functions:
    SomeNullaryFunction: ->
      'A string returned from SomeNullaryFunction.'
    SomeUnaryFunction: (input) ->
      "A string returned from SomeUnaryFunction with #{input}."

To start a server, you can use server.listen():

server.listen 8080

Functions

functions can return any objects serializable with JSON.stringify. If a function returns a rejected Promise or throws an error, the server responds with 400 Bad Request.

CORS headers

By default, it will return permissive CORS headers(Access-Control-Allow-Origin: *) for requests from any origin. For private APIs, you might want to restrict that:

server = Server
  CORS:
    Origins: ['https://some.domain', 'https://another.domain']
  functions:
    SomeNullaryFunction: ->
      'A string returned from SomeNullaryFunction.'
    SomeUnaryFunction: (input) ->
      "A string returned from SomeUnaryFunction with #{input}."

You can also override the default values as follows:

server = Server
  CORS:
    Methods: 'POST, OPTIONS'
    Headers: 'Authorization, Content-Type'
    MaxAge: '86400'
  functions:
    SomeNullaryFunction: ->
      'A string returned from SomeNullaryFunction.'
    SomeUnaryFunction: (input) ->
      "A string returned from SomeUnaryFunction with #{input}."

Authorization

By default, any client is allowed to call the functions. For public APIs, you will probably want to restrict that.

To do so, pass FindUser as follows:

server = Server
  FindUser: (token) ->
    if token is 'TheOnlyValidToken'
      name: 'A'
  functions:
    SomeNullaryFunction: ->
      "Hello, #{@user.name}."

FindUser should be a function that takes one argument, a String token. token is what clients are supposed to pass in the Authorization header.

If FindUser returns one of these:

  • a falsy value;
  • a rejected Promise;
  • a Promise resolved to a falsy value;

or throws an error, the server responds with 403 Forbidden.

If FindUser returns something else, the server will assume it is something that represents the current user. If it is a Promise, the value resolved from this Promise will be available inside of the functions as @user. If it is not a Promise, it will be available as @user.

0.1.1

2 years ago

0.1.0

2 years ago

0.0.1

2 years ago

0.0.0

2 years ago