Différences
Ci-dessous, les différences entre deux révisions de la page.
| 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/11 08:09] – jcheron | web:api:prisma-fastify:p2-b [2026/03/20 13:50] (Version actuelle) – [Factorisation] jcheron | ||
|---|---|---|---|
| Ligne 117: | Ligne 117: | ||
| ----- | ----- | ||
| + | |||
| + | ==== 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< | ||
| + | constructor(private model: T) {} | ||
| + | |||
| + | findAll() { | ||
| + | return this.model.findMany() | ||
| + | } | ||
| + | |||
| + | findById(id: | ||
| + | return this.model.findUnique({ where: { id } }) | ||
| + | } | ||
| + | |||
| + | create(data: | ||
| + | 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 } | ||
| + | }) | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | === Spécialisation par ressource === | ||
| + | <sxh ts> | ||
| + | class EventService extends BaseService< | ||
| + | constructor() { | ||
| + | super(prisma.event) | ||
| + | } | ||
| + | |||
| + | async joinEvent(eventId: | ||
| + | // logique métier spécifique | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | === 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 }) | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| + | Pour éviter les try/catch partout | ||
| + | |||
| + | <sxh ts> | ||
| + | const getEvents = handle(async (req) => { | ||
| + | return eventService.findAll() | ||
| + | }) | ||
| + | </ | ||
| + | |||
| + | |||
| ===== Conclusion ===== | ===== Conclusion ===== | ||