banana
/
definma-api
Archived
2
Fork 0
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

33 lines
941 B
TypeScript

import Joi from 'joi';
export default class IdValidate {
private static id = Joi.string()
.pattern(new RegExp('[0-9a-f]{24}'))
.length(24)
.messages({'string.pattern.base': 'Invalid object id'});
static get () { // return joi validation
return this.id;
}
static valid (id) { // validate id
return this.id.validate(id).error === undefined;
}
static parameter () { // :id url parameter
return ':id([0-9a-f]{24})';
}
static stringify (data) { // convert all ObjectID objects to plain strings
Object.keys(data).forEach(key => {
// stringify id
if (data[key] !== null && data[key].hasOwnProperty('_bsontype') && data[key]._bsontype === 'ObjectID') {
data[key] = data[key].toString();
}
else if (typeof data[key] === 'object' && data[key] !== null) { // deeper into recursion
data[key] = this.stringify(data[key]);
}
});
return data;
}
}