Archived
2
This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
definma-api/src/routes/validate/id.ts

29 lines
872 B
TypeScript
Raw Normal View History

2020-05-07 21:55:29 +02:00
import Joi from '@hapi/joi';
2020-04-29 12:10:27 +02:00
export default class IdValidate {
2020-05-07 21:55:29 +02:00
private static id = Joi.string().pattern(new RegExp('[0-9a-f]{24}')).length(24);
2020-04-29 12:10:27 +02:00
2020-05-18 14:47:22 +02:00
static get () { // return joi validation
2020-04-29 12:10:27 +02:00
return this.id;
}
2020-05-18 14:47:22 +02:00
static valid (id) { // validate id
2020-04-29 12:10:27 +02:00
return this.id.validate(id).error === undefined;
}
2020-05-06 14:39:04 +02:00
static parameter () { // :id url parameter
2020-04-29 12:10:27 +02:00
return ':id([0-9a-f]{24})';
}
2020-05-06 14:39:04 +02:00
2020-05-18 14:47:22 +02:00
static stringify (data) { // convert all ObjectID objects to plain strings
2020-05-06 14:39:04 +02:00
Object.keys(data).forEach(key => {
2020-05-18 14:47:22 +02:00
if (data[key] !== null && data[key].hasOwnProperty('_bsontype') && data[key]._bsontype === 'ObjectID') { // stringify id
2020-05-06 14:39:04 +02:00
data[key] = data[key].toString();
}
2020-05-18 14:47:22 +02:00
else if (typeof data[key] === 'object' && data[key] !== null) { // deeper into recursion
data[key] = this.stringify(data[key]);
}
2020-05-06 14:39:04 +02:00
});
return data;
}
2020-04-29 12:10:27 +02:00
}