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

rapid-rpc

v0.0.1-alpha.0

Published

lightweight, typesafe, and scalable remote procedure calls

Downloads

2

Readme

rapid-rpc

A lightweight, typesafe, and scalable way of writing APIs that works with Next.js. Build to work with the App Router and server and client components.

This is an experimental version not meant for production use

Create your API

We recommend creating your API safely using the server-only package, to make sure you never expose server code to the client.

// filename: rpc/server.ts
import "server-only";
import { create } from "rapid-rpc";

export const [serverApi, connector] = create({
  queries: {
    getRecentTodos: async (max: number) => {
      const todos: Todo[] = await db.readTodos(max);
      return todos;
    },
  },
  mutations: {
    addTodo: async (text: string, completed: boolean) => {
      const newTodo: Todo = await db.createTodo(text, completed);
      return newTodo;
    },
  },
});

export type API = typeof serverApi;

Create your API client:

// filename: rpc/client.ts
"use client";

import { createClient } from "rapid-rpc/client";
import { API } from "./server";

export const api = createClient<API>("http://localhost:3000/api");

Connect your route:

// filename: app/api/[method]/route.ts
import { connector } from "@/rpc/server";

export const { GET, POST } = connector;

Use your API

Use the API in server components:

import { serverApi } from "@/rpc/server";

export default async function Page() {
  const todos = await serverApi.getRecentTodos(5);

  return <Home todos={todos} />;
}

Use the API in client components:

"use client";

import { api } from "@/rpc/client";

export default function MyClientComponent() {
  const { data, isLoading, error, mutate } = api.getRecentTodos.useQuery(10);
  const { mutate: addTodo } = api.addTodo.useMutation({
    onSuccess: () => mutate(),
  });

  // You can call addTodo with two arguments anytime like so: addTodo("learn typescript", false)

  ...
}

The hooks useQuery and useMutation are thin wrappers around SWRs useSWR and useSWRMutation hooks.

There is also the useQueryOptions hook which gives you access to the options you have with the useSWR hook:

"use client";

import { api } from "@/rpc/client";

export default function MyClientComponent() {
  const { data, isLoading, error } = api.getRecentTodos.useQueryOptions({ refreshInterval: 5000 }, 10);

  ...
}

Create a protected API

import "server-only";
import { createProtected, MiddlewareOptions } from "rapid-rpc";
import { NextResponse } from "next/server";
import { cookies } from "next/headers";

export const [serverApi, connector] = createProtected({
  // The returned context will be fed into every query and mutation call
  getContext: async (): Promise<Token | null> => {
    const sessionCookie = cookies().get("session");
    const token: Token | null = auth.getToken(sessionCookie);
    return token;
  },
  middleware: (options: MiddlewareOptions<Token | null>, next: () => any) => {
    // options.ctx will contain the return value of getContext
    if (!options.ctx) {
      return NextResponse.json({ message: "Not logged in!" }, { status: 403 });
    }
    return next();
  },
  queries: {
    getTodosByUser: async (ctx: Token | null, max: number) => {
      const { userId } = ctx!;
      const todos: Todo[] = await db.readTodosByUser(userId, max);
      return todos;
    },
  },
  mutations: {
    addTodo: async (ctx: Token | null, text: string, completed: boolean) => {
      const { userId } = ctx!;
      const newTodo: Todo = await db.createTodo(userId, text, completed);
      return newTodo;
    },
  },
});

export type API = typeof serverApi;

Combine APIs

import "server-only";
import { create, createProtected, combine } from "rapid-rpc";

const publicApi = create({
  ...
});

const protectedApi = createProtected({
  ...
});

export const [serverApi, connector] = combine(publicApi, protectedApi);

export type API = typeof serverApi;