1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-28 00:06:53 +01:00
unleash.unleash/lib/routes/admin-api/util.js

51 lines
1.3 KiB
JavaScript
Raw Normal View History

'use strict';
2020-07-31 22:15:09 +02:00
const joi = require('joi');
const customJoi = joi.extend(j => ({
2020-01-02 19:23:52 +01:00
type: 'isUrlFriendly',
base: j.string(),
2020-01-02 19:23:52 +01:00
messages: {
'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') };
}
return undefined;
},
}));
const nameType = customJoi
.isUrlFriendly()
.min(2)
.max(100)
.required();
const handleErrors = (res, logger, error) => {
logger.warn(error.message);
// eslint-disable-next-line no-param-reassign
error.isJoi = true;
switch (error.name) {
case 'NotFoundError':
return res.status(404).end();
case 'NameExistsError':
return res
.status(409)
.json(error)
.end();
case 'ValidationError':
return res
.status(400)
.json(error)
.end();
default:
logger.error('Server failed executing request', error);
return res.status(500).end();
}
};
module.exports = { nameType, handleErrors };