Skip to content

msutkowski/ts-rest-hono

Repository files navigation

ts-rest-hono

🔥 A hono adapter for ts-rest 🔥

Incrementally adoptable RPC-like client and server helpers for a magical end to end typed experience + The small, simple, and ultrafast web framework for the Edges.

GitHub Repo stars Bundle Size

Set it up in 3 Steps!

1. Define your Contract.

// contract.ts
import { initContract } from "@ts-rest/core";
import { z } from "zod";

const c = initContract();

export const TodoSchema = z.object({
  id: z.string(),
  title: z.string(),
  completed: z.boolean(),
});

export const contract = c.router({
  getTodos: {
    method: "GET",
    path: "/todos",
    responses: {
      201: TodoSchema.array(),
    },
    summary: "Create ",
  },
  createTodo: {
    method: "POST",
    path: "/todo",
    responses: {
      201: TodoSchema,
    },
    body: z.object({
      title: z.string(),
      completed: z.boolean(),
    }),
    summary: "Creates a todo.",
  },
});

2. Initialize Server Router.

// router.ts
import { initServer } from "ts-rest-hono";
import { contract } from "./contract";
import { nanoid } from "nanoid";

const s = initServer();

type Todo = {
  id: string;
  title: string;
  completed: boolean;
};

// Database
const todos: Todo[] = [];

export const router = s.router(contract, {
  getTodos: async () => {
    return {
      status: 201,
      body: todos,
    };
  },
  createTodo: async ({ body: { completed, title } }) => {
    const newTodo = {
      id: nanoid(),
      title,
      completed,
    };

    todos.push(newTodo);

    return {
      status: 201,
      body: newTodo,
    };
  },
});

3. Create Endpoints on App.

// app.ts
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { createHonoEndpoints } from "ts-rest-hono";
import { contract } from "./contract";
import { router } from "./router";

const app = new Hono();

app.get("/", (c) => {
  return c.text("🔥 Hello Hono!");
});

createHonoEndpoints(contract, router, app);

// Run the server!
try {
  serve(app, (info) => {
    console.log(`Listening on http://localhost:${info.port}`);
  });
} catch (err) {
  console.log(err);
  process.exit(1);
}

Finally just run app.ts

It's that easy! Enjoy your ultra-fast typesafe API 🔥🚀

Deno is also supported at deno_dist.