Exercise: tRPC
by Tomas Trescak· APIs

0 / 1590 XP
The external project has not been reviewed yet
Please follow instructions below to submit your project

Instructions

In this assignment, you’ll build a task management API using tRPC, a modern, type-safe alternative to traditional REST APIs, integrated with Next.js App Router. You’ll create a simple app where users can list, retrieve, create, update, and delete tasks—think of it as a to-do list with a twist! The goal is to understand how tRPC simplifies API development by leveraging TypeScript’s power, all while exploring Next.js’s latest routing system. You will continue wuth the same structure as in the Express and REST router!

Fork and clone the repository for this exercise at:

https://github.com/WesternSydneyUniversity/comp3036-apis-trpc

Try to pass all the tests!

Scenario

Imagine you’re developing a task management app for students. Users can view their tasks (e.g., “Complete the project report”), mark them as done, add new ones, or remove old ones. With a REST API, you’d define endpoints like GET /tasks or POST /tasks, juggling HTTP requests and responses. tRPC changes the game: it lets you write backend procedures and call them like regular functions from the frontend, with full type safety. Your job is to implement these procedures using tRPC!

Objectives

  • Learn how tRPC differs from REST and why it’s useful.
  • Implement a set of tRPC procedures to manage tasks in a Next.js app.
  • Use TypeScript to ensure type safety across the app.
  • Test your implementation with provided unit tests using Vitest.
  • Explore Next.js App Router for modern routing and server-client integration.

Repository Structure

The repository provides a skeleton project with everything set up except the core tRPC logic. Here’s what you’ll find:

  • <strong>src/app/</strong>: Contains the Next.js App Router setup.
    • api/trpc/[trpc]/route.ts: The tRPC route handler (pre-configured).
    • page.tsx: A client-side React component to interact with your API.
    • layout.tsx: The root layout with tRPC and React Query providers.
  • <strong>src/server/</strong>:
    • context.ts: Defines the tRPC context (pre-configured).
    • router.ts: The tRPC router file where you’ll write your solution.
  • <strong>src/utils/trpc.ts</strong>: tRPC client setup (pre-configured).
  • <strong>src/types/task.ts</strong>: Type definition for a Task (id, description, completed).
  • <strong>tests/router.test.ts</strong>: Unit tests to verify your implementation.
  • <strong>package.json</strong>, <strong>tsconfig.json</strong>, <strong>vitest.config.ts</strong>: Project configuration files.

Task Requirements

Your task is to complete the src/server/router.ts file by implementing five tRPC procedures to manage an in-memory task list. The procedures should match the following specifications:

  1. <strong>getTasks</strong>:
    • Type: Query
    • Input: None
    • Output: Returns an array of all tasks.
    • Purpose: List all tasks in the store.
  2. <strong>getTaskById</strong>:
    • Type: Query
    • Input: A task ID (number).
    • Output: Returns a single task matching the ID or throws an error if not found.
    • Purpose: Retrieve a specific task.
  3. <strong>createTask</strong>:
    • Type: Mutation
    • Input: An object with description (string) and optional completed (boolean, defaults to false).
    • Output: Returns the newly created task.
    • Purpose: Add a new task to the list.
  4. <strong>updateTask</strong>:
    • Type: Mutation
    • Input: An object with id (number), description (string), and completed (boolean).
    • Output: Returns the updated task or throws an error if not found.
    • Purpose: Modify an existing task.
  5. <strong>deleteTask</strong>:
    • Type: Mutation
    • Input: A task ID (number).
    • Output: Returns { message: 'Task deleted' } or throws an error if not found.
    • Purpose: Remove a task from the list.

Initial Setup

  • The task store starts with two tasks:

    let tasks: Task[] = [
      { id: 1, description: 'Complete the project report', completed: false },
      { id: 2, description: 'Clean the house', completed: true },
    ];
  • Use this in-memory array to store tasks (no database required).

Guidelines

  • Use TypeScript: Define types and use Zod for input validation (e.g., z.number(), z.string()).
  • Follow tRPC Syntax: Use t.procedure.query() for queries and t.procedure.mutation() for mutations.
  • Handle Errors: Throw errors (e.g., throw new Error('Task not found')) when tasks aren’t found.
  • Keep It Simple: Focus on functionality—no need for authentication or complex logic.

Getting Started

  1. Fork the Repository

    https://github.com/WesternSydneyUniversity/comp3036-apis-trpc

    Clone the Repository:

    git clone <your forked url>
    cd <your local folder>
  2. Install Dependencies:

    pnpm install
  3. Run the App:

    pnpm run dev

    Open http://localhost:3000 to see the the failing UI.

  4. Run Tests:

    pnpm test

    Use this to check if your implementation works (all tests should pass once completed).

Testing Your Work

The tests/router.test.ts file includes Vitest unit tests for all five procedures. They’ll check:

  • Listing all tasks.
  • Retrieving a task by ID (including error cases).
  • Creating a new task.
  • Updating an existing task.
  • Deleting a task.

Run pnpm run test:watch to see live feedback as you code!

Tips

  • Start with getTasks—it’s the simplest.
  • Use the provided Task type from src/types/task.ts.
  • Check the client code in page.tsx to see how your procedures are called.
  • If stuck, review the tRPC docs: https://trpc.io/docs.

Submission

  • Complete router.ts with your solution.
  • Ensure all tests pass.
  • Push your changes to a personal GitHub repository or submit as instructed by your lecturer.

Why This Matters

By the end, you’ll see how tRPC eliminates the hassle of REST endpoints and keeps your app type-safe. This skill is gold in modern web development—think faster builds, fewer bugs, and happier teams. Ready to dive in? Let’s make this task app awesome!

Maggie

Discuss with Maggie
Use the power of generative AI to interact with course content

Maggie is a generative AI that can help you understand the course content better. You can ask her questions about the lecture, and she will try to answer them. You can also see the questions asked by other students and her responses.

Discuss with Others
Ask questions, share your thoughts, and discuss with other learners

Join the discussion to ask questions, share your thoughts, and discuss with other learners
Setup
React Fundamentals
10 points
Next.js
10 points
Advanced React
Databases
10 points
React Hooks
Authentication and Authorisation
10 points
APIs
CI/CD and DevOps
Testing React
Advanced Topics