@contract-kit/application
v1.0.0
Published
Use case builder for contract-kit - framework-agnostic
Maintainers
Readme
@contract-kit/application
Use case builder for Contract Kit - framework-agnostic commands and queries
This package provides a clean way to define use cases (commands and queries) that are framework-agnostic and work with any Standard Schema library.
Installation
npm install @contract-kit/application
# Use with your preferred Standard Schema library
npm install zodTypeScript requirements
This package requires TypeScript 5.0 or higher for proper type inference.
Concepts
Commands vs queries
- Commands - Write operations with side effects (create, update, delete)
- Queries - Read-only operations (get, list, search)
This separation helps with:
- Clear intent in your code
- Easier testing (queries are pure functions)
- CQRS-style architecture if needed
Use cases
A use case encapsulates a single business operation with:
- A unique name for identification
- Input schema for runtime validation
- Output schema for runtime validation
- Optional domain events it may emit
Use cases validate their input before your .run(...) function is called and
validate the returned output before resolving. That makes them safe to call from
HTTP handlers, jobs, scripts, tests, and event handlers.
Usage
Route handler or use case?
Use a route handler alone when the endpoint is just transport glue: health checks, webhooks that only normalize a payload, or a one-off adapter response. Use a use case when the workflow has business rules, touches ports, should be tested directly, or may later run from HTTP, jobs, scripts, events, or tests.
Authorization
Use hooks or adapter middleware for HTTP boundary authentication. Put business authorization in use cases or app-owned policy functions so ownership, role, tenant, plan, and resource-state rules run no matter which entrypoint calls the workflow.
import { requireUser } from "@/lib/auth";
import { authorizePost } from "@/policies/posts";
import { appError } from "@/server/errors";
export const updatePost = useCase
.command("posts.update")
.input(UpdatePostInput)
.output(PostOutput)
.run(async ({ ctx, input }) => {
const user = requireUser(ctx);
const post = await ctx.ports.posts.findById(input.id);
if (!post) {
throw appError("PostNotFound", { details: { id: input.id } });
}
authorizePost(user, "update", post);
return ctx.ports.posts.update(input.id, input);
});Policy functions should stay plain TypeScript. One-off checks can live inline;
repeated rules can move to modules like policies/posts.ts.
Creating a use case builder
// use-cases/builder.ts
import { createUseCase } from "@contract-kit/application";
import type { AppCtx } from "./ctx";
export const useCase = createUseCase<AppCtx>();Validation is enabled by default. You can opt out at the builder level when you only want schema metadata or you are deliberately avoiding duplicate validation:
export const useCase = createUseCase<AppCtx>({
validate: false,
});
// Or configure phases independently:
export const useCase = createUseCase<AppCtx>({
validate: { input: true, output: false },
});Defining commands
// use-cases/todos/create.ts
import { z } from "zod";
import { useCase } from "../builder";
const CreateTodoInput = z.object({
title: z.string().min(1),
description: z.string().optional(),
});
const CreateTodoOutput = z.object({
id: z.string(),
title: z.string(),
completed: z.boolean(),
});
export const createTodo = useCase
.command("todos.create")
.input(CreateTodoInput)
.output(CreateTodoOutput)
.run(async ({ ctx, input }) => {
const todo = await ctx.ports.db.todos.create({
id: crypto.randomUUID(),
title: input.title,
description: input.description,
completed: false,
});
return {
id: todo.id,
title: todo.title,
completed: todo.completed,
};
});The input value received by .run(...) is the parsed schema output, so schema
coercions, defaults, and transforms are applied before your business logic runs.
The finalized use case exposes its schemas as public properties. Reuse them in contracts when the HTTP shape matches the application shape:
export const createTodoContract = todos
.post("/api/todos")
.body(createTodo.inputSchema)
.responses({
201: createTodo.outputSchema,
});Defining queries
// use-cases/todos/get.ts
import { z } from "zod";
import { useCase } from "../builder";
const GetTodoInput = z.object({
id: z.string(),
});
const GetTodoOutput = z.object({
id: z.string(),
title: z.string(),
description: z.string().nullable(),
completed: z.boolean(),
}).nullable();
export const getTodo = useCase
.query("todos.get")
.input(GetTodoInput)
.output(GetTodoOutput)
.run(async ({ ctx, input }) => {
const todo = await ctx.ports.db.todos.findById(input.id);
if (!todo) {
return null;
}
return {
id: todo.id,
title: todo.title,
description: todo.description,
completed: todo.completed,
};
});Emitting domain events
Use cases can declare which domain events they may emit. .emits(...) records metadata; publish the event from inside .run(...) using your event bus port:
// use-cases/todos/complete.ts
import { z } from "zod";
import { useCase } from "../builder";
import { TodoCompletedEvent } from "@/domain/events";
import { publishEvent } from "@contract-kit/events";
const CompleteTodoInput = z.object({
id: z.string(),
});
const CompleteTodoOutput = z.object({
success: z.boolean(),
});
export const completeTodo = useCase
.command("todos.complete")
.input(CompleteTodoInput)
.output(CompleteTodoOutput)
.emits([TodoCompletedEvent])
.run(async ({ ctx, input }) => {
const todo = await ctx.ports.db.todos.update(input.id, {
completed: true,
completedAt: new Date(),
});
if (!todo) {
return { success: false };
}
// Publish the domain event through the validated helper
await publishEvent(ctx.ports.eventBus, TodoCompletedEvent, {
todoId: todo.id,
completedAt: todo.completedAt.toISOString(),
});
return { success: true };
});Application context
Your application context provides access to ports (dependencies):
// app-context.ts
import type { PortsContext } from "@contract-kit/ports";
import type { AppPorts } from "@/ports";
export interface AppCtx extends PortsContext<AppPorts> {
user: { id: string; role: string } | null;
now: () => Date;
requestId: string;
}Using with Next.js adapter
Use cases integrate directly with @contract-kit/next:
// server/index.ts
import { defineRoutes } from "@contract-kit/next";
import { getTodoContract } from "@/contracts/todos";
import { getTodo } from "@/use-cases/todos/get";
export const routes = defineRoutes([
{
contract: getTodoContract,
handle: async ({ ctx, path }) => {
const todo = await getTodo.run({
ctx,
input: { id: path.id },
});
return { status: 200, body: todo };
},
},
]);API reference
createUseCase<Ctx>()
Creates a use case builder with a specific context type.
const useCase = createUseCase<AppCtx>();useCase.command(name)
Starts building a command use case.
useCase
.command("todos.create")
.input(InputSchema)
.output(OutputSchema)
.emits([DomainEvent]) // Optional
.run(async ({ ctx, input }) => { ... });useCase.query(name)
Starts building a query use case.
useCase
.query("todos.get")
.input(InputSchema)
.output(OutputSchema)
.run(async ({ ctx, input }) => { ... });createUseCaseTester<Ctx>(ctx)
Creates a small test harness around a fixed context or a context factory:
import { createUseCaseTester } from "@contract-kit/application";
const tester = createUseCaseTester<AppCtx>(() => ({
ports: { db: createInMemoryDb() },
user: { id: "user-1", role: "user" },
requestId: "test-request",
}));
const result = await tester.run(createTodo, { title: "Test" });Use a context factory when tests mutate in-memory ports or request-scoped state.
Call tester.ctx() when multiple use cases in the same test need to share one
context instance.
Type helpers
UseCaseInput<TUseCase>, UseCaseOutput<TUseCase>, and
UseCaseContext<TUseCase> extract the input, output, and context types from a
finalized use case.
Use case definition
The resulting use case definition includes:
type UseCaseDef = {
name: string; // Unique identifier
kind: "command" | "query";
inputSchema: StandardSchema;
outputSchema: StandardSchema;
emits: DomainEvent[]; // Domain events (metadata only)
run: (args: { ctx: Ctx; input: Input }) => Promise<Output>;
};Validation errors
If input or output validation fails, .run(...) throws UseCaseValidationError:
import { UseCaseValidationError } from "@contract-kit/application";
try {
await createTodo.run({ ctx, input });
} catch (error) {
if (error instanceof UseCaseValidationError) {
console.log(error.useCaseName); // "todos.create"
console.log(error.phase); // "input" | "output"
console.log(error.issues); // Standard Schema issues
}
}Testing use cases
Use cases are easy to test because their dependencies come from the explicit context you pass to the tester:
import { createUseCaseTester } from "@contract-kit/application";
import { createTodo } from "@/use-cases/todos/create";
describe("createTodo", () => {
it("creates a todo", async () => {
const mockDb = {
todos: {
create: vi.fn().mockResolvedValue({
id: "1",
title: "Test",
completed: false,
}),
},
};
const tester = createUseCaseTester(() => ({
ports: { db: mockDb },
user: { id: "user-1", role: "user" },
}));
const result = await tester.run(createTodo, { title: "Test" });
expect(result).toEqual({
id: "1",
title: "Test",
completed: false,
});
expect(mockDb.todos.create).toHaveBeenCalled();
});
});Related packages
@contract-kit/core- Core contract definitions@contract-kit/ports- Ports & Adapters pattern@contract-kit/domain- Domain modeling@contract-kit/next- Next.js integration@contract-kit/server- Server runtime
License
MIT
