End-to-End type safety for REST APIs written in Fastify. Only problem is you have to explicity export and register route handlers. LOL

Overview

Chino

intelligence in japaneese

End-to-End type safety for REST APIs written in Fastify. Only problem is you have to explicity export and register route handlers. LOL

Why ?

I love tRPC, like really. But even If I migrated Mirai's codebase to v10, the type inference speed didn't improve that much. I know that the maintainers are working really hard, still out of my frustration, I tried to write something which can make REST APIs end to end type-safe. Definitely there are trade-offs. I borrowed the idea of centralized route registration convention from ruby on rails. I really like the idea of explicitly registering routes. So yes, this thing works. I was able to make it work with Fastify's types for now. Will add some tests and release it later this week. If everything goes well, Mirai will be moving to full REST APIs.

Convention

  • When registering routes to the registry, the route path and method should be separated by '#'
const Routes = {
  // the route path is prefixed by #
  // this is needed for proper request execution
  // this is a convention we expect to follow
  'get#/users': handler,
  'get#/users/user2': handler2,
};

API

Chino has a super small API surface.

ChinoClient

creates the chino client instance, uses Axios under the hood. Just create a new class by passing your registry type as a generic.

// --- Server code (FAstify server only)

import { FastifyRequest } from 'fastify';
import { ChinoClient } from '../src';

interface Params1 {
  id: string;
}

interface Query1 {
  name: string;
}

async function handler(req: FastifyRequest<{ Params: Params1 }>) {
  return req.params;
}

async function handler2(req: FastifyRequest<{ Querystring: Query1 }>) {
  return req.query;
}

async function handler3(
  req: FastifyRequest<{ Body: { user: { name: string } } }>,
) {
  return req.body;
}

// start by creating a route registry

const Routes = {
  // the route path is prefixed by #
  // this is needed for proper request execution
  // this is a convention we expect to follow
  'get#/users': handler,
  'get#/users/user2': handler2,
};


// --- client code (Frontend app i guess) 

// create chino client
const chino = new ChinoClient<typeof Routes>();
// here you can pass axios instance config

async function getData() {
  const data = await chino.fetch('get#/users', {
    // these are params
    // same happens for query and body
    params: {
      id: '10',
    },
  });

  // full type safety
  data.data.id;

  const data2 = await chino.fetch('get#/users/user2', {
    query: {
      name: 'sambit',
    },
  });
}

Tradeoffs

  • Developer burden of explicitly exporting and registering route handlers
  • Again the above point as js BE developers are used to writing inlined arrow functions for route handlers

Credits

You might also like...

The interpretation implementation implemented programming language built for fun. I'm currently boring in full stack web development. So, I crafted this one LoL. 👻

The interpretation implementation implemented programming language built for fun. I'm currently boring in full stack web development. So, I crafted this one LoL.  👻

What's Wuttyi? Everything is expression 👻 I just developed this tiny programming language because of boring in higher level programming construct. Mo

Dec 13, 2022

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 HypeScript Introduction This is a simplified implementation of TypeScript's type system that's written in TypeScript's type annotations. This means

Dec 20, 2022

A back-end web app allows you to register and login to access a secrets page

A back-end web app allows you to register and login to access a secrets page

Oct 30, 2022

100 Days of Code is a self improvement tool, where you make a commitment to solve 1 coding problem everyday for the next 100 days.

100 Days of Code is a self-improvement tool, where you make a commitment to solve 1 coding problem everyday for the next 100 days. This repository includes a range of tasks, lessons, resources, and challenges on various programming languages to help improve programming skills.

Dec 14, 2022

✨ A cli can automatically export files of the same type

✨ A cli can automatically export files of the same type

auto-export A cli can automatically export files Why When you want to export many files of the same type in one folder, you may cost a lot of time to

Aug 11, 2022

Making(Creating , Modifying , Deleting) Lists you have to do 😎 Built Only with Html, JavaScript, Css

Making(Creating , Modifying , Deleting) Lists you have to do 😎 Built Only with Html, JavaScript, Css

To-Do_App Live Demo You Can See The Project Live On: Here Description A Simple To-Do App Mainly Written In Javascript The project structure is kinda l

Nov 2, 2022

Automatically document all of your Remix loaders and actions typings per each route. 📚

Automatically document all of your Remix loaders and actions typings per each route. 📚

About remix-docs-gen parses all of your Remix loaders and actions and automatically documents all the typings per each route. Installation First, you

Nov 9, 2022

This project is for hacktoberfest to encourage new developer and open source developers to contribute to open source and improve skills which require debugging, write testable code, industry standards, problem solving and many more,

This project is for hacktoberfest to encourage new developer and open source developers to contribute to open source and improve skills which require debugging, write testable code, industry standards, problem solving and many more,

🚀 Blog project for hacktoberfest In this repository, you can find issues related to a blog project that is built on top of Next.js. The project is a

Oct 9, 2022

Check if a url is a known route to a next.js application ahead of time

next-known-route Check if a url is a known route to a next.js application ahead of time. https://www.npmjs.com/package/next-known-route Use Case Why d

Jul 17, 2022
Owner
sambit sahoo
small engineer, vue, react, node, FE @revenuehero Built @billbird-dev
sambit sahoo
Here I will add daily one problem with solution basic to advance level and try to add multiple solutions of a single problem.

#100-code-days ?? I am adding daily 1 JavaScript solution here ?? and you can fork the repo for add your solution for any specific probelm ⌛️ Day 01:

Amir Sohel 4 Jan 22, 2022
Run REST APIs in Node.js applications frameworks (Express, Koa, Hapi and Fastify) on top of any Serverless Cloud.

?? Serverless Adapter Install | Usage | Support | Architecture | Credits Run REST APIs and other web applications using your existing Node.js applicat

Vinicius Lourenço 45 Jan 1, 2023
OBL is a free, libre and open source botlist for Discord, Revolt, Telegram and Guilded. No nfts,no web3,no daos. only bots lol

OBL (aka OpenBotList) Obl is a free,libre and open source botlist for Discord, Revolt, Telegram and Guilded that has free bananas ( Revolt, Telegram a

OpenBotList Foundation 10 Sep 26, 2022
Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Stratulat Alexandru 192 Jan 2, 2023
This is a vanilla Node.js rest API created to show that it is possible to create a rest API using only vanilla Node.js

This is a vanilla Node.js rest API created to show that it is possible to create a rest API using only vanilla Node.js. But in most cases, I would recommend you to use something like Express in a production project for productivity purposes.

Eduardo Dantas 7 Jul 19, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Utilities to work with protocol handlers (like "vscode://") on the web.

Protocol Handlers Utilities to work with protocol handlers on the web. Why? While the Navigator API provides methods to .registerProtocolHandler() and

Artem Zakharchenko 11 Oct 1, 2022
zieeco 12 Jul 8, 2022