Reference
newt add use-case
Adds a use case to a module, with its schema and its test.
newt add use-case adds one thing a module does, such as completing a task. It writes a method that reads the entity by its id, saves it and returns it, ready for you to fill in.
newt add use-case <context>/<module> <use-case> [options]Arguments
Section titled “Arguments”| Argument | Meaning |
|---|---|
context/module |
A module of the backend, as in tasks/task |
use-case |
The use case’s name, as in complete-task |
Options
Section titled “Options”| Option | Default | Meaning |
|---|---|---|
--backend <folder> |
the one you are in | The backend, in a monorepo with several |
It also takes the global flags.
Name rules
Section titled “Name rules”- Lowercase letters and digits, words joined by
-, starting with a letter:complete-taskbecomes the methodcompleteTask. - Not
find,get,paginateorsearch: newt’s lint shapes those reads. - Not
name,useCaseRunner,on,depsorevents, which every module has, nor a word JavaScript keeps. - Not a name the module already has as a member, or whose schema (
TaskCompleteTaskSchema,TaskCompleteTaskDTO) is already in<module>.schema.ts.
What it writes
Section titled “What it writes”newt add use-case tasks/task complete-task updated src/contexts/tasks/modules/task/task.schema.ts updated src/contexts/tasks/modules/task/task.module.ts updated src/contexts/tasks/modules/task/task.module.test.ts
Next steps: change the task by a method of its entity, in task.ts, and call it before persist in completeTask bun test src/contexts/tasks/modules/taskThe schema and the method it adds:
export const TaskCompleteTaskSchema = TaskSchema.pick({ id: true })export type TaskCompleteTaskDTO = z.input<typeof TaskCompleteTaskSchema> @UseCase() async completeTask(input: TaskCompleteTaskDTO): Promise<TaskDTO> { const { id } = TaskCompleteTaskSchema.parse(input) const [task] = await this.tasks.find( TaskFilter.toCriteria<TaskRow>({ id }), { limit: 1 }, ) if (!task) { throw new TaskNotFound() } await this.tasks.persist(task) return task.toDTO() }The test checks that the use case reads the task by its id and returns it. Running the command again for the same use case changes nothing.
Next steps
Section titled “Next steps”- Change the entity with a method of its own, in
<module>.ts, and call it beforepersist. bun test src/contexts/<context>/modules/<module>
Errors
Section titled “Errors”- Missing arguments:
newt add use-case takes the module and the use case, as in newt add use-case sales/order mark-paid. - A context or module that is not there: refused, naming the command that adds it.
- A read’s name (
find,get,paginate,search): refused; name the use case by what it does. - A name the module already uses: refused.
See Use cases.