web:api:prisma-fastify:p2-b

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

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] jcheronweb: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<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 =====
  • web/api/prisma-fastify/p2-b.1773212963.txt.gz
  • Dernière modification : il y a 7 semaines
  • de jcheron