0.1.4 • Published 2 years ago

@nitestack/tnrpc v0.1.4

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

tNRPC - Typescript Next.js 13 Remote Procedure Call

Writing type-safe route handlers, server actions and fetching type-safe data

npm install @nitestack/tnrpc

Validators

Zod

  • npm install zod

Yup

  • npm install yup

And more coming soon...

Initialize tNRPC

// lib/tnrpc.ts
import { createTNRPC } from "@nitestack/tnrpc";

export const { tNRH, tNSA } = createTNRPC(
  {
    baseUrl: "http://localhost:3000"
  },
  async () => ({}) //Context
);

Route Handler

// app/api/example/route.ts
import { tNRH } from "@/lib/tnrpc";
import { TNRHError } from "@nitestack/tnrpc/error";
import { z } from "zod";

export const { GET, tNRHFetch: getExample } = tNRH.get(
  z.object({ text: z.string() })
)(
  //Type-safe
  ({ input, request, context }) => {
    return input.text;
  },
  {
    url: "/api/example"
  }
);

Page

// app/page.tsx
import { getExample } from "@/app/api/example/route";

async function getData() {
  const res = await getExample({ text: "Hello from Server Component!" });
  return res.json();
}

export default async function ServerComponent() {
  const data = await getData();
  return <pre>{JSON.stringify(data)}</pre>;
}

Server Actions (alpha)

// actions/example.ts
"use server";

import { tNSA } from "@/lib/tnrpc";

import { z } from "zod";

export const getExample = tNSA(z.string())(({ input, context }) => {
  return input;
});

Client Component

// app/page.text
"use client";

import { useTNSA } from "@nitestack/tnrpc/client";
import { getExample } from "@/actions/example";

export default function ClientComponent() {
  const { data, error, loading, mutate, success } = useTNSA(getExample);

  return (
    <>
      {loading && <p>Pending...</p>}
      <button onClick={() => mutate("Call Server Action")}>
        Call Server Action
      </button>
      <button onClick={() => mutate("Another button to call Server Action")}>
        Another button to call Server Action
      </button>
      {success && JSON.stringify(data)}
    </>
  );
}
0.1.4

2 years ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago