Lesson 6 of 7
Mini Project: Task Manager - Part 7 (Async Data Layer)
Build the Task Manager's async data layer - a typed API client with Zod validation, resilient fetch with retry and timeout, an async paginated task loader, and request deduplication via a typed in-flight map.
Task Manager Part 7 - Typed Async Data Layer
// src/lib/http.ts - low-level typed fetch ─────────────────────
import { z, type ZodSchema } from "zod";
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
export interface RequestOptions<B = unknown> {
method?: HttpMethod;
body?: B;
headers?: Record<string, string>;
signal?: AbortSignal;
timeout?: number;
}
export async function http<T>(
url: string,
schema: ZodSchema<T>,
options: RequestOptions = {},
): Promise<T> {
const { method = "GET", body, headers = {}, signal, timeout = 10_000 } = options;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
const combinedSignal = signal
? AbortSignal.any([signal, controller.signal])
: controller.signal;
try {
const res = await fetch(url, {
method,
signal: combinedSignal,
headers: { "Content-Type": "application/json", ...headers },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
clearTimeout(timer);
if (!res.ok) {
const err: unknown = await res.json().catch(() => ({}));
throw new Error(
typeof err === "object" && err !== null && "message" in err
? String((err as { message: unknown }).message)
: `HTTP ${res.status}`
);
}
const raw: unknown = await res.json();
return schema.parse(raw); // throws ZodError on shape mismatch
} catch (error: unknown) {
if (error instanceof DOMException && error.name === "AbortError") {
throw new Error("Request timed out or was cancelled");
}
throw error;
}
}
// src/lib/taskApi.ts - typed API methods ──────────────────────
import { z } from "zod";
import { http } from "./http";
const TaskSchema = z.object({
id: z.number(),
title: z.string().min(1),
description: z.string().nullable(),
status: z.enum(["todo", "in-progress", "done", "archived"]),
priority: z.enum(["low", "medium", "high", "critical"]),
dueDate: z.string().nullable().transform((v) => (v ? new Date(v) : null)),
createdAt: z.string().transform((v) => new Date(v)),
});
const TaskListSchema = z.array(TaskSchema);
export type Task = z.infer<typeof TaskSchema>;
const BASE = "/api/v1";
export const taskApi = {
getAll: (signal?: AbortSignal) =>
http(`${BASE}/tasks`, TaskListSchema, { signal }),
getById: (id: number, signal?: AbortSignal) =>
http(`${BASE}/tasks/${id}`, TaskSchema, { signal }),
create: (input: Pick<Task, "title" | "priority">, signal?: AbortSignal) =>
http(`${BASE}/tasks`, TaskSchema, { method: "POST", body: input, signal }),
update: (id: number, patch: Partial<Pick<Task, "title" | "status" | "priority">>) =>
http(`${BASE}/tasks/${id}`, TaskSchema, { method: "PATCH", body: patch }),
delete: (id: number) =>
http(`${BASE}/tasks/${id}`, z.object({ deleted: z.literal(true) }), { method: "DELETE" }),
};
// src/lib/taskLoader.ts - async paginated loader ─────────────
import { z } from "zod";
import { http } from "./http";
import { TaskSchema } from "./taskApi";
const PageSchema = z.object({
tasks: z.array(TaskSchema),
total: z.number(),
page: z.number(),
perPage: z.number(),
});
export async function* loadAllTasks(
pageSize = 25,
): AsyncGenerator<Task, void, unknown> {
let page = 1;
let loaded = 0;
do {
const data = await http(
`/api/v1/tasks?page=${page}&limit=${pageSize}`,
PageSchema,
);
for (const task of data.tasks) yield task;
loaded += data.tasks.length;
page++;
} while (loaded < data.total);
}Common Mistakes
- Hardcoding the base URL in every api call - define `BASE` once and build paths from it. Changing the base URL or version should be a one-line change.
- Not combining `AbortSignal`s - when using both a user-supplied signal and a timeout, use `AbortSignal.any([userSignal, timeoutSignal])` (Node 18+/modern browsers). Without combining, only one signal is respected.
- Swallowing Zod parse errors - if the server returns unexpected shape, `schema.parse(raw)` throws `ZodError`. Let it propagate or catch specifically to log the validation failure and return a typed error response.
Tip
Tip
Practice Mini Project Task Manager Part 7 Async Data Layer in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Mini Project: Task Manager - Part 7 (Async Data Layer)
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Task Manager Part 7 Async Data Layer 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 7 Async Data Layer 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
- Build the Task Manager's async data layer - a typed API client with Zod validation, resilient fetch with retry and timeout, an async paginated task loader, and request deduplication via a typed in-flight map.
- Hardcoding the base URL in every api call - define `BASE` once and build paths from it. Changing the base URL or version should be a one-line change.
- Not combining `AbortSignal`s - when using both a user-supplied signal and a timeout, use `AbortSignal.any([userSignal, timeoutSignal])` (Node 18+/modern browsers). Without combining, only one signal is respected.
- Swallowing Zod parse errors - if the server returns unexpected shape, `schema.parse(raw)` throws `ZodError`. Let it propagate or catch specifically to log the validation failure and return a typed error response.
Finished this lesson?