| Les deux révisions précédentes Révision précédente Prochaine révision | Révision précédente |
| web:api:prisma-fastify:p2-b [2026/03/09 11:23] – jcheron | web:api:prisma-fastify:p2-b [2026/03/20 13:50] (Version actuelle) – [Factorisation] jcheron |
|---|
| |
| ----- | ----- |
| | |
| | ==== Factorisation ==== |
| | |
| | === Services === |
| | Pour le CRUD : |
| | <sxh ts> |
| | type CrudModel = { |
| | findMany: (args?: any) => any |
| | findUnique: (args: any) => any |
| | create: (args: any) => any |
| | update: (args: any) => any |
| | delete: (args: any) => any |
| | } |
| | |
| | class BaseService<T extends CrudModel> { |
| | constructor(private model: T) {} |
| | |
| | findAll() { |
| | return this.model.findMany() |
| | } |
| | |
| | findById(id: string) { |
| | return this.model.findUnique({ where: { id } }) |
| | } |
| | |
| | create(data: any) { |
| | return this.model.create({ data }) |
| | } |
| | |
| | update(id: string, data: any) { |
| | return this.model.update({ |
| | where: { id }, |
| | data |
| | }) |
| | } |
| | |
| | delete(id: string) { |
| | return this.model.delete({ |
| | where: { id } |
| | }) |
| | } |
| | } |
| | </sxh> |
| | |
| | === Spécialisation par ressource === |
| | <sxh ts> |
| | class EventService extends BaseService<Event> { |
| | constructor() { |
| | super(prisma.event) |
| | } |
| | |
| | async joinEvent(eventId: string, userId: string) { |
| | // logique métier spécifique |
| | } |
| | } |
| | </sxh> |
| | |
| | === Controller === |
| | Faire un helper : |
| | <sxh ts> |
| | const handle = (fn) => async (req, res) => { |
| | try { |
| | const result = await fn(req) |
| | res.send(result) |
| | } catch (e) { |
| | res.status(500).send({ error: e.message }) |
| | } |
| | } |
| | </sxh> |
| | Pour éviter les try/catch partout |
| | |
| | <sxh ts> |
| | const getEvents = handle(async (req) => { |
| | return eventService.findAll() |
| | }) |
| | </sxh> |
| | |
| | |
| |
| ===== Conclusion ===== | ===== Conclusion ===== |
| |
| ✔ Pas de classes | * Pas de classes |
| ✔ Fonctions simples | * Fonctions simples |
| ✔ Séparation claire | * Séparation claire |
| ✔ Architecture maintenable | * Architecture maintenable |
| ✔ Production ready | * Production ready |
| |
| ----- | ----- |
| | |
| | <button type="primary" size="sm">[[web:api:prisma-fastify:p3|Suite >>]]</button> |
| |