JKHeadley / rest-hapi

πŸš€ A RESTful API generator for Node.js
https://resthapi.com
MIT License
1.19k stars 152 forks source link

Added support for querying "createdAt" date range in listHandler #297

Open alsabbahy opened 2 years ago

alsabbahy commented 2 years ago

Hi @JKHeadley ! πŸ‘‹

Firstly, thanks for your work on this project! πŸ™‚

Regarding the issue #296. Today I used patch-package to patch rest-hapi@2.3.0 for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/rest-hapi/utilities/handler-helper.js b/node_modules/rest-hapi/utilities/handler-helper.js
index e0334e5..a13b2ed 100644
--- a/node_modules/rest-hapi/utilities/handler-helper.js
+++ b/node_modules/rest-hapi/utilities/handler-helper.js
@@ -148,6 +148,23 @@ async function _listHandler(model, request, Log) {
     if (query.$flatten) {
       flatten = true
     }
+
+    if ( query.$startDate || query.$endDate ) {
+      query.createdAt = {}
+      
+      if ( query.$startDate ) {
+        query.createdAt.$gte = new Date( query.$startDate )
+
+        delete query.$startDate;
+      }
+
+      if ( query.$endDate ) {
+        query.createdAt.$lte = new Date( query.$endDate )
+
+        delete query.$endDate;
+      }
+    }
+
     delete query.$flatten
     const { $embed } = query
     if (query.$count) {
diff --git a/node_modules/rest-hapi/utilities/joi-mongoose-helper.js b/node_modules/rest-hapi/utilities/joi-mongoose-helper.js
index 1a076eb..e230021 100644
--- a/node_modules/rest-hapi/utilities/joi-mongoose-helper.js
+++ b/node_modules/rest-hapi/utilities/joi-mongoose-helper.js
@@ -337,6 +337,8 @@ internals.generateJoiListQueryModel = function(model, logger) {
         .optional()
         .description('An optional field for raw mongoose queries.')
     }
+    queryModel.$startDate = Joi.date().description( 'The start of the date range.' ).optional()
+    queryModel.$endDate = Joi.date().description( 'The end of the date range.' ).optional()

     _.each(queryableFields, function(fieldName) {
       const joiModel = internals.generateJoiModelFromFieldType(

This issue body was partially generated by patch-package.

JKHeadley commented 2 years ago

@alsabbahy thanks for this! I'll work on integrating this functionality into the tool.