2018-12-01 12:03:47 +01:00
|
|
|
'use strict';
|
|
|
|
|
2020-01-02 19:23:52 +01:00
|
|
|
const joi = require('@hapi/joi');
|
2018-12-12 10:09:38 +01:00
|
|
|
|
|
|
|
const customJoi = joi.extend(j => ({
|
2020-01-02 19:23:52 +01:00
|
|
|
type: 'isUrlFriendly',
|
2018-12-12 10:09:38 +01:00
|
|
|
base: j.string(),
|
2020-01-02 19:23:52 +01:00
|
|
|
messages: {
|
2020-02-21 22:14:40 +01:00
|
|
|
'isUrlFriendly.base': '{{#label}} must be URL friendly',
|
2020-01-02 19:23:52 +01:00
|
|
|
},
|
|
|
|
validate(value, helpers) {
|
|
|
|
// Base validation regardless of the rules applied
|
|
|
|
if (encodeURIComponent(value) !== value) {
|
|
|
|
// Generate an error, state and options need to be passed
|
|
|
|
return { value, errors: helpers.error('isUrlFriendly.base') };
|
|
|
|
}
|
2020-04-14 22:29:11 +02:00
|
|
|
return undefined;
|
2018-12-12 10:09:38 +01:00
|
|
|
},
|
|
|
|
}));
|
|
|
|
|
|
|
|
const nameType = customJoi
|
|
|
|
.isUrlFriendly()
|
|
|
|
.min(2)
|
|
|
|
.max(100)
|
|
|
|
.required();
|
2018-12-01 12:03:47 +01:00
|
|
|
|
2019-04-30 21:14:23 +02:00
|
|
|
const handleErrors = (res, logger, error) => {
|
2018-12-05 21:16:51 +01:00
|
|
|
logger.warn(error.message);
|
|
|
|
switch (error.name) {
|
|
|
|
case 'NotFoundError':
|
|
|
|
return res.status(404).end();
|
|
|
|
case 'NameExistsError':
|
|
|
|
case 'ValidationError':
|
2020-04-14 22:29:11 +02:00
|
|
|
// eslint-disable-next-line no-param-reassign
|
2020-01-02 19:23:52 +01:00
|
|
|
error.isJoi = true;
|
2018-12-05 21:16:51 +01:00
|
|
|
return res
|
|
|
|
.status(400)
|
|
|
|
.json(error)
|
|
|
|
.end();
|
|
|
|
default:
|
|
|
|
logger.error('Server failed executing request', error);
|
|
|
|
return res.status(500).end();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-12-12 10:09:38 +01:00
|
|
|
module.exports = { nameType, handleErrors };
|