Skip to main content

Lesson 6 of 7

Mini Project: Task Manager - Part 10 (Full Validation Pipeline)

Wire together the full validation pipeline - Zod schemas for request DTOs, typed response DTOs with mappers, custom error hierarchy in Express, the Result type for service methods, and a complete CRUD controller with zero `any`.

17 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Task Manager Part 10 - Production Validation Pipeline

Task Manager Part 10 - Production Validation Pipeline
// src/schemas/task.schema.ts - single source of truth ────────
import { z } from "zod";

export const PrioritySchema   = z.enum(["low","medium","high","critical"]);
export const TaskStatusSchema = z.enum(["todo","in-progress","done","archived"]);

export const CreateTaskSchema = z.object({
  title:       z.string().min(1, "Title is required").max(200),
  priority:    PrioritySchema.default("medium"),
  description: z.string().max(5_000).optional(),
  dueDate:     z.string().datetime({ message: "dueDate must be an ISO 8601 datetime" })
                .optional()
                .transform((v) => (v ? new Date(v) : undefined)),
  tags:        z.array(z.string().min(1).max(50)).max(10).default([]),
});

export const UpdateTaskSchema = CreateTaskSchema.partial().extend({
  status: TaskStatusSchema.optional(),
});

export type CreateTaskDTO = z.infer<typeof CreateTaskSchema>;
export type UpdateTaskDTO = z.infer<typeof UpdateTaskSchema>;

// src/dtos/task.dto.ts - response mapper ──────────────────────
export interface TaskResponseDTO {
  id:          number;
  title:       string;
  description: string | null;
  status:      string;
  priority:    string;
  tags:        string[];
  createdAt:   string;
  updatedAt:   string;
  dueDate:     string | null;
}

export function toTaskDTO(task: Task): TaskResponseDTO {
  return {
    id:          task.id,
    title:       task.title,
    description: task.description,
    status:      task.status,
    priority:    task.priority,
    tags:        [...task.tags],
    createdAt:   task.createdAt.toISOString(),
    updatedAt:   task.updatedAt.toISOString(),
    dueDate:     task.dueDate?.toISOString() ?? null,
  };
}

// src/services/taskService.ts - Result-returning methods ────────
export class TaskService {
  constructor(private readonly repo: ITaskRepository) {}

  async findById(id: number): Promise<Result<Task, NotFoundError>> {
    const task = await this.repo.findById(id);
    return task ? ok(task) : fail(new NotFoundError("Task", id));
  }

  async create(input: CreateTaskDTO): Promise<Result<Task, ConflictError>> {
    const existing = await this.repo.findByTitle(input.title);
    if (existing) return fail(new ConflictError(`Task "${input.title}" already exists`));
    const task = await this.repo.save({
      id: Date.now(), ...input,
      description: input.description ?? null,
      dueDate: input.dueDate ?? null,
      status: "todo",
      assignee: null,
      createdAt: new Date(),
      updatedAt: new Date(),
    } as Task);
    return ok(task);
  }
}

// src/controllers/taskController.ts - clean controller ─────────
export class TaskController {
  constructor(private readonly service: TaskService) {}

  getById = async (req: Request<{ id: string }>, res: Response, next: NextFunction): Promise<void> => {
    const id = parseInt(req.params.id, 10);
    if (isNaN(id)) { res.status(400).json({ error: "INVALID_ID", message: "id must be a number" }); return; }

    const result = await this.service.findById(id);
    if (!result.ok) { next(result.error); return; }
    res.json(toTaskDTO(result.value));
  };

  create = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    const parsed = CreateTaskSchema.safeParse(req.body);
    if (!parsed.success) {
      res.status(400).json({ error: "VALIDATION_ERROR", fields: parsed.error.flatten().fieldErrors });
      return;
    }
    const result = await this.service.create(parsed.data);
    if (!result.ok) { next(result.error); return; }
    res.status(201).json(toTaskDTO(result.value));
  };
}

Common Mistakes

  • Validating in the controller AND the service - validation should happen once at the entry point (controller/middleware). Services trust their inputs are already valid.
  • Exposing internal IDs or relationships in DTOs without intent - the DTO mapper is the last chance to hide internal fields. Audit every field before adding it to the response DTO.
  • Not consistent Result vs throw in one codebase - choose one paradigm per layer and stick with it. Services can return Result; infrastructure (DB adapter) can throw. Don't mix Result and throw arbitrarily.

Tip

Tip

Practice Mini Project Task Manager Part 10 Full Validation Pipeline in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Task Manager - Part 10 (Full Validation Pipeline)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Task Manager Part 10 Full Validation Pipeline from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Task Manager Part 10 Full Validation Pipeline is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • Wire together the full validation pipeline - Zod schemas for request DTOs, typed response DTOs with mappers, custom error hierarchy in Express, the Result type for service methods, and a complete CRUD controller with zero `any`.
  • Validating in the controller AND the service - validation should happen once at the entry point (controller/middleware). Services trust their inputs are already valid.
  • Exposing internal IDs or relationships in DTOs without intent - the DTO mapper is the last chance to hide internal fields. Audit every field before adding it to the response DTO.
  • Not consistent Result vs throw in one codebase - choose one paradigm per layer and stick with it. Services can return Result; infrastructure (DB adapter) can throw. Don't mix Result and throw arbitrarily.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done