Skip to content

Build a writable book catalog ​

Extend the read-only endpoint so a client can create a book, follow its Location and retrieve the stored record. This example keeps its state in memory for the lifetime of one application.

1. Give the store an owner ​

Create catalog.ts beside main.ts. The store assigns identifiers and owns the records. It can be tested independently of HTTP.

ts
import { Injectable } from "@chojs/web";

export type Book = { id: string; title: string };

@Injectable()
export class Catalog {
  readonly #books = new Map<string, Book>();

  add(title: string): Book {
    const book = { id: crypto.randomUUID(), title };
    this.#books.set(book.id, book);
    return book;
  }

  find(id: string): Book | undefined {
    return this.#books.get(id);
  }
}

2. Register the store and routes ​

Replace app.ts with the following. Both methods share the Catalog instance declared in Library. The POST handler receives the trimmed title only after the validator succeeds. Its @Doc declaration records the 201 response for tools that read the API description.

ts
import {
  Args, Body, ChoWeb, Controller, Doc, Get, Middlewares, Module, Param, Post, validate,
} from "@chojs/web";
import { Catalog } from "./catalog.ts";

export const bookTitle = {
  parse(value: unknown): string {
    if (typeof value !== "string" || value.trim() === "") {
      throw new Error("Supply a non-empty title");
    }
    return value.trim();
  },
};

@Middlewares(validate())
@Controller({ route: "books", dependencies: [Catalog] })
class Books {
  constructor(readonly catalog: Catalog) {}

  @Doc({
    operationId: "createBook",
    summary: "Add a book to the catalog",
    responses: { 201: { description: "Book created", contentType: "application/json" } },
  })
  @Post("")
  @Args(Body("title", bookTitle))
  create(title: string) {
    const book = this.catalog.add(title);
    return Response.json(book, {
      status: 201,
      headers: { location: "/api/books/" + book.id },
    });
  }

  @Doc({
    operationId: "findBook",
    summary: "Find a book by ID",
    responses: { 404: { description: "Book not found" } },
  })
  @Get(":id")
  @Args(Param("id"))
  find(id: string) {
    return this.catalog.find(id) ??
      Response.json({ error: "Book not found" }, { status: 404 });
  }
}

@Module({ providers: [Catalog], controllers: [Books] })
export class Library {}

export const createApp = () => ChoWeb.create(Library, { prefix: "api" });

3. Create and retrieve a record ​

Use the main.ts and launch command from the HTTP quick start. In another terminal, create a book:

sh
curl -i http://127.0.0.1:3000/api/books \
  -H 'Content-Type: application/json' \
  -d '{"title":" The Odyssey "}'

Expect 201 Created. Copy the path from the Location header and request it from the same server. For example, if the header reads /api/books/abc, request http://127.0.0.1:3000/api/books/abc. The body contains the generated ID and the trimmed title.

4. Check two distinct failures ​

SendExpected responseWhich component answered
POST /api/books with {"title":" "}400 with key: "title"Validation middleware
GET /api/books/missing404 with {"error":"Book not found"}The controller after a successful route match

Restarting the process clears the map. To add durable storage, replace the store with a provider that owns the connection and disposes it on shutdown. To verify the HTTP contract before changing the implementation, run the catalog test.

To let clients explore these operations, serve the catalog's OpenAPI document and Swagger UI.

Released under the MIT License.