Advertisement
cirossmonteiro

Express.JS, mongoose, Joi

Nov 13th, 2022 (edited)
914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 2.45 KB | Source Code | 0 0
  1. const Users = mongoose.model('users', new mongoose.Schema({
  2.   username: {
  3.     type: String,
  4.     required: true,
  5.     unique: true
  6.   },
  7.   color:{
  8.     type: String,
  9.     required: true,
  10.     unique: true
  11.   },
  12. }, { timestamps: true }));
  13.  
  14. const main = async (req, res, callback, {
  15.   internalCode = -1,
  16.   joiSchema = null
  17. }) => {
  18.   const params = { ...req.body, ...req.query };
  19.   let data;
  20.   try {
  21.     let value = {};
  22.     if (joiSchema) {
  23.       const { error: joiError, value: joiValue = {} } = await joiSchema.validate(params);
  24.       if (joiError) {
  25.         console.error(joiError);
  26.         throw `Joi error: ${JSON.stringify(joiError)}.`;
  27.       } else {
  28.         value = { ...joiValue };
  29.       }
  30.     }
  31.     await connectDB();
  32.     data = await callback(value);
  33.   } catch (err) {
  34.     const { code, index, keyPattern, keyValue, message } = err;
  35.     data = { code, index, keyPattern, keyValue, message };
  36.     console.error('ERROR', data);
  37.   } finally {
  38.     res.json(data);
  39.   }
  40. }
  41.  
  42. const joiPaginationSchema = Joi.object({
  43.   skip: Joi.number().default(0),
  44.   limit: Joi.number().default(PAGE_LIMIT)
  45. });
  46.  
  47. const joiSchemaFromModel = model => {
  48.   const obj = {};
  49.   const schemaObj = model.schema.obj;
  50.   Object.keys(schemaObj).forEach(field => {
  51.     const fieldType = schemaObj[field].type;
  52.     if (fieldType === String) {
  53.       obj[field] = Joi.string();
  54.     }
  55.   });
  56.   return Joi.object(obj);
  57. }
  58.  
  59. const joiModelSchema = model => joiPaginationSchema.concat(joiSchemaFromModel(model));
  60.  
  61. const paginationAggregation = ({
  62.   skip: $skip,
  63.   limit: $limit
  64. }) => [
  65.   { $skip },
  66.   { $limit }
  67. ];
  68.  
  69. const GEThandlerFromModel = model => async (req, res) => {
  70.   const joiSchema = joiModelSchema(model);
  71.   main(req, res, async (values = {}) => {
  72.     const { skip, limit } = values;
  73.     const $match = {};
  74.     const aggregation = [
  75.       { $match },
  76.       ...paginationAggregation({ skip, limit })
  77.     ];
  78.     return await model.aggregate(aggregation);
  79.   }, { joiSchema, internalCode: 52 });
  80. }
  81.  
  82. const POSThandlerFromModel = model => async (req, res) => {
  83.   const joiSchema = joiModelSchema(model);
  84.   main(req, res, async (values = {}) => {
  85.     return await model.create(values);
  86.   }, { joiSchema, internalCode: 52 });
  87. }
  88.  
  89. const mapMethods = {
  90.   GET: GEThandlerFromModel,
  91.   POST: POSThandlerFromModel
  92. }
  93.  
  94. const RESTAPIHandler = model => async (req, res) => {
  95.   mapMethods[req.method](model)(req, res);
  96. }
  97.  
  98. app.all('/users', RESTAPIHandler(Users));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement