0.5.0 • Published 2 years ago
ts-rest-hono v0.5.0
ts-rest-hono
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);
}Deno is also supported at deno_dist.
0.5.0
2 years ago
0.1.0
2 years ago
0.3.0
2 years ago
0.2.1
2 years ago
0.2.0
2 years ago
0.3.5
2 years ago
0.3.2
2 years ago
0.4.0
2 years ago
0.3.1
2 years ago
0.3.4
2 years ago
0.3.3
2 years ago
0.0.11
2 years ago
0.0.10
3 years ago
0.0.9
3 years ago
0.0.8
3 years ago
0.0.7
3 years ago
0.0.6
3 years ago
0.0.5
3 years ago
0.0.4
3 years ago
0.0.3
3 years ago
0.0.2
3 years ago
0.0.1
3 years ago