nestjsx/crud

Database JSON column and query WHERE support

LucusWebsites opened this issue · 0 comments

Just for future souls who are looking for support for WHERE and database JSON columns.
This patch might help and/or push you in the right direction.
Use at your own risk, it's not thorougly tested!

diff --git a/node_modules/@nestjsx/crud-typeorm/lib/typeorm-crud.service.js b/node_modules/@nestjsx/crud-typeorm/lib/typeorm-crud.service.js
index 541c2a8..6907f5a 100644
--- a/node_modules/@nestjsx/crud-typeorm/lib/typeorm-crud.service.js
+++ b/node_modules/@nestjsx/crud-typeorm/lib/typeorm-crud.service.js
@@ -573,6 +573,10 @@ class TypeOrmCrudService extends crud_1.CrudService {
         if (cond.operator[0] !== '$') {
             cond.operator = ('$' + cond.operator);
         }
+
+        param = param.replaceAll('-', '_')
+        param = param.replaceAll(' ', '_')
+
         switch (cond.operator) {
             case '$eq':
                 str = `${field} = :${param}`;
@@ -666,6 +670,21 @@ class TypeOrmCrudService extends crud_1.CrudService {
                 str = `${field} = :${param}`;
                 break;
         }
+
+        if (field.startsWith('customer.')) {
+            const jsonFieldName = field.substring(9)
+
+            if (str.startsWith('LOWER(')) {
+                const start = str.substring(0, 6)
+                const end = str.substring(6 + field.length)
+                str = start + `JSON_EXTRACT(\`customer\`, '$."${jsonFieldName}"')` + end
+            } else {
+                const start = ''
+                const end = str.substring(field.length)
+                str = start + `JSON_EXTRACT(\`customer\`, '$."${jsonFieldName}"')` + end
+            }
+        }
+
         if (typeof params === 'undefined') {
             params = { [param]: cond.value };
         }