Concepts
Value objects
Values with rules, such as an id or an email, checked once where they are made.
A value object is a value with rules, such as a task’s id, an email or a priority. It is a plain string or number with a type that says what it is, made only by a function that checks it.
A function that takes a TaskId cannot get a project’s id or a random string by mistake. TypeScript refuses it, and the value was already checked where it was made.
A value object
Section titled “A value object”import { defineValueObject } from '@newt-js/core'import { z } from 'zod'// --------------------------------------------------------import { InvalidPriority } from '../errors/invalid-priority'
export const Priority = defineValueObject( z.string().trim().min(1).max(100).brand<'Priority'>(), text => new InvalidPriority(text),)export type Priority = z.output<typeof Priority.schema>Priority.from(' A-1 ') // 'A-1', typed PriorityPriority.from(' ') // throws InvalidPriorityPriority.tryFrom(' ') // undefinedAt run time a Priority is a string. The .brand<'Priority'>() only exists for TypeScript, so a plain string is not a Priority until from checked it.
Using one in a schema
Section titled “Using one in a schema”Put its schema in the module’s schema. The field then has the value object’s rules and type:
export const TaskSchema = z.object({ id: TaskId.schema, name: z.string().trim().min(1).max(100), priority: Priority.schema, createdAt: z.string(), updatedAt: z.string(),})TaskDTO['priority'] is now a Priority. Inside a schema, a bad value fails like any other zod check: HTTP answers 400 with the code validation. Only from throws your own error.
defineValueObject
Section titled “defineValueObject”defineValueObject(schema, invalid, extra?)| Argument | What it is |
|---|---|
schema |
A zod schema, usually ending in .brand<'Name'>(). |
invalid |
(input) => KnownError: the error from throws when the schema refuses the input. |
extra |
Optional. An object whose members are added to the result, such as generate(). |
It returns:
| Member | What it does |
|---|---|
schema |
The schema. Use it inside other schemas: id: TaskId.schema. |
from(input) |
Returns the checked value, or throws the error from invalid. |
tryFrom(input) |
Returns the checked value, or undefined. |
Ids: uuidFactory and Uuid
Section titled “Ids: uuidFactory and Uuid”Every module gets an id type of its own:
import type { Uuid } from '@newt-js/core'import { uuidFactory } from '@newt-js/core'
export const TaskId = uuidFactory('TaskId')export type TaskId = Uuid<'TaskId'>uuidFactory(name) makes a value object for UUID v7 strings, with one extra member:
TaskId.generate()returns a new UUID v7, typedTaskId.TaskId.from(text)refuses anything that is not a UUID v7, withInvalidUuid(codeinvalid_uuid).
Routes turn the path’s text into an id before giving it to a use case in a DTO:
router.post('/tasks/:id/complete-task', async request => Response.json( await tasks.completeTask({ id: TaskId.from(request.params.id) }), ),)Uuid itself is a ready-made uuidFactory('Uuid') for an id of no particular kind.
Built-in value objects
Section titled “Built-in value objects”@newt-js/core ships these. Each one except EventId also has a factory (emailFactory(), keyFactory(name, pattern?) and so on) that makes a new one with the same rules.
| Value object | What it is for | Error and code |
|---|---|---|
Email |
An email address. | InvalidEmail, invalid_email |
Key |
A short name made by a program. | InvalidKey, invalid_key |
SearchText |
The text a user types in a search box. | InvalidSearchText, invalid_search_text |
SecretToken |
A random secret, as a sign-in token. | InvalidSecretToken, invalid_secret_token |
Uuid |
An id of no particular kind. | InvalidUuid, invalid_uuid |
EventId |
The id of a published event. | InvalidUuid, invalid_uuid |
Their rules:
Emailtrims the text, lowers its case, and checks it is an email of at most 254 characters.Keytakes 1 to 200 letters, digits,.,_,:or-.keyFactory('Slug', /^[a-z0-9-]+$/)makes a key type with your own pattern.SearchTexttrims the text and takes at most 100 characters. An empty text is valid. Use it as thetextof asearch(text, page)use case.SecretTokenis 43 characters of base64url.SecretToken.generate()makes one from 32 random bytes, andSecretToken.hash(token)returns its SHA-256 in hex.EventIdis auuidFactory('EventId'): the id every event gets when it is published.
With the CLI
Section titled “With the CLI”newt add value-object tasks/task priorityIt writes value-objects/priority.ts, its error errors/invalid-priority.ts (a ValidationError with the code task.invalid_priority) and a test. Edit the schema to say what a priority is. See newt add value-object.