2018-12-01 12:03:47 +01:00
|
|
|
'use strict';
|
|
|
|
|
2020-07-31 22:15:09 +02:00
|
|
|
const joi = require('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);
|
2020-09-25 22:14:31 +02:00
|
|
|
// eslint-disable-next-line no-param-reassign
|
|
|
|
error.isJoi = true;
|
2018-12-05 21:16:51 +01:00
|
|
|
switch (error.name) {
|
|
|
|
case 'NotFoundError':
|
|
|
|
return res.status(404).end();
|
2020-09-28 21:54:44 +02:00
|
|
|
case 'InvalidOperationError':
|
2018-12-05 21:16:51 +01:00
|
|
|
case 'NameExistsError':
|
2020-09-25 22:14:31 +02:00
|
|
|
return res
|
|
|
|
.status(409)
|
|
|
|
.json(error)
|
|
|
|
.end();
|
2018-12-05 21:16:51 +01:00
|
|
|
case 'ValidationError':
|
|
|
|
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 };
|