This repository has been archived on 2024-02-11. You can view files and clone it, but cannot push or open issues or pull requests.
Files
restful-api-task/services/ValidationService.js

33 lines
755 B
JavaScript

import { setResp400 } from '../helpers/http.js'
import { extractProps } from '../helpers/utils.js'
import {webFields} from '../repositories/schema.js'
/**
*
* @param schema
* @returns {(function(*, *, *): Promise<*|undefined>)|*}
*/
export default (schema) => async (req, res, next) => {
let objToValidate
if (req.method === 'POST' || req.method === 'PATCH') {
if (req.method === 'PATCH'){
webFields.id = null
}
objToValidate = extractProps(webFields, req.body)
}else{
const { id } = req.params
objToValidate = id
}
try {
req.validatedData = await schema.validate(objToValidate)
next()
} catch (error) {
return res.status(400).json(setResp400(error.name || null, error.message || null ))
}
}