web:api:prisma-fastify:p2

Objectif :

  • Structurer proprement le projet
  • Séparer routes / controllers / services
  • Ajouter authentification JWT
  • Protéger les routes

npm install @fastify/jwt bcrypt
npm install -D @types/bcrypt


src/
 ├── server.ts
 ├── prisma.ts
 ├── plugins/
 │     └── jwt.ts
 ├── controllers/
 ├── services/
 └── routes/


Modifier `schema.prisma` :

model User {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  password  String
  createdAt DateTime @default(now())
}

Migration :

npx prisma migrate dev --name add_user


`src/plugins/jwt.ts`

import fp from "fastify-plugin"
import jwt from "@fastify/jwt"

export default fp(async (app) => {
  app.register(jwt, {
    secret: "supersecret"
  })

  app.decorate("authenticate", async (request: any, reply: any) => {
    await request.jwtVerify()
  })
})


Service = logique métier Controller = interface HTTP

Exemple logique :

Service :

async registerUser(data)

Controller :

async function register(request, reply)


app.get("/posts", {
  preHandler: [app.authenticate]
}, handler)

  • web/api/prisma-fastify/p2.txt
  • Dernière modification : il y a 38 heures
  • de jcheron