magic-rpc
    TypeScript icon, indicating that this package has built-in type declarations

    0.0.18 • Public • Published

    magic-rpc GitHub license npm version

    A typesafe RPC framework with compile-time error checking.

    Magic RPC intellisense demo

    🤔 Why is this useful?

    You can think of magic-rpc as a way to write APIs quickly and [typed] safely. It avoids the clunkiness of REST and the boilerplate/complexity of GraphQL.

    👩🏼‍🏫 I want more boring details!

    Motivation:

    It helps to have correctness guarantees from your compiler when writing your programs. This is applicable when writing client-server applications, but requires some tooling to achieve.

    To this end, we can use an RPC client that is aware of the return type of the server response. We will encode the data type and error type into the return type of an RPC method. The client will infer the type of the RPC method enabling the compiler to know about data and error types. The compiler will enforce appropriate error handling on the client: providing us strongly-typed client-server code.

    Inspiration:

    This project is loosely based on JSON RPC.

    Our error propagation is inspired by Rust's Result type, which returns a tuple of Result<T, E> from a function. Here T is your data type and E is your error type.

    Install

    npm i magic-rpc
    ⚠️ IMPORTANT: You must enable `strictNullChecks` in your `tsconfig.json`.

    Typescript currently has a bug, making type narrowing only work when strictNullChecks is turned on.

    // tsconfig.json
    {
      // ...
      "compilerOptions": {
        // ...
        "strictNullChecks": true
      }
    }

    Features

    🪄 Magical type inference

    Invoke methods in your client code with type guarantees but without strange import paths.

    ⚡️ Fast Developer Experience

    No code generation is required, speeding up your iteration! Minimal boilerplate and intuitive syntax. Looks just like method invocations. Tiny library footprint.

    🔍 Observability

    See stack traces from server code in development

    🚧 Easy to try in an existing project

    Can be gradually deployed into your project. Designed to be agnostic to front-end framework choice.

    Usage

    Simple Example

    Invoking an RPC method from your client looks like calling a function defined on your server.

    const quotient = await math.divide(10, 2);

    Create a client that is aware of the return types of your methods.

    // client.ts
    import { createClient } from 'magic-rpc';
    import fetch from 'cross-fetch';
    import type { Services } from './server';
    
    export async function main() {
      // Create an RPC Client
      const { math } = createClient<Services>(`http://localhost:8080/rpc`, fetch);
    
      // Invoke method on RPC client (crosses network boundary)
      const response = await math.divide(10, 2); // TS is aware of types
    
      console.log(response);
    }

    Finally, this is what configuring your server looks like.

    // server.ts
    import { createRpcHandler, Request } from 'magic-rpc';
    import express from 'express';
    
    // Define some services
    const services = {
      math: {
        divide(_: Request, x: number, y: number) {
          return x / y;
        },
      },
    };
    
    // Client will import these for the RpcClient
    export type Services = typeof services;
    
    // Configure server
    export const app = express();
    app.use(express.json());
    app.post('/rpc', createRpcHandler(services));
    What does a `curl` command look like?
    $ curl localhost:8080/rpc \
      --header "Content-Type: application/json" \
      --request POST \
      --data '{
        "service": "math",
        "method": "divide",
        "params": [99, 3]
      }'
    {"result":{"ok":true,"err":false,"val":33}}

    Alternatives

    Install

    npm i magic-rpc

    DownloadsWeekly Downloads

    1

    Version

    0.0.18

    License

    MIT

    Unpacked Size

    93.8 kB

    Total Files

    54

    Last publish

    Collaborators

    • abhayvatsa