@marasuchus/domain
v4.0.0
Published
Domain types and helpers: Result, Zod validation and pagination
Readme
@marasuchus/domain
Domain types and helpers, published as a public package on npmjs.com. ESM only, types included.
Installation
pnpm add @marasuchus/domainzod is an optional peer: install it only if you use ./validation (see
table below).
Modules
Each module is imported via subpath, with no barrel loading everything:
import { Result } from "@marasuchus/domain/result";| Subpath | Status | Required peers |
| -------------- | ----------- | -------------- |
| ./result | implemented | none |
| ./pagination | implemented | none |
| ./validation | implemented | zod |
result
Result<T, E> models success or failure without throwing exceptions.
DomainError is the union of ValidationError and NotFoundError.
import { Result } from "@marasuchus/domain/result";
const found = Result.ok(user);
const missing = Result.notFound("User not found", "User", id);
const invalid = Result.validation("Invalid input", { email: "Invalid email" });
if (!found.ok) {
// found.error: DomainError
}Result.err builds an arbitrary error when the E type is not DomainError.
pagination
Base types for paginated listings, plus the constant SortDirection derives
from.
import {
SORT_DIRECTION,
type BaseQuery,
type PaginatedResult,
type SortDirection,
} from "@marasuchus/domain/pagination";
const page: PaginatedResult<{ id: number }> = {
data: [{ id: 1 }],
count: 42,
page: 2,
pageSize: 15,
pageCount: 3,
};validation
zod schemas and helpers for query params and forms: they all tolerate
null, undefined, and empty strings (returning undefined or a default
instead of failing).
sortDirSchema/sortDirDescSchema:"asc" | "desc", defaulting to"asc"/"desc"on invalid input.optionalPositiveInt,optionalInt,optionalNumber: coerce strings to numbers;undefinedwhen there is no value or it is invalid.optionalTrue: onlytrue,"true", or"1"returntrue; everything else isundefined(useful for checkboxes).optionalDateOnly: acceptsYYYY-MM-DDonly.optionalTextFilter: trim + 255 character max.parseFormBoolean(value, fallback): parses"true"/"1"and"false"/"0", falling back tofallbackfor anything else.createPaginatedQuerySchema(sortOptions, defaultSortBy, defaultSortDir, { defaultPageSize, maxPageSize }): validapage(default1),pageSize(clamped amaxPageSize, default adefaultPageSize),sortByysortDircon sus defaults.
import {
createPaginatedQuerySchema,
optionalPositiveInt,
sortDirSchema,
} from "@marasuchus/domain/validation";
const querySchema = createPaginatedQuerySchema(
["name", "createdAt"] as const,
"name",
"asc",
{
defaultPageSize: 15,
maxPageSize: 100,
},
);License
MIT — see LICENSE.
