NextNodeTemplate/backend/routes/example.js
DosAi 766d758be1
Some checks are pending
CI/CD / lint-and-build (push) Waiting to run
feat: Add timeout, improved error handling and logging to API client
2025-11-02 17:19:39 +03:00

89 lines
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Пример файла с роутами с валидацией
// Используйте эту структуру для организации API endpoints
const express = require('express');
const { body, param } = require('express-validator');
const validate = require('../middleware/validate');
const { strictLimiter } = require('../middleware/rateLimiter');
const logger = require('../config/logger');
const router = express.Router();
// GET endpoint
router.get('/hello', (req, res) => {
logger.info('Hello endpoint called');
res.json({
success: true,
message: 'Hello from example route!',
});
});
// POST endpoint с валидацией
router.post(
'/data',
strictLimiter, // Применить строгий rate limiter
[
body('name')
.trim()
.notEmpty()
.withMessage('Name is required')
.isLength({ min: 2, max: 50 })
.withMessage('Name must be between 2 and 50 characters'),
body('value')
.notEmpty()
.withMessage('Value is required')
.isNumeric()
.withMessage('Value must be a number'),
],
validate, // Проверяем результаты валидации
(req, res) => {
try {
const { name, value } = req.body;
logger.info(`Processing data: name=${name}, value=${value}`);
// Обработка данных
res.json({
success: true,
data: {
name,
value: Number(value),
processed: true,
timestamp: new Date().toISOString(),
},
});
} catch (err) {
logger.error('Error processing data:', err);
res.status(500).json({
success: false,
error: err.message,
});
}
}
);
// GET с параметром и валидацией
router.get(
'/item/:id',
[
param('id')
.isInt({ min: 1 })
.withMessage('ID must be a positive integer'),
],
validate,
(req, res) => {
const { id } = req.params;
logger.info(`Getting item with id: ${id}`);
res.json({
success: true,
data: {
id: Number(id),
name: 'Example Item',
},
});
}
);
module.exports = router;