Skip to content
/ t_rest Public

Library inspired by tRPC for REST APIs

Notifications You must be signed in to change notification settings

phaux/t_rest

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Typed REST

deno doc

Library inspired by tRPC for REST APIs.

Example

server.ts:

import {
  createEndpoint,
  createMethodFilter,
  createPathFilter,
} from "https://deno.land/x/t_rest/server/mod.ts";

const serveApi = createPathFilter({
  "hello": createMethodFilter({
    GET: createEndpoint(
      {
        query: {
          name: { type: "string" },
        },
      },
      async ({ query }) => {
        return {
          status: 200,
          body: {
            type: "text/plain",
            data: `Hello ${query.name}`,
          },
        };
      },
    ),
  }),
});

Deno.serve({ port: 8000 }, serveApi);

export type ApiHandler = typeof serveApi;

client.ts:

// @deno-types="https://deno.land/x/t_rest/client/mod.ts"
import { createFetcher } from "https://esb.deno.dev/https://deno.land/x/t_rest/client/mod.ts";
import { type ApiHandler } from "./server.ts";

const fetchApi = createFetcher<ApiHandler>({
  baseUrl: "http://localhost:8080/",
});

const response = await fetchApi("hello", "GET", {
  query: { name: "world" },
});

if (response.status !== 200) {
  throw new Error("Request failed");
}
console.log(response.body); // { type: "text/plain", data: "Hello world" }

See more examples in tests.

Features / TODO

  • Query params
  • JSON body (application/json)
  • File uploads (multipart/form-data)
  • Path segment params
  • Custom headers
  • Subscriptions (Server Sent Events / WebSockets)

About

Library inspired by tRPC for REST APIs

Resources

Stars

Watchers

Forks