Builders Academy
Clean Architecture avec Node.js
4 of 5

Chapitre 2 · Leçon 1

Persistence Mapper

La frontière entre domaine et base de données

Section 1

Pourquoi un mapper dédié ?

Step 1

Le problème

Si tes entités TypeORM sont aussi tes entités domaine, tu ne peux plus modifier le schéma DB sans risquer de casser la logique métier. Le mapper crée une frontière dure entre les deux mondes.

TutorialPersistenceMapper.ts

typescript
1export class TutorialPersistenceMapper {
2  // TypeORM Entity → Domain Entity (rich model)
3  static toDomain(entity: TutorialEntity): Tutorial {
4    return Tutorial.create({
5      id: entity.id,
6      slug: entity.slug,
7      level: entity.level as DifficultyLevelValue,
8      chapters: (entity.chapters ?? []).map(
9        (c) => this.chapterToDomain(c)
10      ),
11      // ...
12    });
13  }
14
15  // Domain Entity → TypeORM Partial (pour save)
16  static toEntity(domain: Tutorial): Partial<TutorialEntity> {
17    return {
18      id: domain.id,
19      slug: domain.slug,
20      level: domain.level,
21      // Jamais de méthodes domaine ici
22    };
23  }
24}

TutorialPersistenceMapper.ts

typescript
1export class TutorialPersistenceMapper {
2  // TypeORM Entity → Domain Entity (rich model)
3  static toDomain(entity: TutorialEntity): Tutorial {
4    return Tutorial.create({
5      id: entity.id,
6      slug: entity.slug,
7      level: entity.level as DifficultyLevelValue,
8      chapters: (entity.chapters ?? []).map(
9        (c) => this.chapterToDomain(c)
10      ),
11      // ...
12    });
13  }
14
15  // Domain Entity → TypeORM Partial (pour save)
16  static toEntity(domain: Tutorial): Partial<TutorialEntity> {
17    return {
18      id: domain.id,
19      slug: domain.slug,
20      level: domain.level,
21      // Jamais de méthodes domaine ici
22    };
23  }
24}

Topics and skills covered

  • TypeORM
  • Mapping
  • Repository Pattern