Skip to content

defineResource

defineResource(name, options) declares a typed public response shape with a field allowlist. Used by HTTP handlers to project internal records into safe-to-ship payloads; consumed by the OpenAPI generator for response schemas.

Signature

ts
import { defineResource } from "@nwire/handler";

function defineResource<TSchema extends ZodTypeAny, TPublic extends keyof z.infer<TSchema>>(
  name: string,
  options: {
    schema: TSchema;
    public?: readonly TPublic[];
  },
): ResourceDefinition<TSchema, TPublic>;

Example

ts
import { defineResource } from "@nwire/handler";
import { z } from "zod";

export const User = defineResource("User", {
  schema: z.object({
    id:           z.string(),
    email:        z.string().email(),
    name:         z.string(),
    createdAt:    z.string().datetime(),
    passwordHash: z.string(),
    deletedAt:    z.string().datetime().nullable(),
  }),
  public: ["id", "email", "name", "createdAt"],
});

Returned API

  • User.project(record) — return only the public fields. Throws in dev if record is missing one of them.
  • User.list(rows) — projects each row + wraps in { items, total }.
  • User.schema — the original Zod schema.
  • User.publicSchema — the projected Zod schema (subset of fields).

In a handler

ts
.wire(
  get("/users/:id", { params: z.object({ id: z.string() }) }),
  async ({ input, resolve }) => {
    const row = await resolve<UserStore>("users").get(input.id);
    return User.project(row);
  },
)

The response body contains only id, email, name, createdAt. The OpenAPI operation's 200 response schema reflects the projection — clients codegenning against the spec see only public fields.

See also

MIT licensed.