Kita

website·Indexed 31 days ago

https://kitajs.org

A meta router for Fastify that simplifies web development through schematized routing, automatic OpenAPI generation, and type-safe parameter handling for bodies, queries, cookies, and paths.

Tokens
14.7K
Snippets
90
Records
100
Agent score
58%

What's inside Kita

  1. Overview of Kita meta router for Fastify

    Kita is a meta router for Fastify that simplifies API development in TypeScript by using static analysis. It scans the src/routes folder for functions named after HTTP methods (e.g., get, post) and automatically generates the necessary Fastify route registrations. By analyzing the TypeScript types of function parameters and return values, Kita automatically handles input/output data validation and generates OpenAPI-compliant documentation, eliminating the need to manually define separate schemas and documentation files.
  2. Optimize Fastify performance with Kita serialization

    Kita enhances Fastify's performance by automatically inferring I/O types for routes at build time and generating route schemas. This allows Fastify to bypass the overhead of standard JSON.stringify and JSON.parse by utilizing fast-json-stringify for serialization and ajv for validation.
  3. Add summaries and descriptions to routes

    Use @summary for a brief overview of the route. Use @description for a detailed explanation. If @description is used, it overrides the default behavior of using the JSDoc's top-level text as the description.
    /** @summary Creates a new user */
    export function get() {
      return true;
    }
    
    /**
     * Internal code comment (hidden from docs)
     * 
     * @description This is the text that will actually appear in the documentation
     */
    export function post() {
      return true;
    }
  4. Enable in-editor type checking and auto-completion with the Kita TypeScript plugin

    Kita provides a TypeScript plugin that enables developers to get real-time type checking and auto-completion (Intellisense) directly within their code editor.
  5. Generate interactive API documentation with Scalar in Kita

    Kita integrates Scalar to automatically generate interactive API documentation by introspecting your routes, types, and documentation. Once Kita is running, the documentation is accessible at http://localhost:1227/reference.
  6. Validate TypeScript types using JSDoc annotations

    Kita allows you to define validation constraints directly in your TypeScript interfaces using JSDoc tags. These annotations are used to generate JSON Schemas compatible with AJV. You can use any standard AJV Keywords and Formats to validate emails, number ranges, string lengths, and more.
    export interface Example {
      /**
       * @minLength 3
       * @maxLength 20
       */
      name: string;
    
      /** @format email */
      email: string;
    
      /**
       * @minimum 0
       * @maximum 150
       */
      age: number;
    
      /**
       * @minItems 1
       * @maxItems 10
       * @uniqueItems
       */
      items: string[];
    
      /**
       * @minProperties 1
       * @maxProperties 10
       */
      properties: Record<string, string>;
    }
  7. Initialize a new Kita project using the automatic installer

    The recommended way to start a project is using npm create kita. This generates a boilerplate that includes essential production features such as graceful shutdown and resource monitoring. You can choose between a standard Fastify backend template or a frontend template using Fastify and @kitajs/html. Note: Node.js version 20 or higher is required.
    # Create the project
    npm create kita
    
    # Navigate to project folder
    cd project
    
    # Start development server
    npm dev
  8. Migrate an existing Fastify project to Kita

    Migrating from Fastify to Kita is straightforward because Kita is built on top of Fastify. To migrate, install Kita and register the Kita plugin within your Fastify instance. Once the plugin is registered, you can incrementally migrate your routes by moving them into the src/routes directory and defining the appropriate I/O types as per Kita's routing documentation. Existing test suites should continue to work as Kita does not alter the underlying Fastify server behavior.
    import { Kita } from '@kitajs/runtime';
    import fastify from 'fastify';
    
    const app = fastify();
    
    // your routes and plugins
    app.register(Kita);
    
    app.listen({ port: 1227 });
  9. Handle query parameter arrays

    Arrays can be defined at the top level using Query with an array type (e.g., string[]).

    Warning: Fields within complex object types cannot be defined as arrays. For complex array requirements, use Body or BodyProp instead.

    import type { Query } from '@kitajs/runtime';
    
    // Example: /?names[]=foo&names[]=bar
    export function get(names: Query<string[]>) {
      return `Hello ${names.join(', ')}!`;
    }
  10. Set default values for request body parameters

    Default values can be assigned to parameters using both Body and BodyProp by using standard TypeScript default parameter syntax.
    import type { Body, BodyProp } from '@kitajs/runtime';
    
    interface CreateUserRequest {
      name: string;
    }
    
    // Default value for a BodyProp
    export function post(name: BodyProp<string, 'name'> = 'Arthur') {
      return `Hello ${name}!`;
    }
    
    // Default value for a Body object
    export function put(content: Body<CreateUserRequest> = { name: 'Arthur' }) {
      return `Hello ${content.name}!`;
    }
  11. Format logs for development with pino-pretty

    Because JSON logs are difficult for humans to read during development, pino-pretty is recommended. To avoid consuming server processing power for formatting, it should be used via a Unix pipeline in the development script rather than within the application code.
    # Install pino-pretty as a dev dependency
    npm install -D pino-pretty
    {
      "scripts": {
        "dev:server": "node --watch dist/index.js | pino-pretty"
      }
    }
  12. Implement type-checked environment variables with env-schema

    To ensure environment variables are type-checked and validated in a KitaJS application, use the env-schema package in conjunction with KitaSchemas.Environment. This allows you to define a TypeScript interface for your environment variables, including constraints like minimum/maximum values, default values, and formats (e.g., email), which are then enforced at runtime.
    npm i env-schema
    // src/providers/schema.ts
    export interface Environment {
      /**
       * @minimum 1000
       * @maximum 65535
       */
      PORT: number;
    
      /** @default 'development' */
      NODE_ENV: 'development' | 'production';
    
      /** @format email */
      EMAIL: string;
    }
    
    // src/env.ts
    import { KitaSchemas } from '@kitajs/runtime';
    import envSchema from 'env-schema';
    import type { Environment } from './providers/schema';
    
    export const Env = envSchema<Environment>({
      schema: KitaSchemas.Environment,
      dotenv: true
    });
    
    // src/index.ts
    import Kita from '@kitajs/runtime';
    import fastify from 'fastify';
    import { Env } from './env';
    
    const app = fastify();
    app.register(Kita);
    
    app.listen({
      port: Env.PORT // Type-checked access to PORT
    }).then(console.log);