[[:oktatas:web:express:typescript_ervenyesseg|< TypeScript érvényesség]] ====== Express - TypeScript validálás joi-val ====== * **Szerző:** Sallai András * Copyright (c) 2024, Sallai András * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: https://szit.hu ===== Függőség ===== Az érvényesség ellenőrzéséhez a joi csomagot fogjuk használni. npm install joi ===== Érvényesség ellenőrzése ===== Az érvényesség ellenőrzéséhez köztes szoftvert fogunk készíteni: import Joi from 'joi'; import { NextFunction, Request, Response } from 'express'; const empSchema = Joi.object({ name: Joi.string().required(), city: Joi.string().min(2), salary: Joi.number() }) const empValidate = ( req: Request, res: Response, next: NextFunction): any => { const { error } = empSchema.validate(req.body); if (error) { res.status(400); return res.json({ error: error.details[0].message }); } next() }; export { empValidate } ===== Belépési pont ===== import express, { Request, Response } from 'express'; import router from './routes/api'; const app = express(); const PORT = 8000; app.use(express.json()); app.use('/api', router); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }) ===== Routing ===== Az útvonalaknál használjuk a köztes szoftvert. import { Router } from 'express'; import EmpController from '../controllers/empController'; import { empValidate } from '../middlewares/validate'; const router = Router(); router.get('/employees', EmpController.index); router.post('/employees', [empValidate], EmpController.store); export default router; ===== Kontroller ===== import { Request, Response } from "express" const EmpController = { index: (req : Request, res : Response) => { res.json({ employees : [] }) }, store: (req : Request, res : Response) => { res.json({ name: req.body.name }) } } export default EmpController ===== Linkek ===== * https://joi.dev/api/?v=17.13.0 (2024) * https://www.npmjs.com/package/joi (2024) * https://www.npmjs.com/package/@types/hapi__joi (2024)