T8 SDK Factory

Schema definition

The APISchema type used with the RequestService constructor is a custom schema outlining the types of requests and responses within an API. The example below shows what such a schema may look like.

import type { Schema } from "@t8/sdk-factory";

// wrapping into the `Schema` generic type is optional, but
// this helps validate the basic schema structure
export type APISchema = Schema<{
  // a schema key can be any unique string, for an HTTP API
  // a pair of a method and a path can serve this purpose
  "GET /items/:id": {
    request: {
      // `params` can be omitted if the URL path is fixed and
      // has no parameter placeholders
      params: {
        id: number;
      };
      query?: {
        mode?: "compact" | "full";
      };
    };
    response: {
      body: {
        id: number;
        name?: string;
      };
    };
  };
  "POST /items/:id": {
    // ...
  };
  "GET /items": {
    // ...
  };
  // ... and so forth
}>;

With such a schema assigned to service, calls to its send() method will be prevalidated against this schema, which means that a type-aware IDE will warn of type mismatches or typos in the parameters:

let { ok, status, body } = await service.send("GET /items/:id", {
  params: {
    id: 10,
  },
  query: {
    mode: "full",
  },
});

The options passed as the second parameter to send() are validated as APISchema["GET /items/:id"] based on the schema type passed to the RequestService constructor and the first parameter passed to send().