Template
1
0

feat: convert to rpc pattern

This commit is contained in:
2025-04-21 00:18:46 +00:00
parent e5f2be1995
commit 3b9a5cb456
15 changed files with 489 additions and 806 deletions

View File

@@ -1,4 +1,4 @@
import z, { ZodObject, ZodRawShape } from "zod";
import z, { ZodObject, ZodRawShape, ZodType } from "zod";
import type { RelayError } from "./errors.ts";
@@ -10,8 +10,8 @@ export class Action<TActionState extends ActionState = ActionState> {
*
* @param input - Schema defining the input requirements of the action.
*/
input<TInput extends ZodRawShape>(input: TInput): Action<Omit<TActionState, "input"> & { input: ZodObject<TInput> }> {
return new Action({ ...this.state, input: z.object(input) as any });
input<TInput extends ZodType>(input: TInput): Action<Omit<TActionState, "input"> & { input: TInput }> {
return new Action({ ...this.state, input });
}
/**
@@ -57,11 +57,15 @@ export const action: {
type ActionState = {
name: string;
input?: ZodObject;
input?: ZodType;
output?: ZodObject;
handle?: ActionHandlerFn;
};
type ActionHandlerFn<TInput = any, TOutput = any> = TInput extends ZodObject
export type ActionPrepareFn<TAction extends Action, TParams extends ZodType> = (
params: z.infer<TParams>,
) => TAction["state"]["input"] extends ZodType ? z.infer<TAction["state"]["input"]> : void;
type ActionHandlerFn<TInput = any, TOutput = any> = TInput extends ZodType
? (input: z.infer<TInput>) => TOutput extends ZodObject ? Promise<z.infer<TOutput> | RelayError> : Promise<void | RelayError>
: () => TOutput extends ZodObject ? Promise<z.infer<TOutput> | RelayError> : Promise<void | RelayError>;

View File

@@ -1,12 +1,20 @@
import type { RouteMethod } from "./route.ts";
export type RelayAdapter = {
fetch(input: RequestInput): Promise<unknown>;
send(input: RelayRequestInput): Promise<RelayResponse>;
};
export type RequestInput = {
method: RouteMethod;
url: string;
search: string;
body?: string;
export type RelayRequestInput = {
method: string;
params: any;
};
export type RelayResponse =
| {
result: unknown;
id: string;
}
| {
error: {
message: string;
};
id: string;
};

View File

@@ -1,180 +1,102 @@
import z from "zod";
import { BadRequestError, InternalServerError, NotFoundError, RelayError } from "./errors.ts";
import type { Route, RouteMethod } from "./route.ts";
const SUPPORTED_MEHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
export class RelayAPI<TRoutes extends Route[]> {
/**
* Route maps funneling registered routes to the specific methods supported by
* the relay instance.
*/
readonly routes: Routes = {
POST: [],
GET: [],
PUT: [],
PATCH: [],
DELETE: [],
};
/**
* List of paths in the '${method} ${path}' format allowing us to quickly throw
* errors if a duplicate route path is being added.
*/
readonly #paths = new Set<string>();
import { Procedure } from "./procedure.ts";
export class RelayApi<TProcedures extends Procedure[]> {
/**
* Route index in the '${method} ${path}' format allowing for quick access to
* a specific route.
*/
readonly #index = new Map<string, Route>();
readonly #index = new Map<string, Procedure>();
/**
* Instantiate a new Server instance.
*
* @param routes - Routes to register with the instance.
*/
constructor({ routes }: Config<TRoutes>) {
const methods: (keyof typeof this.routes)[] = [];
for (const route of routes) {
this.#validateRoutePath(route);
this.routes[route.method].push(route);
methods.push(route.method);
this.#index.set(`${route.method} ${route.path}`, route);
}
for (const method of methods) {
this.routes[method].sort(byStaticPriority);
constructor({ procedures }: Config<TProcedures>) {
for (const procedure of procedures) {
this.#index.set(procedure.method, procedure);
}
}
/**
* Handle a incoming fetch request.
*
* @param request - Fetch request to pass to a route handler.
* @param method - Method name being executed.
* @param params - Parameters provided with the method request.
* @param id - Request id used for response identification.
*/
async handle(request: Request): Promise<Response> {
const url = new URL(request.url);
const matched = this.#resolve(request.method, request.url);
if (matched === undefined) {
return toResponse(
new NotFoundError(`Invalid routing path provided for ${request.url}`, {
method: request.method,
url: request.url,
}),
);
async call(method: string, params: unknown, id: string): Promise<Response> {
const procedure = this.#index.get(method);
if (procedure === undefined) {
return toResponse(new NotFoundError(`Method '' does not exist`), id);
}
const { route, params } = matched;
// ### Context
// Context is passed to every route handler and provides a suite of functionality
// and request data.
const context: Record<string, unknown> = {};
const args: any[] = [];
// ### Params
// If the route has params we want to coerce the values to the expected types.
if (route.state.params !== undefined) {
const result = await route.state.params.safeParseAsync(params);
if (result.success === false) {
return toResponse(new BadRequestError("Invalid request params", z.prettifyError(result.error)));
}
for (const key in result.data) {
context[key] = (result.data as any)[key];
}
}
// ### Query
// If the route has a query schema we need to validate and parse the query.
if (route.state.search !== undefined) {
const result = await route.state.search.safeParseAsync(toSearch(url.searchParams) ?? {});
if (result.success === false) {
return toResponse(new BadRequestError("Invalid request query", z.prettifyError(result.error)));
}
for (const key in result.data) {
context[key] = (result.data as any)[key];
}
}
// ### Body
// If the route has a body schema we need to validate and parse the body.
if (route.state.body !== undefined) {
let body: Record<string, unknown> = {};
if (request.headers.get("content-type")?.includes("json")) {
body = await request.json();
if (procedure.state.params !== undefined) {
if (params === undefined) {
return toResponse(new BadRequestError("Procedure expected 'params' but got 'undefined'."), id);
}
const result = await route.state.body.safeParseAsync(body);
const result = await procedure.state.params.safeParseAsync(params);
if (result.success === false) {
return toResponse(new BadRequestError("Invalid request body", z.prettifyError(result.error)));
}
for (const key in result.data) {
context[key] = (result.data as any)[key];
return toResponse(new BadRequestError("Invalid request body", z.prettifyError(result.error)), id);
}
args.push(result.data);
}
// ### Actions
// Run through all assigned actions for the route.
if (route.state.actions !== undefined) {
for (const action of route.state.actions) {
const result = (await action.state.input?.safeParseAsync(context)) ?? { success: true, data: {} };
const data: Record<string, unknown> = {};
if (procedure.state.actions !== undefined) {
for (const entry of procedure.state.actions) {
let action = entry;
let input: any;
if (Array.isArray(entry)) {
action = entry[0];
input = entry[1](args[0]);
}
const result = (await action.state.input?.safeParseAsync(input)) ?? { success: true, data: {} };
if (result.success === false) {
return toResponse(new BadRequestError("Invalid action input", z.prettifyError(result.error)));
return toResponse(new BadRequestError("Invalid action input", z.prettifyError(result.error)), id);
}
if (action.state.handle === undefined) {
return toResponse(new InternalServerError(`Action '${action.state.name}' is missing handler.`));
return toResponse(new InternalServerError(`Action '${action.state.name}' is missing handler.`), id);
}
const output = await action.state.handle(result.data);
if (output instanceof RelayError) {
return toResponse(output);
return toResponse(output, id);
}
for (const key in output) {
context[key] = output[key];
data[key] = output[key];
}
}
args.push(data);
}
// ### Handler
// Execute the route handler and apply the result.
if (route.state.handle === undefined) {
return toResponse(new InternalServerError(`Path '${route.method} ${route.path}' is missing request handler.`));
}
return toResponse(await route.state.handle(context).catch((error) => error));
}
/**
* Attempt to resolve a route based on the given method and pathname.
*
* @param method - HTTP method.
* @param url - HTTP request url.
*/
#resolve(method: string, url: string): ResolvedRoute | undefined {
this.#assertMethod(method);
for (const route of this.routes[method]) {
if (route.match(url) === true) {
return { route, params: route.getParsedParams(url) };
}
}
}
#validateRoutePath(route: Route): void {
const path = `${route.method} ${route.path}`;
if (this.#paths.has(path)) {
throw new Error(`Router > Path ${path} already exists`);
}
this.#paths.add(path);
}
#assertMethod(method: string): asserts method is RouteMethod {
if (!SUPPORTED_MEHODS.includes(method)) {
throw new Error(`Router > Unsupported method '${method}'`);
if (procedure.state.handle === undefined) {
return toResponse(new InternalServerError(`Path '${procedure.method}' is missing request handler.`), id);
}
return toResponse(await procedure.state.handle(...args).catch((error) => error), id);
}
}
@@ -184,78 +106,56 @@ export class RelayAPI<TRoutes extends Route[]> {
|--------------------------------------------------------------------------------
*/
/**
* Sorting method for routes to ensure that static properties takes precedence
* for when a route is matched against incoming requests.
*
* @param a - Route A
* @param b - Route B
*/
function byStaticPriority(a: Route, b: Route) {
const aSegments = a.path.split("/");
const bSegments = b.path.split("/");
const maxLength = Math.max(aSegments.length, bSegments.length);
for (let i = 0; i < maxLength; i++) {
const aSegment = aSegments[i] || "";
const bSegment = bSegments[i] || "";
const isADynamic = aSegment.startsWith(":");
const isBDynamic = bSegment.startsWith(":");
if (isADynamic !== isBDynamic) {
return isADynamic ? 1 : -1;
}
if (isADynamic === false && aSegment !== bSegment) {
return aSegment.localeCompare(bSegment);
}
}
return a.path.localeCompare(b.path);
}
/**
* Resolve and return query object from the provided search parameters, or undefined
* if the search parameters does not have any entries.
*
* @param searchParams - Search params to create a query object from.
*/
function toSearch(searchParams: URLSearchParams): object | undefined {
if (searchParams.size === 0) {
return undefined;
}
const result: Record<string, string> = {};
for (const [key, value] of searchParams.entries()) {
result[key] = value;
}
return result;
}
/**
* Takes a server side request result and returns a fetch Response.
*
* @param result - Result to send back as a Response.
* @param id - Request id which can be used to identify the response.
*/
function toResponse(result: object | RelayError | Response | void): Response {
function toResponse(result: object | RelayError | Response | void, id: string): Response {
if (result === undefined) {
return new Response(
JSON.stringify({
result: null,
id,
}),
{
status: 200,
headers: {
"content-type": "application/json",
},
},
);
}
if (result instanceof Response) {
return result;
}
if (result instanceof RelayError) {
return new Response(result.message, {
status: result.status,
});
return new Response(
JSON.stringify({
error: result,
id,
}),
{
status: result.status,
headers: {
"content-type": "application/json",
},
},
);
}
if (result === undefined) {
return new Response(null, { status: 204 });
}
return new Response(JSON.stringify(result), {
status: 200,
headers: {
"content-type": "application/json",
return new Response(
JSON.stringify({
result,
id,
}),
{
status: 200,
headers: {
"content-type": "application/json",
},
},
});
);
}
/*
@@ -264,19 +164,6 @@ function toResponse(result: object | RelayError | Response | void): Response {
|--------------------------------------------------------------------------------
*/
type Config<TRoutes extends Route[]> = {
routes: TRoutes;
};
type Routes = {
POST: Route[];
GET: Route[];
PUT: Route[];
PATCH: Route[];
DELETE: Route[];
};
type ResolvedRoute = {
route: Route;
params: any;
type Config<TProcedures extends Procedure[]> = {
procedures: TProcedures;
};

View File

@@ -1,134 +1,44 @@
import z, { ZodType } from "zod";
import type { RelayAdapter, RequestInput } from "./adapter.ts";
import type { Route, RouteMethod } from "./route.ts";
import type { RelayAdapter } from "./adapter.ts";
import { Procedure, type Procedures } from "./procedure.ts";
export class RelayClient<TRoutes extends Route[]> {
/**
* Route index in the '${method} ${path}' format allowing for quick access to
* a specific route.
*/
readonly #index = new Map<string, Route>();
/**
* Make a new relay client instance.
*
* @param config - Client configuration.
* @param procedures - Map of procedures to make available to the client.
*/
export function makeRelayClient<TProcedures extends Procedures>(config: RelayClientConfig, procedures: TProcedures): RelayClient<TProcedures> {
return mapProcedures(procedures, config.adapter);
}
/**
* Instantiate a new Relay instance.
*
* @param config - Relay configuration to apply to the instance.
* @param routes - Routes to register with the instance.
*/
constructor(readonly config: RelayConfig<TRoutes>) {
for (const route of config.routes) {
this.#index.set(`${route.method} ${route.path}`, route);
/*
|--------------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------------
*/
function mapProcedures<TProcedures extends Procedures>(procedures: TProcedures, adapter: RelayAdapter): RelayClient<TProcedures> {
const client: any = {};
for (const key in procedures) {
const entry = procedures[key];
if (entry instanceof Procedure) {
client[key] = async (params: unknown) => {
const response = await adapter.send({ method: entry.method, params });
if ("error" in response) {
throw new Error(response.error.message);
}
if ("result" in response && entry.state.result !== undefined) {
return entry.state.result.parseAsync(response.result);
}
return response.result;
};
} else {
client[key] = mapProcedures(entry, adapter);
}
}
/**
* Send a "POST" request through the relay `fetch` adapter.
*
* @param path - Path to send request to.
* @param args - List of request arguments.
*/
async post<
TPath extends Extract<TRoutes[number], { state: { method: "POST" } }>["state"]["path"],
TRoute extends Extract<TRoutes[number], { state: { method: "POST"; path: TPath } }>,
>(path: TPath, ...args: TRoute["args"]): Promise<RelayResponse<TRoute>> {
return this.#send("POST", path, args) as RelayResponse<TRoute>;
}
/**
* Send a "GET" request through the relay `fetch` adapter.
*
* @param path - Path to send request to.
* @param args - List of request arguments.
*/
async get<
TPath extends Extract<TRoutes[number], { state: { method: "GET" } }>["state"]["path"],
TRoute extends Extract<TRoutes[number], { state: { method: "GET"; path: TPath } }>,
>(path: TPath, ...args: TRoute["args"]): Promise<RelayResponse<TRoute>> {
return this.#send("GET", path, args) as RelayResponse<TRoute>;
}
/**
* Send a "PUT" request through the relay `fetch` adapter.
*
* @param path - Path to send request to.
* @param args - List of request arguments.
*/
async put<
TPath extends Extract<TRoutes[number], { state: { method: "PUT" } }>["state"]["path"],
TRoute extends Extract<TRoutes[number], { state: { method: "PUT"; path: TPath } }>,
>(path: TPath, ...args: TRoute["args"]): Promise<RelayResponse<TRoute>> {
return this.#send("PUT", path, args) as RelayResponse<TRoute>;
}
/**
* Send a "PATCH" request through the relay `fetch` adapter.
*
* @param path - Path to send request to.
* @param args - List of request arguments.
*/
async patch<
TPath extends Extract<TRoutes[number], { state: { method: "PATCH" } }>["state"]["path"],
TRoute extends Extract<TRoutes[number], { state: { method: "PATCH"; path: TPath } }>,
>(path: TPath, ...args: TRoute["args"]): Promise<RelayResponse<TRoute>> {
return this.#send("PATCH", path, args) as RelayResponse<TRoute>;
}
/**
* Send a "DELETE" request through the relay `fetch` adapter.
*
* @param path - Path to send request to.
* @param args - List of request arguments.
*/
async delete<
TPath extends Extract<TRoutes[number], { state: { method: "DELETE" } }>["state"]["path"],
TRoute extends Extract<TRoutes[number], { state: { method: "DELETE"; path: TPath } }>,
>(path: TPath, ...args: TRoute["args"]): Promise<RelayResponse<TRoute>> {
return this.#send("DELETE", path, args) as RelayResponse<TRoute>;
}
async #send(method: RouteMethod, url: string, args: any[]) {
const route = this.#index.get(`${method} ${url}`);
if (route === undefined) {
throw new Error(`RelayClient > Failed to send request for '${method} ${url}' route, not found.`);
}
// ### Input
const input: RequestInput = { method, url: `${this.config.url}${url}`, search: "" };
let index = 0; // argument incrementor
if (route.state.params !== undefined) {
const params = args[index++] as { [key: string]: string };
for (const key in params) {
input.url = input.url.replace(`:${key}`, params[key]);
}
}
if (route.state.search !== undefined) {
const search = args[index++] as { [key: string]: string };
const pieces: string[] = [];
for (const key in search) {
pieces.push(`${key}=${search[key]}`);
}
if (pieces.length > 0) {
input.search = `?${pieces.join("&")}`;
}
}
if (route.state.body !== undefined) {
input.body = JSON.stringify(args[index++]);
}
// ### Fetch
const data = await this.config.adapter.fetch(input);
if (route.state.output !== undefined) {
return route.state.output.parse(data);
}
return data;
}
return client;
}
/*
@@ -137,10 +47,16 @@ export class RelayClient<TRoutes extends Route[]> {
|--------------------------------------------------------------------------------
*/
type RelayResponse<TRoute extends Route> = TRoute["state"]["output"] extends ZodType ? z.infer<TRoute["state"]["output"]> : void;
type RelayConfig<TRoutes extends Route[]> = {
url: string;
adapter: RelayAdapter;
routes: TRoutes;
export type RelayClient<TProcedures extends Procedures> = {
[TKey in keyof TProcedures]: TProcedures[TKey] extends Procedure<infer TState>
? TState["params"] extends ZodType
? (params: z.infer<TState["params"]>) => Promise<TState["result"] extends ZodType ? z.infer<TState["result"]> : void>
: () => Promise<TState["result"] extends ZodType ? z.infer<TState["result"]> : void>
: TProcedures[TKey] extends Procedures
? RelayClient<TProcedures[TKey]>
: never;
};
export type RelayClientConfig = {
adapter: RelayAdapter;
};

View File

@@ -104,6 +104,23 @@ export class NotFoundError<D = unknown> extends RelayError<D> {
}
}
export class MethodNotAllowedError<D = unknown> extends RelayError<D> {
/**
* Instantiate a new MethodNotAllowedError.
*
* The **HTTP 405 Method Not Allowed** response code indicates that the
* request method is known by the server but is not supported by the target resource.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
*
* @param message - Optional message to send with the error. Default: "Method Not Allowed".
* @param data - Optional data to send with the error.
*/
constructor(message = "Method Not Allowed", data?: D) {
super(message, 405, data);
}
}
export class NotAcceptableError<D = unknown> extends RelayError<D> {
/**
* Instantiate a new NotAcceptableError.
@@ -165,6 +182,23 @@ export class GoneError<D = unknown> extends RelayError<D> {
}
}
export class UnsupportedMediaTypeError<D = unknown> extends RelayError<D> {
/**
* Instantiate a new UnsupportedMediaTypeError.
*
* The **HTTP 415 Unsupported Media Type** response code indicates that the
* server refuses to accept the request because the payload format is in an unsupported format.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
*
* @param message - Optional message to send with the error. Default: "Unsupported Media Type".
* @param data - Optional data to send with the error.
*/
constructor(message = "Unsupported Media Type", data?: D) {
super(message, 415, data);
}
}
export class UnprocessableContentError<D = unknown> extends RelayError<D> {
/**
* Instantiate a new UnprocessableContentError.

153
libraries/procedure.ts Normal file
View File

@@ -0,0 +1,153 @@
import z, { ZodObject, ZodType } from "zod";
import { Action } from "./action.ts";
import { RelayError } from "./errors.ts";
export class Procedure<TState extends State = State> {
declare readonly args: Args<TState>;
constructor(readonly state: TState) {}
get method(): TState["method"] {
return this.state.method;
}
/**
* Params allows for custom casting of URL parameters. If a parameter does not
* have a corresponding zod schema the default param type is "string".
*
* @param params - URL params.
*
* @examples
*
* ```ts
* relay
* .method("user:create")
* .params({
* bar: z.number()
* })
* .handle(async ({ bar }) => {
* console.log(typeof bar); // => number
* });
* ```
*/
params<TParams extends ZodType>(params: TParams): Procedure<Omit<TState, "params"> & { params: TParams }> {
return new Procedure({ ...this.state, params });
}
/**
* List of route level middleware action to execute before running the
* route handler.
*
* @param actions - Actions to execute on this route.
*
* @examples
*
* ```ts
* const hasFooBar = action
* .make("hasFooBar")
* .response(z.object({ foobar: z.number() }))
* .handle(async () => {
* return {
* foobar: 1,
* };
* });
*
* relay
* .method("foo")
* .actions([hasFooBar])
* .handle(async ({ foobar }) => {
* console.log(typeof foobar); // => number
* });
* ```
*/
actions<TAction extends Action, TActionFn extends ActionFn<TAction, this["state"]>>(
actions: (TAction | [TAction, TActionFn])[],
): Procedure<Omit<TState, "actions"> & { actions: TAction[] }> {
return new Procedure({ ...this.state, actions: actions as TAction[] });
}
/**
* Shape of the response this route produces. This is used by the transform
* tools to ensure the client receives parsed data.
*
* @param response - Response shape of the route.
*
* @examples
*
* ```ts
* relay
* .method("foo")
* .result(
* z.object({
* bar: z.number()
* })
* )
* .handle(async () => {
* return { bar: 1 };
* });
* ```
*/
result<TResult extends ZodType>(result: TResult): Procedure<Omit<TState, "result"> & { result: TResult }> {
return new Procedure({ ...this.state, result });
}
/**
* Server handler callback method.
*
* @param handle - Handle function to trigger when the route is executed.
*/
handle<THandleFn extends HandleFn<this["args"], this["state"]["result"]>>(handle: THandleFn): Procedure<Omit<TState, "handle"> & { handle: THandleFn }> {
return new Procedure({ ...this.state, handle });
}
}
/*
|--------------------------------------------------------------------------------
| Factories
|--------------------------------------------------------------------------------
*/
export const procedure: {
method<const TMethod extends string>(method: TMethod): Procedure<{ method: TMethod }>;
} = {
method<const TMethod extends string>(method: TMethod): Procedure<{ method: TMethod }> {
return new Procedure({ method });
},
};
/*
|--------------------------------------------------------------------------------
| Types
|--------------------------------------------------------------------------------
*/
export type Procedures = {
[key: string]: Procedures | Procedure;
};
type State = {
method: string;
params?: ZodType;
actions?: Array<Action>;
result?: ZodType;
handle?: HandleFn;
};
type ActionFn<TAction extends Action, TState extends State> = TState["params"] extends ZodType
? (params: z.infer<TState["params"]>) => TAction["state"]["input"] extends ZodType ? z.infer<TAction["state"]["input"]> : void
: () => TAction["state"]["input"] extends ZodType ? z.infer<TAction["state"]["input"]> : void;
type HandleFn<TArgs extends Array<any> = any[], TResponse = any> = (
...args: TArgs
) => TResponse extends ZodType ? Promise<z.infer<TResponse> | Response | RelayError> : Promise<Response | RelayError | void>;
type Args<TState extends State = State> = [
...(TState["params"] extends ZodType ? [z.infer<TState["params"]>] : []),
...(TState["actions"] extends Array<Action> ? [UnionToIntersection<MergeAction<TState["actions"]>>] : []),
];
type MergeAction<TActions extends Array<Action>> =
TActions[number] extends Action<infer TState> ? (TState["output"] extends ZodObject ? z.infer<TState["output"]> : object) : object;
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;

View File

@@ -1,64 +1,77 @@
import type { Route, RouteMethod } from "./route.ts";
import { makeRelayClient, RelayClient, RelayClientConfig } from "./client.ts";
import { Procedure, Procedures } from "./procedure.ts";
export class Relay<TRoutes extends Route[]> {
/**
* Route index in the '${method} ${path}' format allowing for quick access to
* a specific route.
*/
readonly #index = new Map<string, Route>();
export class Relay<TProcedures extends Procedures, TProcedureIndex = ProcedureIndex<TProcedures>> {
readonly #index = new Map<keyof TProcedureIndex, Procedure>();
declare readonly $inferRoutes: TRoutes;
declare readonly $inferClient: RelayClient<TProcedures>;
declare readonly $inferIndex: TProcedureIndex;
/**
* Instantiate a new Relay instance.
*
* @param config - Relay configuration to apply to the instance.
* @param routes - Routes to register with the instance.
* @param procedures - Procedures to register with the instance.
*/
constructor(readonly routes: TRoutes) {
for (const route of routes) {
this.#index.set(`${route.method} ${route.path}`, route);
}
constructor(readonly procedures: TProcedures) {
indexProcedures(procedures, this.#index);
}
/**
* Retrieve a route for the given method/path combination which can be further extended
* for serving incoming third party requests.
* Retrieve a registered procedure registered with the relay instance.
*
* @param method - Method the route is registered for.
* @param path - Path the route is registered under.
*
* @examples
*
* ```ts
* const relay = new Relay([
* route
* .post("/users")
* .body(
* z.object({
* name: z.object({ family: z.string(), given: z.string() }),
* email: z.string().check(z.email()),
* })
* )
* ]);
*
* relay
* .route("POST", "/users")
* .actions([hasSessionUser, hasAccess("users", "create")])
* .handle(async ({ name, email, sessionUserId }) => {
* // await db.users.insert({ name, email, createdBy: sessionUserId });
* })
* ```
* @param method - Method name assigned to the procedure.
*/
route<
TMethod extends RouteMethod,
TPath extends Extract<TRoutes[number], { state: { method: TMethod } }>["state"]["path"],
TRoute extends Extract<TRoutes[number], { state: { method: TMethod; path: TPath } }>,
>(method: TMethod, path: TPath): TRoute {
const route = this.#index.get(`${method} ${path}`);
if (route === undefined) {
throw new Error(`Relay > Route not found at '${method} ${path}' index`);
}
return route as TRoute;
procedure<TMethod extends keyof TProcedureIndex>(method: TMethod): TProcedureIndex[TMethod] {
return this.#index.get(method) as TProcedureIndex[TMethod];
}
/**
* Create a new relay client instance from the instance procedures.
*
* @param config - Client configuration.
*/
client(config: RelayClientConfig): this["$inferClient"] {
return makeRelayClient(config, this.procedures) as any;
}
}
/*
|--------------------------------------------------------------------------------
| Types
|--------------------------------------------------------------------------------
*/
function indexProcedures<TProcedures extends Procedures, TProcedureIndex = ProcedureIndex<TProcedures>, TProcedureKey = keyof TProcedureIndex>(
procedures: TProcedures,
index: Map<TProcedureKey, Procedure>,
) {
for (const key in procedures) {
if (procedures[key] instanceof Procedure) {
const method = procedures[key].method as TProcedureKey;
if (index.has(method)) {
throw new Error(`Relay > Procedure with method '${method}' already exists!`);
}
index.set(method, procedures[key]);
} else {
indexProcedures(procedures[key], index);
}
}
}
/*
|--------------------------------------------------------------------------------
| Types
|--------------------------------------------------------------------------------
*/
type ProcedureIndex<TProcedures extends Procedures> = MergeUnion<FlattenProcedures<TProcedures>>;
type FlattenProcedures<TProcedures extends Procedures> = {
[TKey in keyof TProcedures]: TProcedures[TKey] extends Procedure<infer TState>
? Record<TState["method"], TProcedures[TKey]>
: TProcedures[TKey] extends Procedures
? FlattenProcedures<TProcedures[TKey]>
: never;
}[keyof TProcedures];
type MergeUnion<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? { [K in keyof I]: I[K] } : never;

View File

@@ -1,341 +0,0 @@
import z, { ZodObject, ZodRawShape, ZodType } from "zod";
import { Action } from "./action.ts";
import { RelayError } from "./errors.ts";
export class Route<TRouteState extends RouteState = RouteState> {
#pattern?: URLPattern;
declare readonly args: RouteArgs<TRouteState>;
declare readonly context: RouteContext<TRouteState>;
constructor(readonly state: TRouteState) {}
/**
* HTTP Method
*/
get method(): RouteMethod {
return this.state.method;
}
/**
* URL pattern of the route.
*/
get pattern(): URLPattern {
if (this.#pattern === undefined) {
this.#pattern = new URLPattern({ pathname: this.path });
}
return this.#pattern;
}
/**
* URL path
*/
get path(): string {
return this.state.path;
}
/**
* Check if the provided URL matches the route pattern.
*
* @param url - HTTP request.url
*/
match(url: string): boolean {
return this.pattern.test(url);
}
/**
* Extract parameters from the provided URL based on the route pattern.
*
* @param url - HTTP request.url
*/
getParsedParams(url: string): object {
const params = this.pattern.exec(url)?.pathname.groups;
if (params === undefined) {
return {};
}
return params;
}
/**
* Params allows for custom casting of URL parameters. If a parameter does not
* have a corresponding zod schema the default param type is "string".
*
* @param params - URL params.
*
* @examples
*
* ```ts
* route
* .post("/foo/:bar")
* .params({
* bar: z.number({ coerce: true })
* })
* .handle(async ({ params: { bar } }) => {
* console.log(typeof bar); // => number
* });
* ```
*/
params<TParams extends ZodRawShape>(params: TParams): Route<Omit<TRouteState, "params"> & { params: ZodObject<TParams> }> {
return new Route({ ...this.state, params: z.object(params) as any });
}
/**
* Search allows for custom casting of URL search parameters. If a parameter does
* not have a corresponding zod schema the default param type is "string".
*
* @param search - URL search arguments.
*
* @examples
*
* ```ts
* route
* .post("/foo")
* .search({
* bar: z.number({ coerce: true })
* })
* .handle(async ({ search: { bar } }) => {
* console.log(typeof bar); // => number
* });
* ```
*/
search<TSearch extends ZodRawShape>(search: TSearch): Route<Omit<TRouteState, "search"> & { search: ZodObject<TSearch> }> {
return new Route({ ...this.state, search: z.object(search) as any });
}
/**
* Shape of the body this route expects to receive. This is used by all
* mutator routes and has no effect when defined on "GET" methods.
*
* @param body - Body the route expects.
*
* @examples
*
* ```ts
* route
* .post("/foo")
* .body(
* z.object({
* bar: z.number()
* })
* )
* .handle(async ({ bar }) => {
* console.log(typeof bar); // => number
* });
* ```
*/
body<TBody extends ZodObject>(body: TBody): Route<Omit<TRouteState, "body"> & { body: TBody }> {
return new Route({ ...this.state, body });
}
/**
* List of route level middleware action to execute before running the
* route handler.
*
* @param actions - Actions to execute on this route.
*
* @examples
*
* ```ts
* const hasFooBar = action
* .make("hasFooBar")
* .response(z.object({ foobar: z.number() }))
* .handle(async () => {
* return {
* foobar: 1,
* };
* });
*
* route
* .post("/foo")
* .actions([hasFooBar])
* .handle(async ({ foobar }) => {
* console.log(typeof foobar); // => number
* });
* ```
*/
actions<TAction extends Action>(actions: TAction[]): Route<Omit<TRouteState, "actions"> & { actions: TAction[] }> {
return new Route({ ...this.state, actions });
}
/**
* Shape of the response this route produces. This is used by the transform
* tools to ensure the client receives parsed data.
*
* @param response - Response shape of the route.
*
* @examples
*
* ```ts
* route
* .post("/foo")
* .response(
* z.object({
* bar: z.number()
* })
* )
* .handle(async () => {
* return {
* bar: 1
* }
* });
* ```
*/
response<TResponse extends ZodType>(output: TResponse): Route<Omit<TRouteState, "output"> & { output: TResponse }> {
return new Route({ ...this.state, output });
}
/**
* Server handler callback method.
*
* @param handle - Handle function to trigger when the route is executed.
*/
handle<THandleFn extends HandleFn<this["context"], this["state"]["output"]>>(handle: THandleFn): Route<Omit<TRouteState, "handle"> & { handle: THandleFn }> {
return new Route({ ...this.state, handle });
}
}
/*
|--------------------------------------------------------------------------------
| Factories
|--------------------------------------------------------------------------------
*/
/**
* Route factories allowing for easy generation of relay compliant routes.
*/
export const route: {
post<TPath extends string>(path: TPath): Route<{ method: "POST"; path: TPath }>;
get<TPath extends string>(path: TPath): Route<{ method: "GET"; path: TPath }>;
put<TPath extends string>(path: TPath): Route<{ method: "PUT"; path: TPath }>;
patch<TPath extends string>(path: TPath): Route<{ method: "PATCH"; path: TPath }>;
delete<TPath extends string>(path: TPath): Route<{ method: "DELETE"; path: TPath }>;
} = {
/**
* Create a new "POST" route for the given path.
*
* @param path - Path to generate route for.
*
* @examples
*
* ```ts
* route
* .post("/foo")
* .body(
* z.object({ bar: z.string() })
* );
* ```
*/
post<TPath extends string>(path: TPath) {
return new Route({ method: "POST", path });
},
/**
* Create a new "GET" route for the given path.
*
* @param path - Path to generate route for.
*
* @examples
*
* ```ts
* route.get("/foo");
* ```
*/
get<TPath extends string>(path: TPath) {
return new Route({ method: "GET", path });
},
/**
* Create a new "PUT" route for the given path.
*
* @param path - Path to generate route for.
*
* @examples
*
* ```ts
* route
* .put("/foo")
* .body(
* z.object({ bar: z.string() })
* );
* ```
*/
put<TPath extends string>(path: TPath) {
return new Route({ method: "PUT", path });
},
/**
* Create a new "PATCH" route for the given path.
*
* @param path - Path to generate route for.
*
* @examples
*
* ```ts
* route
* .patch("/foo")
* .body(
* z.object({ bar: z.string() })
* );
* ```
*/
patch<TPath extends string>(path: TPath) {
return new Route({ method: "PATCH", path });
},
/**
* Create a new "DELETE" route for the given path.
*
* @param path - Path to generate route for.
*
* @examples
*
* ```ts
* route.delete("/foo");
* ```
*/
delete<TPath extends string>(path: TPath) {
return new Route({ method: "DELETE", path });
},
};
/*
|--------------------------------------------------------------------------------
| Types
|--------------------------------------------------------------------------------
*/
type RouteState = {
method: RouteMethod;
path: string;
params?: ZodObject;
search?: ZodObject;
body?: ZodObject;
actions?: Array<Action>;
output?: ZodType;
handle?: HandleFn;
};
export type RouteMethod = "POST" | "GET" | "PUT" | "PATCH" | "DELETE";
export type HandleFn<TContext = any, TResponse = any> = (
context: TContext,
) => TResponse extends ZodType ? Promise<z.infer<TResponse> | Response | RelayError> : Promise<Response | RelayError | void>;
type RouteContext<TRouteState extends RouteState = RouteState> = (TRouteState["params"] extends ZodObject ? z.infer<TRouteState["params"]> : object) &
(TRouteState["search"] extends ZodObject ? z.infer<TRouteState["search"]> : object) &
(TRouteState["body"] extends ZodObject ? z.infer<TRouteState["body"]> : object) &
(TRouteState["actions"] extends Array<Action> ? UnionToIntersection<MergeAction<TRouteState["actions"]>> : object);
type RouteArgs<TRouteState extends RouteState = RouteState> = [
...TupleIfZod<TRouteState["params"]>,
...TupleIfZod<TRouteState["search"]>,
...TupleIfZod<TRouteState["body"]>,
];
type TupleIfZod<TState> = TState extends ZodObject ? [z.infer<TState>] : [];
type MergeAction<TActions extends Array<Action>> =
TActions[number] extends Action<infer TActionState> ? (TActionState["output"] extends ZodObject ? z.infer<TActionState["output"]> : object) : object;
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;