À propos de ce cours
Objectifs du TP
- Modéliser un domaine réel avec des entités et des relations TypeORM.
- Gérer le schéma par migrations et les données de départ par un seeder.
- Écrire une recherche paginée, filtrée et triée.
- Protéger les règles métier par des transactions et des verrous.
- Traduire les erreurs de la base en réponses HTTP correctes.
- Publier le projet sur GitHub dès le départ, un commit par partie.
Durée: 6 h | Prérequis: chapitres 05 à 11 | Livrable: le dépôt api-bibliotheque avec l'étiquette v1.0.0.
Cinq tables, une relation plusieurs-à-plusieurs et les règles d'emprunt.
Cahier des charges
La bibliothèque du centre de formation veut informatiser son catalogue et ses prêts.
- Un livre a un ISBN unique de 13 chiffres, un titre, une année de publication, un nombre d'exemplaires (1 à 50) et un nombre d'exemplaires disponibles. Il a un seul auteur et une ou plusieurs catégories.
- Un auteur ne peut pas être supprimé s'il a des livres.
- Un adhérent (e-mail unique) peut être inactif : il ne peut alors plus emprunter.
- Un emprunt dure 14 jours. Un adhérent a au plus 3 emprunts en cours et ne peut pas emprunter deux fois le même livre en même temps. Deux adhérents ne doivent jamais pouvoir emprunter ensemble le dernier exemplaire.
- On ne peut pas réduire le nombre d'exemplaires d'un livre en dessous du nombre d'exemplaires empruntés, ni supprimer un livre qui a des emprunts en cours.
| Route | Rôle | Réponses |
|---|---|---|
GET /api/livres?page&limite&q&auteurId&categorie&disponible&tri&ordre | recherche paginée avec auteur et catégories | 200 ; 400 |
GET /api/livres/:id | un livre | 200 ; 404 |
POST /api/livres, PATCH /api/livres/:id, DELETE /api/livres/:id | CRUD | 201/200/204 ; 400 ; 404 ; 409 |
GET /api/auteurs, GET /api/auteurs/:id (avec livres), POST, DELETE | auteurs | 404 ; 409 si des livres |
POST /api/adherents, GET /api/adherents/:id/emprunts | adhérents et historique | 201 ; 404 ; 409 |
POST /api/emprunts | emprunter { livreId, adherentId } | 201 ; 404 ; 409 ; 422 |
PATCH /api/emprunts/:id/retour | rendre (indique s'il y a retard) | 200 ; 404 ; 409 |
GET /api/emprunts/en-retard, GET /api/emprunts/statistiques | suivi | 200 |
Partie 1 Projet, dépôt GitHub et base de données
nest new api-bibliotheque --package-manager npm --strict, dépôt GitHub publicapi-bibliotheque, premier push.npm install @nestjs/typeorm typeorm mysql2 @nestjs/config class-validator class-transformer @nestjs/mapped-types.- Créez la base
bibliotheque_devet un utilisateur dédié (leçon 11.1, activité 3). Créez.envet.env.example(ce dernier versionné). - Configurez
TypeOrmModule.forRootAsyncavecautoLoadEntities: trueetsynchronize: false. - Commit :
chore: configuration de la base de données.
Partie 2 Les entités et la migration initiale
- Écrivez les cinq entités et leurs relations (schéma ci-dessus). Attention aux colonnes
string | null(leçon 11.3) et aux optionsonDelete:RESTRICTpour l'auteur d'un livre. - Créez
src/data-source.tset les scripts npm de la leçon 11.8. npm run migration:generate --name=Initialisation, relisez le fichier, puisnpm run migration:run. Vérifiez les tables et les clés étrangères (SHOW CREATE TABLE livres).- Commit :
db: entités et migration initiale.
Partie 3 Le seeder
- Écrivez
src/seeds/seed.ts: 4 catégories, 4 auteurs (dont deux auteurs tunisiens), 6 livres, 3 adhérents dont un inactif. Tout dans une transaction, et rien si des livres existent déjà. - Lancez-le deux fois : la seconde exécution ne doit rien créer.
- Commit :
db: seeder des données de départ.
Partie 4 Auteurs, livres et recherche
- DTO de création et de modification des livres (l'ISBN ne se modifie pas), DTO de filtre (leçon 11.7).
LivresService.rechercher()avec le QueryBuilder : recherche dans le titre, filtres auteur, catégorie (le livre doit garder toutes ses catégories dans la réponse : utilisez une sous-requête), disponibilité, tri par liste blanche, pagination.- Création (auteur et catégories vérifiés), modification (recalcul de
disponiblessiexemplaireschange, 409 si impossible), suppression (409 si emprunts en cours). - Un filtre d'exception
@Catch(QueryFailedError)enregistré avecAPP_FILTERtraduitER_DUP_ENTRYetER_ROW_IS_REFERENCED_2en 409. - Commit :
feat: auteurs et livres.
Partie 5 Emprunts en transaction
EmpruntsService.emprunter()dansdataSource.transaction(), avec un verroupessimistic_writesur le livre. Vérifiez dans l'ordre : livre (404), adhérent (404), actif (422), nombre d'emprunts en cours (422), même livre déjà emprunté (409), exemplaire disponible (409). Puis décrémentezdisponibleset créez l'emprunt.rendre()dans une transaction : 409 si déjà rendu ; date de retour, incrément dedisponibles, indicateur de retard.enRetard()avecIsNull()etLessThan();statistiques()avec le QueryBuilder (3 livres les plus empruntés, valeurs converties en nombres).- Commit :
feat: emprunts et retours.
Partie 6 Tester, documenter et livrer
- Créez
requetes/bibliotheque.http(base ci-dessous) et complétez-le pour couvrir chaque règle du cahier des charges. - Pour tester les retards, modifiez à la main la date de retour prévue d'un emprunt dans la base (
UPDATE emprunts SET date_retour_prevue = '2026-10-31' WHERE id = 1). - README : installation (base,
.env,migration:run,seed), routes, règles métier, schéma des tables. npm run lint,npm run build, commitdocs: README et requêtes, push, étiquettev1.0.0.
@base = http://localhost:3000/api
### Recherche paginée, filtres et tri
GET {{base}}/livres?limite=2&tri=anneePublication
###
GET {{base}}/livres?categorie=Histoire&disponible=true
###
GET {{base}}/livres?q=mis
### Créer un auteur puis un livre
POST {{base}}/auteurs
Content-Type: application/json
{ "nom": "Camus", "prenom": "Albert", "nationalite": "française" }
###
POST {{base}}/livres
Content-Type: application/json
{ "isbn": "9782070360024", "titre": "L'Étranger", "anneePublication": 1942, "exemplaires": 2, "auteurId": 5, "categorieIds": [1] }
### Emprunter / rendre
POST {{base}}/emprunts
Content-Type: application/json
{ "livreId": 4, "adherentId": 1 }
###
PATCH {{base}}/emprunts/1/retour
### Retards et statistiques
GET {{base}}/emprunts/en-retard
###
GET {{base}}/emprunts/statistiques
Résultat attendu
Migration, seeder et requêtes exécutés avec la correction :
$ npm run build && npm run migration:generate --name=Initialisation
Migration src/migrations/1794728942669-Initialisation.ts has been generated successfully.
$ npm run build && npm run migration:run
0 migrations are already loaded in the database.
1 migrations were found in the source code.
1 migrations are new migrations must be executed.
Migration Initialisation1794728942669 has been executed successfully.
$ npm run seed
Seeder : 4 catégories, 4 auteurs, 6 livres, 3 adhérents
$ npm run seed (relancé)
Données déjà présentes : rien à faire
$ requêtes de test
GET /api/livres?limite=2&tri=anneePublication → 200 {"donnees":[{"id":4,"isbn":"9782253096337","titre":"Notre-Dame de Paris","anneePublication":1831,"exemplaires":1,"disponibles":1,"auteur":{"id":3,"nom":"Hugo","prenom":"Victor","nationalite":"française"},"auteurId":3,"categories":[{"id":1,"libelle":"Roman"}],"creeLe":"…"},{"id":3,"isbn":"9782070409228","titre":"Les Misérables","anneePublication":1862,"exemplaires":4,"disponibles":4,"auteur":{"id":3,"nom":"Hugo","prenom":"Victor","nationalite":"française"},"auteurId":3,"categories":[{"id":1,"libelle":"Roman"},{"id":3,"libelle":"Histoire"}],"creeLe":"…"}],"meta":{"total":6,"page":1,"limite":2,"pages":3}}
GET /api/livres?categorie=Histoire&disponible=true → 200 {"donnees":[{"id":5,"isbn":"9782253004226","titre":"Germinal","anneePublication":1885,"exemplaires":2,"disponibles":2,"auteur":{"id":4,"nom":"Zola","prenom":"Émile","nationalite":"française"},"auteurId":4,"categories":[{"id":3,"libelle":"Histoire"},{"id":1,"libelle":"Roman"}],"creeLe":"…"},{"id":3,"isbn":"9782070409228","titre":"Les Misérables","anneePublication":1862,"exemplaires":4,"disponibles":4,"auteur":{"id":3,"nom":"Hugo","prenom":"Victor","nationalite":"française"},"auteurId":3,"categories":[{"id":3,"libelle":"Histoire"},{"id":1,"libelle":"Roman"}],"creeLe":"…"}],"meta":{"total":2,"page":1,"limite":10,"pages":1}}
GET /api/livres?q=mis → 200 {"donnees":[{"id":3,"isbn":"9782070409228","titre":"Les Misérables","anneePublication":1862,"exemplaires":4,"disponibles":4,"auteur":{"id":3,"nom":"Hugo","prenom":"Victor","nationalite":"française"},"auteurId":3,"categories":[{"id":1,"libelle":"Roman"},{"id":3,"libelle":"Histoire"}],"creeLe":"…"}],"meta":{"total":1,"page":1,"limite":10,"pages":1}}
POST /api/livres → 404 {"message":"Auteur 99 introuvable","error":"Not Found","statusCode":404}
POST /api/auteurs → 201 {"id":5,"nom":"Camus","prenom":"Albert","nationalite":"française"}
POST /api/livres → 201 {"id":7,"isbn":"9782070360024","titre":"L'Étranger","anneePublication":1942,"exemplaires":2,"disponibles":2,"auteurId":5,"categories":[{"id":1,"libelle":"Roman"}],"creeLe":"…"}
POST /api/livres → 409 {"statusCode":409,"message":"Cette valeur existe déjà (champ unique)"}
POST /api/livres → 400 {"message":["L'ISBN doit contenir 13 chiffres","titre must be longer than or equal to 1 characters","anneePublication must not be greater than 2026","exemplaires must not be less than 1","All categorieIds's elements must be unique"],"error":"Bad Request","statusCode":400}
POST /api/emprunts → 201 {"id":1,"livre":"Notre-Dame de Paris","adherent":"Sami Ben Ali","dateRetourPrevue":"2026-11-29"}
POST /api/emprunts → 409 {"message":"Aucun exemplaire disponible de « Notre-Dame de Paris »","error":"Conflict","statusCode":409}
POST /api/emprunts → 422 {"message":"Adhérent inactif","error":"Unprocessable Entity","statusCode":422}
POST /api/emprunts → 201 {"id":2,"livre":"Les Misérables","adherent":"Sami Ben Ali","dateRetourPrevue":"2026-11-29"}
POST /api/emprunts → 409 {"message":"Cet adhérent a déjà emprunté ce livre","error":"Conflict","statusCode":409}
POST /api/emprunts → 201 {"id":3,"livre":"Les Chants de la vie","adherent":"Sami Ben Ali","dateRetourPrevue":"2026-11-29"}
POST /api/emprunts → 422 {"message":"Limite atteinte : 3 emprunts en cours","error":"Unprocessable Entity","statusCode":422}
PATCH /api/livres/4 → 200 {"id":4,"isbn":"9782253096337","titre":"Notre-Dame de Paris","anneePublication":1831,"exemplaires":3,"disponibles":2,"auteur":{"id":3,"nom":"Hugo","prenom":"Victor","nationalite":"française"},"auteurId":3,"categories":[{"id":1,"libelle":"Roman"},{"id":3,"libelle":"Histoire"}],"creeLe":"…"}
DELETE /api/livres/4 → 409 {"message":"Le livre « Notre-Dame de Paris » a des emprunts en cours","error":"Conflict","statusCode":409}
DELETE /api/auteurs/3 → 409 {"statusCode":409,"message":"Suppression impossible : cet élément est utilisé ailleurs"}
GET /api/emprunts/en-retard → 200 [{"id":1,"livre":{"id":4,"isbn":"9782253096337","titre":"Notre-Dame de Paris","anneePublication":1831,"exemplaires":3,"disponibles":2,"auteurId":3,"creeLe":"…"},"adherent":{"id":1,"nom":"Ben Ali","prenom":"Sami","email":"sami@exemple.tn","actif":true},"dateEmprunt":"2026-10-17","dateRetourPrevue":"2026-10-31","dateRetour":null}]
PATCH /api/emprunts/1/retour → 200 {"id":1,"livre":"Notre-Dame de Paris","rendu":"2026-11-15","enRetard":true}
PATCH /api/emprunts/1/retour → 409 {"message":"Emprunt 1 déjà rendu le 2026-11-15","error":"Conflict","statusCode":409}
POST /api/emprunts → 201 {"id":4,"livre":"Le Barrage","adherent":"Sami Ben Ali","dateRetourPrevue":"2026-11-29"}
POST /api/emprunts → 201 {"id":5,"livre":"Les Misérables","adherent":"Ines Trabelsi","dateRetourPrevue":"2026-11-29"}
PATCH /api/livres/3 → 409 {"message":"2 exemplaire(s) sont empruntés : impossible de descendre à 1","error":"Conflict","statusCode":409}
GET /api/emprunts/statistiques → 200 {"enCours":4,"plusEmpruntes":[{"titre":"Les Misérables","emprunts":2},{"titre":"Le Barrage","emprunts":1},{"titre":"Les Chants de la vie","emprunts":1}]}
GET /api/adherents/1/emprunts → 200 {"id":1,"nom":"Ben Ali","prenom":"Sami","email":"sami@exemple.tn","actif":true,"emprunts":[{"id":2,"livre":{"id":3,"isbn":"9782070409228","titre":"Les Misérables","anneePublication":1862,"exemplaires":4,"disponibles":2,"auteurId":3,"creeLe":"…"},"dateEmprunt":"2026-11-15","dateRetourPrevue":"2026-11-29","dateRetour":null},{"id":4,"livre":{"id":2,"isbn":"9789973000028","titre":"Le Barrage","anneePublication":1955,"exemplaires":2,"disponibles":1,"auteurId":2,"creeLe":"…"},"dateEmprunt":"2026-11-15","dateRetourPrevue":"2026-11-29","dateRetour":null},{"id":3,"livre":{"id":1,"isbn":"9789973000011","titre":"Les Chants de la vie","anneePublication":1955,"exemplaires":3,"disponibles":2,"auteurId":1,"creeLe":"…"},"dateEmprunt":"2026-11-15","dateRetourPrevue":"2026-11-29","dateRetour":null},{"id":1,"livre":{"id":4,"isbn":"9782253096337","titre":"Notre-Dame de Paris","anneePublication":1831,"exemplaires":3,"disponibles":3,"auteurId":3,"creeLe":"…"},"dateEmprunt":"2026-10-17","dateRetourPrevue":"2026-10-31","dateRetour":"2026-11-15"}]}
Points à vérifier dans vos propres résultats : la recherche par catégorie renvoie les livres avec leurs deux catégories ; le dernier exemplaire de « Notre-Dame de Paris » ne peut pas être emprunté deux fois ; l'adhérent inactif est refusé (422) ; la quatrième demande de Sami est refusée ; la réduction à 1 exemplaire des « Misérables » est refusée car 2 exemplaires sont empruntés ; l'auteur Hugo ne peut pas être supprimé ; l'emprunt dont la date a été modifiée apparaît en retard, et son retour indique enRetard: true.
Pour aller plus loin
- Ajoutez des réservations: quand un livre n'est pas disponible, l'adhérent peut le réserver ; au retour, l'exemplaire est attribué au premier réservataire (transaction).
- Ajoutez une colonne
penalitesaux adhérents : 0,500 DT par jour de retard, calculés au retour (attention aux DECIMAL, leçon 11.3). - Écrivez une migration qui ajoute la colonne
resume(texte facultatif) aux livres, puis annulez-la et réappliquez-la. - Remplacez le verrou pessimiste par une mise à jour conditionnelle (
UPDATE … WHERE disponibles > 0, leçon 11.9, activité 4) et comparez. - Protégez les routes d'écriture avec les guards du TP 6 (rôle « bibliothécaire »).
Correction
src/auteurs/auteur.entity.ts
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
import { Livre } from '../livres/livre.entity';
@Entity('auteurs')
export class Auteur {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 60 })
nom: string;
@Column({ length: 60 })
prenom: string;
@Column({ type: 'varchar', length: 40, nullable: true }) // type obligatoire avec « string | null »
nationalite: string | null;
@OneToMany(() => Livre, (livre) => livre.auteur)
livres: Livre[];
}
src/livres/categorie.entity.ts
import { Column, Entity, ManyToMany, PrimaryGeneratedColumn } from 'typeorm';
import { Livre } from './livre.entity';
@Entity('categories')
export class Categorie {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 40, unique: true })
libelle: string;
@ManyToMany(() => Livre, (livre) => livre.categories)
livres: Livre[];
}
src/livres/livre.entity.ts
import {
Column, CreateDateColumn, Entity, Index, JoinColumn, JoinTable, ManyToMany, ManyToOne, OneToMany, PrimaryGeneratedColumn,
} from 'typeorm';
import { Auteur } from '../auteurs/auteur.entity';
import { Emprunt } from '../emprunts/emprunt.entity';
import { Categorie } from './categorie.entity';
@Entity('livres')
export class Livre {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'char', length: 13, unique: true })
isbn: string;
@Index()
@Column({ length: 200 })
titre: string;
@Column({ type: 'smallint', name: 'annee_publication' })
anneePublication: number;
@Column({ type: 'smallint' })
exemplaires: number; // nombre total d'exemplaires
@Column({ type: 'smallint' })
disponibles: number; // exemplaires non empruntés
@ManyToOne(() => Auteur, (auteur) => auteur.livres, { nullable: false, onDelete: 'RESTRICT' })
@JoinColumn({ name: 'auteur_id' })
auteur: Auteur;
@Column({ name: 'auteur_id' })
auteurId: number;
@ManyToMany(() => Categorie, (categorie) => categorie.livres)
@JoinTable({ name: 'livres_categories', joinColumn: { name: 'livre_id' }, inverseJoinColumn: { name: 'categorie_id' } })
categories: Categorie[];
@OneToMany(() => Emprunt, (emprunt) => emprunt.livre)
emprunts: Emprunt[];
@CreateDateColumn({ name: 'cree_le' })
creeLe: Date;
}
src/adherents/adherent.entity.ts
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
import { Emprunt } from '../emprunts/emprunt.entity';
@Entity('adherents')
export class Adherent {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 60 })
nom: string;
@Column({ length: 60 })
prenom: string;
@Column({ length: 120, unique: true })
email: string;
@Column({ default: true })
actif: boolean;
@OneToMany(() => Emprunt, (emprunt) => emprunt.adherent)
emprunts: Emprunt[];
}
src/emprunts/emprunt.entity.ts
import { Column, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { Adherent } from '../adherents/adherent.entity';
import { Livre } from '../livres/livre.entity';
@Entity('emprunts')
export class Emprunt {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(() => Livre, (livre) => livre.emprunts, { nullable: false, onDelete: 'CASCADE' })
@JoinColumn({ name: 'livre_id' })
livre: Livre;
@ManyToOne(() => Adherent, (adherent) => adherent.emprunts, { nullable: false })
@JoinColumn({ name: 'adherent_id' })
adherent: Adherent;
@Column({ type: 'date', name: 'date_emprunt' })
dateEmprunt: string;
@Index()
@Column({ type: 'date', name: 'date_retour_prevue' })
dateRetourPrevue: string;
@Column({ type: 'date', name: 'date_retour', nullable: true })
dateRetour: string | null; // null tant que le livre n'est pas rendu
}
src/data-source.ts
import 'dotenv/config';
import { DataSource } from 'typeorm';
// Source de données utilisée par la CLI de TypeORM (migrations) et par les seeders
export default new DataSource({
type: 'mysql',
host: process.env.DB_HOTE,
port: Number(process.env.DB_PORT ?? 3306),
username: process.env.DB_UTILISATEUR,
password: process.env.DB_MOT_DE_PASSE,
database: process.env.DB_NOM,
entities: [__dirname + '/**/*.entity.js'],
migrations: [__dirname + '/migrations/*.js'],
synchronize: false, // ✓ le schéma n'évolue QUE par les migrations
});
src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { APP_FILTER } from '@nestjs/core';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AdherentsModule } from './adherents/adherents.module';
import { AuteursModule } from './auteurs/auteurs.module';
import { TypeOrmErreursFilter } from './common/typeorm-erreurs.filter';
import { EmpruntsModule } from './emprunts/emprunts.module';
import { LivresModule } from './livres/livres.module';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
type: 'mysql',
host: config.getOrThrow('DB_HOTE'),
port: Number(config.get('DB_PORT', 3306)),
username: config.getOrThrow('DB_UTILISATEUR'),
password: config.get('DB_MOT_DE_PASSE', ''),
database: config.getOrThrow('DB_NOM'),
autoLoadEntities: true,
synchronize: false, // le schéma est géré par les migrations
}),
}),
AuteursModule,
LivresModule,
AdherentsModule,
EmpruntsModule,
],
providers: [{ provide: APP_FILTER, useClass: TypeOrmErreursFilter }],
})
export class AppModule {}
src/common/typeorm-erreurs.filter.ts
import { ArgumentsHost, Catch, ExceptionFilter, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import { QueryFailedError } from 'typeorm';
// Traduit les erreurs de contraintes MySQL en réponses HTTP compréhensibles
@Catch(QueryFailedError)
export class TypeOrmErreursFilter implements ExceptionFilter {
catch(exception: QueryFailedError & { code?: string }, host: ArgumentsHost) {
const res = host.switchToHttp().getResponse<Response>();
const correspondances: Record<string, [number, string]> = {
ER_DUP_ENTRY: [HttpStatus.CONFLICT, 'Cette valeur existe déjà (champ unique)'],
ER_ROW_IS_REFERENCED_2: [HttpStatus.CONFLICT, 'Suppression impossible : cet élément est utilisé ailleurs'],
ER_NO_REFERENCED_ROW_2: [HttpStatus.BAD_REQUEST, 'Référence vers un élément inexistant'],
};
const [statut, message] = correspondances[exception.code ?? ''] ?? [HttpStatus.INTERNAL_SERVER_ERROR, 'Erreur de base de données'];
res.status(statut).json({ statusCode: statut, message });
}
}
src/common/date.ts
// Dates au format AAAA-MM-JJ (colonnes DATE)
export const aujourdHui = (): string => new Date().toISOString().slice(0, 10);
export function dansNJours(n: number): string {
const d = new Date();
d.setDate(d.getDate() + n);
return d.toISOString().slice(0, 10);
}
src/auteurs/auteur.dto.ts
import { IsOptional, IsString, Length } from 'class-validator';
export class CreerAuteurDto {
@IsString() @Length(1, 60) nom: string;
@IsString() @Length(1, 60) prenom: string;
@IsOptional() @IsString() @Length(2, 40) nationalite?: string;
}
src/auteurs/auteurs.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreerAuteurDto } from './auteur.dto';
import { Auteur } from './auteur.entity';
@Injectable()
export class AuteursService {
constructor(@InjectRepository(Auteur) private readonly depot: Repository<Auteur>) {}
findAll() {
return this.depot.find({ order: { nom: 'ASC' } });
}
async findOne(id: number) {
const auteur = await this.depot.findOne({ where: { id }, relations: { livres: true } });
if (!auteur) throw new NotFoundException(`Auteur ${id} introuvable`);
return auteur;
}
create(dto: CreerAuteurDto) {
return this.depot.save(this.depot.create(dto));
}
async remove(id: number) {
const resultat = await this.depot.delete({ id }); // ER_ROW_IS_REFERENCED_2 s'il a des livres
if (!resultat.affected) throw new NotFoundException(`Auteur ${id} introuvable`);
}
}
src/auteurs/auteurs.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Param, ParseIntPipe, Post } from '@nestjs/common';
import { CreerAuteurDto } from './auteur.dto';
import { AuteursService } from './auteurs.service';
@Controller('auteurs')
export class AuteursController {
constructor(private readonly auteursService: AuteursService) {}
@Get()
findAll() {
return this.auteursService.findAll();
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.auteursService.findOne(id);
}
@Post()
create(@Body() dto: CreerAuteurDto) {
return this.auteursService.create(dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', ParseIntPipe) id: number) {
return this.auteursService.remove(id);
}
}
src/auteurs/auteurs.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Auteur } from './auteur.entity';
import { AuteursController } from './auteurs.controller';
import { AuteursService } from './auteurs.service';
@Module({
imports: [TypeOrmModule.forFeature([Auteur])],
controllers: [AuteursController],
providers: [AuteursService],
})
export class AuteursModule {}
src/livres/livre.dto.ts
import { OmitType, PartialType } from '@nestjs/mapped-types';
import { Transform, Type } from 'class-transformer';
import {
ArrayUnique, IsArray, IsBoolean, IsIn, IsInt, IsOptional, IsPositive, IsString, Length, Matches, Max, Min, MinLength,
} from 'class-validator';
export class CreerLivreDto {
@Matches(/^\d{13}$/, { message: "L'ISBN doit contenir 13 chiffres" })
isbn: string;
@IsString() @Length(1, 200)
titre: string;
@IsInt() @Min(1450) @Max(new Date().getFullYear())
anneePublication: number;
@IsInt() @Min(1) @Max(50)
exemplaires: number;
@IsInt() @IsPositive()
auteurId: number;
@IsOptional() @IsArray() @ArrayUnique() @IsInt({ each: true })
categorieIds?: number[];
}
export class ModifierLivreDto extends PartialType(OmitType(CreerLivreDto, ['isbn'] as const)) {}
export class FiltreLivresDto {
@IsOptional() @Type(() => Number) @IsInt() @Min(1)
page: number = 1;
@IsOptional() @Type(() => Number) @IsInt() @Min(1) @Max(50)
limite: number = 10;
@IsOptional() @IsString() @MinLength(2)
q?: string;
@IsOptional() @Type(() => Number) @IsInt()
auteurId?: number;
@IsOptional() @IsString()
categorie?: string;
@IsOptional() @Transform(({ value }) => value === 'true' ? true : value === 'false' ? false : value) @IsBoolean()
disponible?: boolean;
@IsOptional() @IsIn(['titre', 'anneePublication', 'creeLe'])
tri: 'titre' | 'anneePublication' | 'creeLe' = 'titre';
@IsOptional() @IsIn(['asc', 'desc'])
ordre: 'asc' | 'desc' = 'asc';
}
src/livres/livres.service.ts
import { BadRequestException, ConflictException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, IsNull, Repository } from 'typeorm';
import { Auteur } from '../auteurs/auteur.entity';
import { Emprunt } from '../emprunts/emprunt.entity';
import { Categorie } from './categorie.entity';
import { CreerLivreDto, FiltreLivresDto, ModifierLivreDto } from './livre.dto';
import { Livre } from './livre.entity';
@Injectable()
export class LivresService {
constructor(
@InjectRepository(Livre) private readonly livres: Repository<Livre>,
@InjectRepository(Auteur) private readonly auteurs: Repository<Auteur>,
@InjectRepository(Categorie) private readonly categories: Repository<Categorie>,
@InjectRepository(Emprunt) private readonly emprunts: Repository<Emprunt>,
) {}
async rechercher(f: FiltreLivresDto) {
const qb = this.livres
.createQueryBuilder('l')
.leftJoinAndSelect('l.auteur', 'a')
.leftJoinAndSelect('l.categories', 'c');
if (f.q) qb.andWhere('l.titre LIKE :q', { q: `%${f.q}%` });
if (f.auteurId) qb.andWhere('l.auteurId = :auteurId', { auteurId: f.auteurId });
if (f.categorie) {
// sous-requête : garder TOUTES les catégories du livre dans la réponse
qb.andWhere(
'l.id IN (SELECT lc.livre_id FROM livres_categories lc JOIN categories c2 ON c2.id = lc.categorie_id WHERE c2.libelle = :cat)',
{ cat: f.categorie },
);
}
if (f.disponible !== undefined) qb.andWhere(f.disponible ? 'l.disponibles > 0' : 'l.disponibles = 0');
qb.orderBy(`l.${f.tri}`, f.ordre === 'desc' ? 'DESC' : 'ASC').addOrderBy('l.id')
.skip((f.page - 1) * f.limite).take(f.limite);
const [donnees, total] = await qb.getManyAndCount();
return { donnees, meta: { total, page: f.page, limite: f.limite, pages: Math.max(1, Math.ceil(total / f.limite)) } };
}
async findOne(id: number) {
const livre = await this.livres.findOne({ where: { id }, relations: { auteur: true, categories: true } });
if (!livre) throw new NotFoundException(`Livre ${id} introuvable`);
return livre;
}
private async chargerCategories(ids?: number[]) {
if (!ids?.length) return [];
const trouvees = await this.categories.findBy({ id: In(ids) });
if (trouvees.length !== ids.length) throw new BadRequestException('Une ou plusieurs catégories sont inconnues');
return trouvees;
}
async create(dto: CreerLivreDto) {
if (!(await this.auteurs.existsBy({ id: dto.auteurId }))) {
throw new NotFoundException(`Auteur ${dto.auteurId} introuvable`);
}
const livre = this.livres.create({
...dto,
disponibles: dto.exemplaires,
categories: await this.chargerCategories(dto.categorieIds),
});
return this.livres.save(livre);
}
async update(id: number, dto: ModifierLivreDto) {
const livre = await this.findOne(id);
if (dto.exemplaires !== undefined) {
const empruntes = livre.exemplaires - livre.disponibles;
if (dto.exemplaires < empruntes) {
throw new ConflictException(`${empruntes} exemplaire(s) sont empruntés : impossible de descendre à ${dto.exemplaires}`);
}
livre.disponibles = dto.exemplaires - empruntes;
livre.exemplaires = dto.exemplaires;
}
if (dto.auteurId !== undefined) {
if (!(await this.auteurs.existsBy({ id: dto.auteurId }))) throw new NotFoundException(`Auteur ${dto.auteurId} introuvable`);
livre.auteurId = dto.auteurId;
livre.auteur = { id: dto.auteurId } as Auteur;
}
if (dto.categorieIds) livre.categories = await this.chargerCategories(dto.categorieIds);
if (dto.titre !== undefined) livre.titre = dto.titre;
if (dto.anneePublication !== undefined) livre.anneePublication = dto.anneePublication;
await this.livres.save(livre);
return this.findOne(id);
}
async remove(id: number) {
const livre = await this.findOne(id);
if (await this.emprunts.existsBy({ livre: { id }, dateRetour: IsNull() })) {
throw new ConflictException(`Le livre « ${livre.titre} » a des emprunts en cours`);
}
await this.livres.remove(livre);
}
}
src/livres/livres.controller.ts
import { Body, Controller, Delete, Get, HttpCode, Param, ParseIntPipe, Patch, Post, Query } from '@nestjs/common';
import { CreerLivreDto, FiltreLivresDto, ModifierLivreDto } from './livre.dto';
import { LivresService } from './livres.service';
@Controller('livres')
export class LivresController {
constructor(private readonly livresService: LivresService) {}
@Get()
rechercher(@Query() filtre: FiltreLivresDto) {
return this.livresService.rechercher(filtre);
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.livresService.findOne(id);
}
@Post()
create(@Body() dto: CreerLivreDto) {
return this.livresService.create(dto);
}
@Patch(':id')
update(@Param('id', ParseIntPipe) id: number, @Body() dto: ModifierLivreDto) {
return this.livresService.update(id, dto);
}
@Delete(':id')
@HttpCode(204)
remove(@Param('id', ParseIntPipe) id: number) {
return this.livresService.remove(id);
}
}
src/livres/livres.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Auteur } from '../auteurs/auteur.entity';
import { Emprunt } from '../emprunts/emprunt.entity';
import { Categorie } from './categorie.entity';
import { Livre } from './livre.entity';
import { LivresController } from './livres.controller';
import { LivresService } from './livres.service';
@Module({
imports: [TypeOrmModule.forFeature([Livre, Auteur, Categorie, Emprunt])],
controllers: [LivresController],
providers: [LivresService],
})
export class LivresModule {}
src/adherents/adherent.dto.ts
import { IsEmail, IsString, Length } from 'class-validator';
export class CreerAdherentDto {
@IsString() @Length(1, 60) nom: string;
@IsString() @Length(1, 60) prenom: string;
@IsEmail() email: string;
}
src/adherents/adherents.controller.ts
import { Body, Controller, Get, NotFoundException, Param, ParseIntPipe, Post } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreerAdherentDto } from './adherent.dto';
import { Adherent } from './adherent.entity';
@Controller('adherents')
export class AdherentsController {
constructor(@InjectRepository(Adherent) private readonly depot: Repository<Adherent>) {}
@Post()
create(@Body() dto: CreerAdherentDto) {
return this.depot.save(this.depot.create(dto));
}
@Get(':id/emprunts')
async emprunts(@Param('id', ParseIntPipe) id: number) {
const adherent = await this.depot.findOne({
where: { id },
relations: { emprunts: { livre: true } },
order: { emprunts: { dateEmprunt: 'DESC' } },
});
if (!adherent) throw new NotFoundException(`Adhérent ${id} introuvable`);
return adherent;
}
}
src/adherents/adherents.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Adherent } from './adherent.entity';
import { AdherentsController } from './adherents.controller';
@Module({
imports: [TypeOrmModule.forFeature([Adherent])],
controllers: [AdherentsController],
})
export class AdherentsModule {}
src/emprunts/emprunt.dto.ts
import { IsInt, IsPositive } from 'class-validator';
export class CreerEmpruntDto {
@IsInt() @IsPositive() livreId: number;
@IsInt() @IsPositive() adherentId: number;
}
src/emprunts/emprunts.service.ts
import { ConflictException, Injectable, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
import { InjectDataSource } from '@nestjs/typeorm';
import { DataSource, IsNull, LessThan } from 'typeorm';
import { Adherent } from '../adherents/adherent.entity';
import { aujourdHui, dansNJours } from '../common/date';
import { Livre } from '../livres/livre.entity';
import { CreerEmpruntDto } from './emprunt.dto';
import { Emprunt } from './emprunt.entity';
export const MAX_EMPRUNTS = 3;
export const DUREE_JOURS = 14;
@Injectable()
export class EmpruntsService {
constructor(@InjectDataSource() private readonly source: DataSource) {}
emprunter(dto: CreerEmpruntDto) {
return this.source.transaction(async (m) => {
// verrou sur le livre : deux emprunts simultanés du dernier exemplaire sont impossibles
const livre = await m.findOne(Livre, { where: { id: dto.livreId }, lock: { mode: 'pessimistic_write' } });
if (!livre) throw new NotFoundException(`Livre ${dto.livreId} introuvable`);
const adherent = await m.findOneBy(Adherent, { id: dto.adherentId });
if (!adherent) throw new NotFoundException(`Adhérent ${dto.adherentId} introuvable`);
if (!adherent.actif) throw new UnprocessableEntityException('Adhérent inactif');
const enCours = await m.countBy(Emprunt, { adherent: { id: adherent.id }, dateRetour: IsNull() });
if (enCours >= MAX_EMPRUNTS) {
throw new UnprocessableEntityException(`Limite atteinte : ${MAX_EMPRUNTS} emprunts en cours`);
}
if (await m.existsBy(Emprunt, { adherent: { id: adherent.id }, livre: { id: livre.id }, dateRetour: IsNull() })) {
throw new ConflictException('Cet adhérent a déjà emprunté ce livre');
}
if (livre.disponibles < 1) throw new ConflictException(`Aucun exemplaire disponible de « ${livre.titre} »`);
await m.decrement(Livre, { id: livre.id }, 'disponibles', 1);
const emprunt = m.create(Emprunt, {
livre, adherent, dateEmprunt: aujourdHui(), dateRetourPrevue: dansNJours(DUREE_JOURS), dateRetour: null,
});
const enregistre = await m.save(emprunt);
return { id: enregistre.id, livre: livre.titre, adherent: `${adherent.prenom} ${adherent.nom}`, dateRetourPrevue: enregistre.dateRetourPrevue };
});
}
rendre(id: number) {
return this.source.transaction(async (m) => {
const emprunt = await m.findOne(Emprunt, { where: { id }, relations: { livre: true }, lock: { mode: 'pessimistic_write' } });
if (!emprunt) throw new NotFoundException(`Emprunt ${id} introuvable`);
if (emprunt.dateRetour) throw new ConflictException(`Emprunt ${id} déjà rendu le ${emprunt.dateRetour}`);
emprunt.dateRetour = aujourdHui();
await m.save(emprunt);
await m.increment(Livre, { id: emprunt.livre.id }, 'disponibles', 1);
const retard = emprunt.dateRetour > emprunt.dateRetourPrevue;
return { id, livre: emprunt.livre.titre, rendu: emprunt.dateRetour, enRetard: retard };
});
}
enRetard() {
return this.source.getRepository(Emprunt).find({
where: { dateRetour: IsNull(), dateRetourPrevue: LessThan(aujourdHui()) },
relations: { livre: true, adherent: true },
order: { dateRetourPrevue: 'ASC' },
});
}
async statistiques() {
const plusEmpruntes = await this.source
.createQueryBuilder()
.select('l.titre', 'titre')
.addSelect('COUNT(e.id)', 'emprunts')
.from(Emprunt, 'e')
.innerJoin('e.livre', 'l')
.groupBy('l.id')
.orderBy('emprunts', 'DESC')
.addOrderBy('l.titre')
.limit(3)
.getRawMany<{ titre: string; emprunts: string }>();
const enCours = await this.source.getRepository(Emprunt).countBy({ dateRetour: IsNull() });
return { enCours, plusEmpruntes: plusEmpruntes.map((r) => ({ titre: r.titre, emprunts: Number(r.emprunts) })) };
}
}
src/emprunts/emprunts.controller.ts
import { Body, Controller, Get, Param, ParseIntPipe, Patch, Post } from '@nestjs/common';
import { CreerEmpruntDto } from './emprunt.dto';
import { EmpruntsService } from './emprunts.service';
@Controller('emprunts')
export class EmpruntsController {
constructor(private readonly empruntsService: EmpruntsService) {}
@Post()
emprunter(@Body() dto: CreerEmpruntDto) {
return this.empruntsService.emprunter(dto);
}
@Patch(':id/retour')
rendre(@Param('id', ParseIntPipe) id: number) {
return this.empruntsService.rendre(id);
}
@Get('en-retard')
enRetard() {
return this.empruntsService.enRetard();
}
@Get('statistiques')
statistiques() {
return this.empruntsService.statistiques();
}
}
src/emprunts/emprunts.module.ts
import { Module } from '@nestjs/common';
import { EmpruntsController } from './emprunts.controller';
import { EmpruntsService } from './emprunts.service';
@Module({ controllers: [EmpruntsController], providers: [EmpruntsService] })
export class EmpruntsModule {}
src/seeds/seed.ts
import 'reflect-metadata';
import source from '../data-source';
import { Adherent } from '../adherents/adherent.entity';
import { Auteur } from '../auteurs/auteur.entity';
import { Categorie } from '../livres/categorie.entity';
import { Livre } from '../livres/livre.entity';
async function semer() {
await source.initialize();
await source.transaction(async (m) => {
if (await m.count(Livre)) {
console.log('Données déjà présentes : rien à faire');
return;
}
const [roman, poesie, histoire, jeunesse] = await m.save(Categorie, [
{ libelle: 'Roman' }, { libelle: 'Poésie' }, { libelle: 'Histoire' }, { libelle: 'Jeunesse' },
]);
const [chebbi, messadi, hugo, zola] = await m.save(Auteur, [
{ nom: 'Chebbi', prenom: 'Aboul-Qacem', nationalite: 'tunisienne' },
{ nom: 'Messadi', prenom: 'Mahmoud', nationalite: 'tunisienne' },
{ nom: 'Hugo', prenom: 'Victor', nationalite: 'française' },
{ nom: 'Zola', prenom: 'Émile', nationalite: 'française' },
]);
await m.save(Livre, [
{ isbn: '9789973000011', titre: 'Les Chants de la vie', anneePublication: 1955, exemplaires: 3, disponibles: 3, auteur: chebbi, categories: [poesie] },
{ isbn: '9789973000028', titre: 'Le Barrage', anneePublication: 1955, exemplaires: 2, disponibles: 2, auteur: messadi, categories: [roman] },
{ isbn: '9782070409228', titre: 'Les Misérables', anneePublication: 1862, exemplaires: 4, disponibles: 4, auteur: hugo, categories: [roman, histoire] },
{ isbn: '9782253096337', titre: 'Notre-Dame de Paris', anneePublication: 1831, exemplaires: 1, disponibles: 1, auteur: hugo, categories: [roman] },
{ isbn: '9782253004226', titre: 'Germinal', anneePublication: 1885, exemplaires: 2, disponibles: 2, auteur: zola, categories: [roman, histoire] },
{ isbn: '9782070612758', titre: 'Contes pour enfants', anneePublication: 1990, exemplaires: 5, disponibles: 5, auteur: hugo, categories: [jeunesse] },
]);
await m.save(Adherent, [
{ nom: 'Ben Ali', prenom: 'Sami', email: 'sami@exemple.tn' },
{ nom: 'Trabelsi', prenom: 'Ines', email: 'ines@exemple.tn' },
{ nom: 'Gharbi', prenom: 'Yassine', email: 'yassine@exemple.tn', actif: false },
]);
console.log('Seeder : 4 catégories, 4 auteurs, 6 livres, 3 adhérents');
});
await source.destroy();
}
semer().catch((e) => {
console.error('Seeder en échec :', e.message);
process.exit(1);
});
src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
package.json (scripts)
{
"scripts": {
"typeorm": "typeorm -d dist/data-source.js",
"migration:generate": "npm run build && npm run typeorm -- migration:generate src/migrations/$npm_config_name",
"migration:create": "typeorm migration:create src/migrations/$npm_config_name",
"migration:run": "npm run build && npm run typeorm -- migration:run",
"migration:revert": "npm run typeorm -- migration:revert",
"migration:show": "npm run typeorm -- migration:show",
"seed": "npm run build && node dist/seeds/seed.js"
}
}
Grille d'évaluation
| Critère | Points |
|---|---|
Dépôt GitHub dès la Partie 1, un commit clair par partie, .env non versionné, étiquette v1.0.0 | 2 |
| Entités, types de colonnes et relations corrects (ManyToOne, OneToMany, ManyToMany, onDelete) | 4 |
| Migration initiale générée, relue et versionnée ; seeder idempotent | 3 |
| Recherche paginée, filtres (dont catégorie), tri par liste blanche, métadonnées | 3 |
| CRUD des livres et auteurs : validation, 404, 409 (doublon, suppression, exemplaires) | 3 |
| Emprunts et retours en transaction avec verrou, toutes les règles métier | 3 |
| Retards, statistiques, fichier .http complet et README | 2 |
| Total | 20 |
Cet article vous a-t-il aidé ?
Merci pour votre avis sur cet article 🙏
Merci, votre message nous a bien été transmis 🙏
Cette leçon vous a été utile ? Partagez-la !