Clean Architecture: Typescript and React
Photo by FELIPE RIBEIRO from Pexels

Clean Architecture: Typescript and React

By employing clean architecture, you can design applications with very low coupling and independent of technical implementation details, such as databases and frameworks. That way, the application becomes easy to maintain and flexible to change. It also becomes intrinsically testable. Here I’ll show how I structure my clean architecture projects. This time we are going to build a React todo application using Typescript.

The folder/group structure of the project takes on the following form:

├── Core 
├── Data 
├── Domain 
└── Presentation

Let’s start with the Domain Layer.

This layer describes WHAT your project/application does. Let me explain, Many applications are built and structured in a way that you cannot understand what the application does by merely looking at the folder structure. Using a building of a house analogy, you can quickly identify what a building would look like and its functionality by viewing the floor plan and elevation of the building

Floor Plan

In the same way, the domain layer of our project should specify and describe WHAT our application does. In this folder, we would use models, repository interfaces, and use cases.

├── Core
├── Data
├── Presentation
└── Domain
    ├── Model
    │   ├── Todo.ts
    │   └── User.ts
    ├── Repository
    │   ├── TodoRepository.ts
    │   └── UserRepository.ts
    └── UseCase
        ├── Todo
        │   ├── GetTodos.ts
        │   ├── GetTodo.ts
        │   ├── DeleteTodo.ts
        │   ├── UpdateTodo.ts
        │   └── CreateTodo.ts
        └── User
            ├── GetUsers.ts
            ├── GetUser.ts
            ├── DeleteUser.ts
            ├── UpdateUser.ts
            └── CreateUser.ts
  1. Model: A model typically represents a real-world object that is related to the problem. In this folder, we would typically keep classes to represent objects. e.g. Todo, User, Product, etc
  2. Repository: Container for all repository interfaces. The repository is a central place to keep all model-specific operations. In this case, the Todo repository interface would describe repository methods. The actual repository implementation will be kept in the Data layer.
  3. UseCases: Container to list all functionality of our application. e.g Get Todos, Delete Todo, Create Todo, Update Todo

The PRESENTATION layer will keep all the consumer-related code as to HOW the application will interact with the outside world. The presentation layer can be WebForms, Command Line Interface, API Endpoints, etc. In this case, it would be the screens for a List of Todos and its accompanying view model.

├── Core
├── Data
├── Domain
└── Presentation
    └── Todo
        └── TodoList
            ├── TodoListViewModel.tsx
            └── TodoListView.tsx

The DATA layer will keep all the external dependency-related code as to HOW they are implemented:

├── Core
├── Domain
├── Presentation
└── Data
    ├── Repository
    │   ├── TodoRepositoryImpl.ts
    └── DataSource
        ├── TodoDataSource.ts
        ├── API
        │   ├── TodoAPIDataSourceImpl.ts
        │   └── Entity
        │       ├── TodoAPIEntity.ts
        │       └── UserAPIEntity.ts
        └── DB
            ├── TodoDBDataSourceImpl.ts
            └── Entity
                ├── TodoDBEntity.ts
                └── UserDBEntity.ts
  1. Repository: Repository implementations
  2. DataSource: All data source interfaces and entities. An entity represents a single instance of your domain object saved into the database as a record. It has some attributes that we represent as columns in our DB tables or API endpoints. We can’t control how data is modeled on the external data source, so these entities are required to be mapped from entities to domain models in the implementations

And lastly, the CORE layer keep all the components that are common across all layers like constants or configs or dependency injection (which we won’t cover) Our first task would be always to start with the domain models and data entities. Let’s start with the model

1export interface Todo { 2 id: number; 3 title: string; 4 isComplete: boolean; 5}

We need it to conform to Identifiable as we’re going to display these items in a list view.

Next, let’s do the todo entity

1export interface TodoAPIEntity { 2 id: number; 3 title: string; 4 completed: boolean; 5}

Let’s now write an interface for the TodoDatasource

1import { Todo } from "../../Domain/Model/Todo"; 2 3export default interface TodoDataSource { 4 getTodos(): Promise<Todo[]>; 5}

We have enough to write an implementation of this interface and we’ll call it TodoAPIImpl:

1import { Todo } from "../../../Domain/Model/Todo"; 2import TodoDataSource from "../TodoDataSource"; 3import { TodoAPIEntity } from "./Entity/TodoAPIEntity"; 4 5const BASE_URL = "https://jsonplaceholder.typicode.com"; 6 7interface TypedResponse<T = any> extends Response { 8 json<P = T>(): Promise<P>; 9} 10 11function myFetch<T>(...args: any): Promise<TypedResponse<T>> { 12 return fetch.apply(window, args); 13} 14 15export default class TodoAPIDataSourceImpl implements TodoDataSource { 16 async getTodos(): Promise<Todo[]> { 17 let response = await myFetch<TodoAPIEntity[]>(`${BASE_URL}/todos`); 18 let data = await response.json(); 19 return data.map((item) => ({ 20 id: item.id, 21 title: item.title, 22 isComplete: item.completed, 23 })); 24 } 25}

Note: this data source’s getTodos function returns a list of Todo. So, we have to map TodoEntity -> Todo: Before we write our TodoRepositoryImpl let’s write the interface for that in the Domain layer

1import { Todo } from "../Model/Todo"; 2 3export interface TodoRepository { 4 getTodos(): Promise<Todo[]>; 5}

Now that we have our todo repository, we can code up the GetTodos use case

1import { Todo } from "../../Domain/Model/Todo"; 2import { TodoRepository } from "../../Domain/Repository/TodoRepository"; 3import TodoDataSource from "../DataSource/TodoDataSource"; 4 5export class TodoRepositoryImpl implements TodoRepository { 6 dataSource: TodoDataSource; 7 8 constructor(_datasource: TodoDataSource) { 9 this.dataSource = _datasource; 10 } 11 12 async getTodos(): Promise<Todo[]> { 13 return this.dataSource.getTodos(); 14 } 15}

and then in turn we can write our presentation’s view model and view

1import { useState } from "react"; 2import TodoAPIDataSourceImpl from "../../../Data/DataSource/API/TodoAPIDataSourceImpl"; 3import { TodoRepositoryImpl } from "../../../Data/Repository/TodoRepositoryImpl"; 4import { Todo } from "../../../Domain/Model/Todo"; 5import { GetTodosUseCase } from "../../../Domain/UseCase/GetTodos"; 6 7export default function TodoListViewModel() { 8 const [todos, setTodos] = useState<Todo[]>([]); 9 10 const UseCase = new GetTodosUseCase( 11 new TodoRepositoryImpl(new TodoAPIDataSourceImpl()) 12 ); 13 14 async function getTodos() { 15 setTodos(await UseCase.invoke()); 16 } 17 18 return { 19 getTodos, 20 todos, 21 }; 22}
1import { useEffect } from "react"; 2import useViewModel from "./TodoListViewModel"; 3import { 4 List, 5 ListItem, 6 ListItemIcon, 7 Checkbox, 8 ListItemText, 9} from "@mui/material"; 10 11export default function TodoListView() { 12 const { getTodos, todos } = useViewModel(); 13 14 useEffect(() => { 15 getTodos(); 16 }, []); 17 18 return ( 19 <List> 20 {todos.map((todo, i) => { 21 return ( 22 <ListItem key={i}> 23 <ListItemIcon> 24 <Checkbox checked={todo.isComplete} /> 25 </ListItemIcon> 26 <ListItemText primary={todo.title} /> 27 </ListItem> 28 ); 29 })} 30 </List> 31 ); 32}

result

So to recap:

recap

GitHub Repo: Here