c2-mongoose 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +92 -0
- package/dist/src/configuration/Environment.js +5 -0
- package/dist/src/index.js +27 -0
- package/dist/src/model/Search.js +174 -0
- package/dist/src/utils/Utils.js +56 -0
- package/package.json +28 -0
- package/src/configuration/Environment.ts +3 -0
- package/src/index.ts +1 -0
- package/src/model/Search.ts +208 -0
- package/src/types/SearchResponse.d.ts +10 -0
- package/src/utils/Utils.ts +57 -0
- package/tsconfig.json +104 -0
package/README.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# c2-mongoose
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
## Getting started
|
|
6
|
+
|
|
7
|
+
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
|
8
|
+
|
|
9
|
+
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
|
10
|
+
|
|
11
|
+
## Add your files
|
|
12
|
+
|
|
13
|
+
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
|
14
|
+
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
cd existing_repo
|
|
18
|
+
git remote add origin https://gitlab.com/cabral_consultoria/c2-mongoose.git
|
|
19
|
+
git branch -M main
|
|
20
|
+
git push -uf origin main
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Integrate with your tools
|
|
24
|
+
|
|
25
|
+
- [ ] [Set up project integrations](https://gitlab.com/cabral_consultoria/c2-mongoose/-/settings/integrations)
|
|
26
|
+
|
|
27
|
+
## Collaborate with your team
|
|
28
|
+
|
|
29
|
+
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
|
30
|
+
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
|
31
|
+
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
|
32
|
+
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
|
33
|
+
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
|
34
|
+
|
|
35
|
+
## Test and Deploy
|
|
36
|
+
|
|
37
|
+
Use the built-in continuous integration in GitLab.
|
|
38
|
+
|
|
39
|
+
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
|
40
|
+
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
|
41
|
+
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
|
42
|
+
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
|
43
|
+
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
|
44
|
+
|
|
45
|
+
***
|
|
46
|
+
|
|
47
|
+
# Editing this README
|
|
48
|
+
|
|
49
|
+
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
|
50
|
+
|
|
51
|
+
## Suggestions for a good README
|
|
52
|
+
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
|
53
|
+
|
|
54
|
+
## Name
|
|
55
|
+
Choose a self-explaining name for your project.
|
|
56
|
+
|
|
57
|
+
## Description
|
|
58
|
+
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
|
59
|
+
|
|
60
|
+
## Badges
|
|
61
|
+
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
|
62
|
+
|
|
63
|
+
## Visuals
|
|
64
|
+
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
|
65
|
+
|
|
66
|
+
## Installation
|
|
67
|
+
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
|
68
|
+
|
|
69
|
+
## Usage
|
|
70
|
+
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
|
71
|
+
|
|
72
|
+
## Support
|
|
73
|
+
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
|
74
|
+
|
|
75
|
+
## Roadmap
|
|
76
|
+
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
|
77
|
+
|
|
78
|
+
## Contributing
|
|
79
|
+
State if you are open to contributions and what your requirements are for accepting them.
|
|
80
|
+
|
|
81
|
+
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
|
82
|
+
|
|
83
|
+
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
|
84
|
+
|
|
85
|
+
## Authors and acknowledgment
|
|
86
|
+
Show your appreciation to those who have contributed to the project.
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
For open source projects, say how it is licensed.
|
|
90
|
+
|
|
91
|
+
## Project status
|
|
92
|
+
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.Search = void 0;
|
|
27
|
+
exports.Search = __importStar(require("./model/Search"));
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
const Environment_1 = require("../configuration/Environment");
|
|
13
|
+
const Utils_1 = require("../utils/Utils");
|
|
14
|
+
class Search {
|
|
15
|
+
constructor(params) {
|
|
16
|
+
this.buildPopulate = () => {
|
|
17
|
+
if ((0, Utils_1.isEmpty)(this.populate)) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
var propertiesArray = this.populate.split(',');
|
|
21
|
+
var populates = [];
|
|
22
|
+
for (var property of propertiesArray) {
|
|
23
|
+
let [first, ...rest] = property.split('.');
|
|
24
|
+
let nested = rest.join('.');
|
|
25
|
+
populates.push(this.buildPath(first, nested));
|
|
26
|
+
}
|
|
27
|
+
this.populate = populates;
|
|
28
|
+
};
|
|
29
|
+
this.buildPath = (target, nested = "") => {
|
|
30
|
+
var populate = {};
|
|
31
|
+
populate.path = target;
|
|
32
|
+
if ((0, Utils_1.isNotEmpty)(nested)) {
|
|
33
|
+
let [first, ...rest] = nested.split('.');
|
|
34
|
+
let nested2 = rest.join('.');
|
|
35
|
+
populate.populate = this.buildPath(first, nested2);
|
|
36
|
+
}
|
|
37
|
+
return populate;
|
|
38
|
+
};
|
|
39
|
+
this.buildOrdenation = () => {
|
|
40
|
+
let order = {};
|
|
41
|
+
this.orderBy = this.orderBy || "_id";
|
|
42
|
+
order[this.orderBy] = this.order === "desc" ? -1 : 1;
|
|
43
|
+
return order;
|
|
44
|
+
};
|
|
45
|
+
this.isPageable = () => {
|
|
46
|
+
if (this.page >= 0) {
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
return false;
|
|
50
|
+
};
|
|
51
|
+
this.diacriticSensitiveRegex = (string = "") => {
|
|
52
|
+
return string
|
|
53
|
+
.replace(/[a|á|à|ä|â|A|Á|Â|Ã|Ä]/g, '[a,á,à,ä,â,A,Á,Â,Ã,Ä]')
|
|
54
|
+
.replace(/[e|é|ë|è|E|É|Ë|È]/g, '[e,é,ë,è,E,É,Ë,È]')
|
|
55
|
+
.replace(/[i|í|ï|ì|I|Í|Ï|Ì]/g, '[i,í,ï,ì,I,Í,Ï,Ì]')
|
|
56
|
+
.replace(/[o|ó|ö|ò|õ|O|Ó|Ö|Ô|Õ]/g, '[o,ó,ö,ò,õ,O,Ó,Ö,Ô,Õ]')
|
|
57
|
+
.replace(/[u|ü|ú|ù|U|Ú|Ü|Ù]/g, '[u,ü,ú,ù,U,Ú,Ü,Ù]')
|
|
58
|
+
.replace(/[ç|Ç|c|C]/g, '[c,C,ç,Ç]');
|
|
59
|
+
};
|
|
60
|
+
this.search = (model) => __awaiter(this, void 0, void 0, function* () {
|
|
61
|
+
if (this.isPageable()) {
|
|
62
|
+
return yield this.searchPageable(model);
|
|
63
|
+
}
|
|
64
|
+
return yield this.searchNoPageable(model);
|
|
65
|
+
});
|
|
66
|
+
this.searchPageable = (model) => __awaiter(this, void 0, void 0, function* () {
|
|
67
|
+
const sort = this.buildOrdenation();
|
|
68
|
+
var items = yield model
|
|
69
|
+
.find(this.filters, this.select)
|
|
70
|
+
.populate(this.populate)
|
|
71
|
+
.skip(this.page * this.limit)
|
|
72
|
+
.limit(this.limit)
|
|
73
|
+
.sort(sort)
|
|
74
|
+
.collation({
|
|
75
|
+
locale: Environment_1.dbCollation || "pt"
|
|
76
|
+
});
|
|
77
|
+
return this.result(model, items);
|
|
78
|
+
});
|
|
79
|
+
this.searchNoPageable = (model) => __awaiter(this, void 0, void 0, function* () {
|
|
80
|
+
const sort = this.buildOrdenation();
|
|
81
|
+
var items = yield model
|
|
82
|
+
.find(this.filters, this.select)
|
|
83
|
+
.populate(this.populate)
|
|
84
|
+
.sort(sort)
|
|
85
|
+
.collation({
|
|
86
|
+
locale: Environment_1.dbCollation || "pt"
|
|
87
|
+
});
|
|
88
|
+
return this.result(model, items);
|
|
89
|
+
});
|
|
90
|
+
this.result = (model, items) => __awaiter(this, void 0, void 0, function* () {
|
|
91
|
+
var total = yield this.count(model);
|
|
92
|
+
var paging = {};
|
|
93
|
+
paging.total = total;
|
|
94
|
+
paging.page = this.page;
|
|
95
|
+
paging.limit = this.limit;
|
|
96
|
+
var searchResponse = {};
|
|
97
|
+
searchResponse.items = items;
|
|
98
|
+
searchResponse.paging = paging;
|
|
99
|
+
return searchResponse;
|
|
100
|
+
});
|
|
101
|
+
this.count = (model) => __awaiter(this, void 0, void 0, function* () {
|
|
102
|
+
return yield model.countDocuments(this.filters).exec();
|
|
103
|
+
});
|
|
104
|
+
this.sumBy = (model, _sum, _by) => __awaiter(this, void 0, void 0, function* () {
|
|
105
|
+
const ret = yield model.aggregate([
|
|
106
|
+
{
|
|
107
|
+
'$match': this.filters
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
$group: {
|
|
111
|
+
_id: _by,
|
|
112
|
+
totalValue: { "$sum": _sum },
|
|
113
|
+
count: { "$sum": 1 }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
]);
|
|
117
|
+
return ret;
|
|
118
|
+
});
|
|
119
|
+
this.buildDefaultFilters = (objectSearch) => {
|
|
120
|
+
let filters = { $and: [] };
|
|
121
|
+
Object.entries(objectSearch).forEach(([key, value]) => {
|
|
122
|
+
if ((0, Utils_1.isNotEmpty)(value)) {
|
|
123
|
+
let condition = {};
|
|
124
|
+
if (['order', 'orderBy', 'properties', 'populate', 'page', 'limit', 'model', 'searchText'].includes(key)) {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (key.endsWith('DateRange')) {
|
|
128
|
+
var keyAux = key.replace('Range', '');
|
|
129
|
+
var values = value;
|
|
130
|
+
if ((0, Utils_1.isNotEmpty)(values[0])) {
|
|
131
|
+
condition[keyAux] = Object.assign(Object.assign({}, condition[keyAux]), { $gte: new Date(values[0]) });
|
|
132
|
+
}
|
|
133
|
+
if ((0, Utils_1.isNotEmpty)(values[1])) {
|
|
134
|
+
condition[keyAux] = Object.assign(Object.assign({}, condition[keyAux]), { $lte: new Date(values[1]) });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
if (!Array.isArray(value)) {
|
|
139
|
+
condition[key] = value;
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
condition[key] = { $in: value };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
filters.$and.push(condition);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
if ((0, Utils_1.isNotEmpty)(objectSearch.model)) {
|
|
149
|
+
this.addFilterModel(objectSearch.model, filters);
|
|
150
|
+
}
|
|
151
|
+
if (filters.$and.length === 0)
|
|
152
|
+
delete filters['$and'];
|
|
153
|
+
return filters;
|
|
154
|
+
};
|
|
155
|
+
this.addFilterModel = (model, filters) => {
|
|
156
|
+
Object.entries(model).forEach(([key, value]) => {
|
|
157
|
+
if ((0, Utils_1.isNotEmpty)(value)) {
|
|
158
|
+
let condition = {};
|
|
159
|
+
condition[key] = value;
|
|
160
|
+
filters.$and.push(condition);
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
};
|
|
164
|
+
this.searchText = params.searchText || "";
|
|
165
|
+
this.order = params.order || "asc";
|
|
166
|
+
this.orderBy = params.orderBy || "_id";
|
|
167
|
+
this.select = params.select;
|
|
168
|
+
this.populate = params.populate;
|
|
169
|
+
this.page = params.page || -1;
|
|
170
|
+
this.limit = params.limit || 25;
|
|
171
|
+
this.buildPopulate();
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
exports.default = Search;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.compareDesc = exports.compareAsc = exports.isNotIterable = exports.isIterable = exports.isEmpty = exports.isNotEmpty = void 0;
|
|
4
|
+
const isNotEmpty = (obj) => {
|
|
5
|
+
return !(0, exports.isEmpty)(obj);
|
|
6
|
+
};
|
|
7
|
+
exports.isNotEmpty = isNotEmpty;
|
|
8
|
+
const isEmpty = (obj) => {
|
|
9
|
+
if (!obj) {
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
if (Array.isArray(obj)) {
|
|
13
|
+
if (obj.length == 0) {
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
if (obj === "") {
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
return false;
|
|
21
|
+
};
|
|
22
|
+
exports.isEmpty = isEmpty;
|
|
23
|
+
const isIterable = (input) => {
|
|
24
|
+
if (input === null || input === undefined) {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
if ('string' === typeof input) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
return typeof input[Symbol.iterator] === 'function';
|
|
31
|
+
};
|
|
32
|
+
exports.isIterable = isIterable;
|
|
33
|
+
const isNotIterable = (input) => {
|
|
34
|
+
return !(0, exports.isIterable)(input);
|
|
35
|
+
};
|
|
36
|
+
exports.isNotIterable = isNotIterable;
|
|
37
|
+
const compareAsc = (a, b) => {
|
|
38
|
+
if (a._id < b._id) {
|
|
39
|
+
return -1;
|
|
40
|
+
}
|
|
41
|
+
if (a._id > b._id) {
|
|
42
|
+
return 1;
|
|
43
|
+
}
|
|
44
|
+
return 0;
|
|
45
|
+
};
|
|
46
|
+
exports.compareAsc = compareAsc;
|
|
47
|
+
const compareDesc = (a, b) => {
|
|
48
|
+
if (a._id > b._id) {
|
|
49
|
+
return -1;
|
|
50
|
+
}
|
|
51
|
+
if (a._id < b._id) {
|
|
52
|
+
return 1;
|
|
53
|
+
}
|
|
54
|
+
return 0;
|
|
55
|
+
};
|
|
56
|
+
exports.compareDesc = compareDesc;
|
package/package.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "c2-mongoose",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Lib to make any search in database mongoose and use as basic crud",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://gitlab.com/cabral_consultoria/c2-mongoose.git"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"mongoose",
|
|
16
|
+
"crud"
|
|
17
|
+
],
|
|
18
|
+
"author": "Cabral Consultoria e Assessoria em Software",
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://gitlab.com/cabral_consultoria/c2-mongoose/issues"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://gitlab.com/cabral_consultoria/c2-mongoose#readme",
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"dotenv": "^16.0.3",
|
|
26
|
+
"mongoose": "^7.0.1"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * as Search from "./model/Search"
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import mongoose from "mongoose"
|
|
2
|
+
import { dbCollation } from "../configuration/Environment"
|
|
3
|
+
import { isEmpty, isNotEmpty } from "../utils/Utils"
|
|
4
|
+
|
|
5
|
+
abstract class Search {
|
|
6
|
+
searchText: string
|
|
7
|
+
order: string
|
|
8
|
+
orderBy: string
|
|
9
|
+
page: number
|
|
10
|
+
limit: number
|
|
11
|
+
select: string
|
|
12
|
+
populate: string | [] | any
|
|
13
|
+
filters: any
|
|
14
|
+
|
|
15
|
+
constructor(params: any) {
|
|
16
|
+
this.searchText = params.searchText || ""
|
|
17
|
+
this.order = params.order || "asc"
|
|
18
|
+
this.orderBy = params.orderBy || "_id"
|
|
19
|
+
this.select = params.select
|
|
20
|
+
this.populate = params.populate
|
|
21
|
+
this.page = params.page || -1
|
|
22
|
+
this.limit = params.limit || 25
|
|
23
|
+
this.buildPopulate()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
public buildPopulate = (): any => {
|
|
27
|
+
if (isEmpty(this.populate)) {
|
|
28
|
+
return
|
|
29
|
+
}
|
|
30
|
+
var propertiesArray = this.populate.split(',')
|
|
31
|
+
var populates = [] as any
|
|
32
|
+
for (var property of propertiesArray) {
|
|
33
|
+
let [first, ...rest] = property.split('.')
|
|
34
|
+
let nested = rest.join('.')
|
|
35
|
+
populates.push(this.buildPath(first, nested))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
this.populate = populates
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
public buildPath = (target: string, nested: string = "") => {
|
|
42
|
+
var populate = {} as any
|
|
43
|
+
populate.path = target
|
|
44
|
+
if (isNotEmpty(nested)) {
|
|
45
|
+
let [first, ...rest] = nested.split('.')
|
|
46
|
+
let nested2 = rest.join('.')
|
|
47
|
+
populate.populate = this.buildPath(first, nested2)
|
|
48
|
+
}
|
|
49
|
+
return populate
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
public buildOrdenation = () => {
|
|
53
|
+
let order = {} as any
|
|
54
|
+
this.orderBy = this.orderBy || "_id"
|
|
55
|
+
order[this.orderBy] = this.order === "desc" ? -1 : 1
|
|
56
|
+
return order
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
private isPageable = () => {
|
|
60
|
+
if (this.page >= 0) {
|
|
61
|
+
return true
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private diacriticSensitiveRegex = (string = "") => {
|
|
68
|
+
return string
|
|
69
|
+
.replace(/[a|á|à|ä|â|A|Á|Â|Ã|Ä]/g, '[a,á,à,ä,â,A,Á,Â,Ã,Ä]')
|
|
70
|
+
.replace(/[e|é|ë|è|E|É|Ë|È]/g, '[e,é,ë,è,E,É,Ë,È]')
|
|
71
|
+
.replace(/[i|í|ï|ì|I|Í|Ï|Ì]/g, '[i,í,ï,ì,I,Í,Ï,Ì]')
|
|
72
|
+
.replace(/[o|ó|ö|ò|õ|O|Ó|Ö|Ô|Õ]/g, '[o,ó,ö,ò,õ,O,Ó,Ö,Ô,Õ]')
|
|
73
|
+
.replace(/[u|ü|ú|ù|U|Ú|Ü|Ù]/g, '[u,ü,ú,ù,U,Ú,Ü,Ù]')
|
|
74
|
+
.replace(/[ç|Ç|c|C]/g, '[c,C,ç,Ç]')
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
public search = async (model: mongoose.Model<any>): Promise<SearchResponse<any>> => {
|
|
78
|
+
if (this.isPageable()) {
|
|
79
|
+
return await this.searchPageable(model)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return await this.searchNoPageable(model)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private searchPageable = async (model: mongoose.Model<any>): Promise<SearchResponse<any>> => {
|
|
86
|
+
const sort = this.buildOrdenation()
|
|
87
|
+
var items = await model
|
|
88
|
+
.find(this.filters, this.select)
|
|
89
|
+
.populate(this.populate)
|
|
90
|
+
.skip(this.page * this.limit)
|
|
91
|
+
.limit(this.limit)
|
|
92
|
+
.sort(sort)
|
|
93
|
+
.collation({
|
|
94
|
+
locale: dbCollation || "pt"
|
|
95
|
+
}) as []
|
|
96
|
+
|
|
97
|
+
return this.result(model, items)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
private searchNoPageable = async (model: mongoose.Model<any>): Promise<SearchResponse<any>> => {
|
|
101
|
+
const sort = this.buildOrdenation()
|
|
102
|
+
var items = await model
|
|
103
|
+
.find(this.filters, this.select)
|
|
104
|
+
.populate(this.populate)
|
|
105
|
+
.sort(sort)
|
|
106
|
+
.collation({
|
|
107
|
+
locale: dbCollation || "pt"
|
|
108
|
+
}) as []
|
|
109
|
+
|
|
110
|
+
return this.result(model, items)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private result = async (model: mongoose.Model<any>, items: []): Promise<SearchResponse<any>> => {
|
|
114
|
+
var total = await this.count(model)
|
|
115
|
+
|
|
116
|
+
var paging: Paging = {}
|
|
117
|
+
paging.total = total
|
|
118
|
+
paging.page = this.page
|
|
119
|
+
paging.limit = this.limit
|
|
120
|
+
|
|
121
|
+
var searchResponse: SearchResponse<any> = {}
|
|
122
|
+
searchResponse.items = items
|
|
123
|
+
searchResponse.paging = paging
|
|
124
|
+
|
|
125
|
+
return searchResponse
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
public count = async (model: mongoose.Model<any>): Promise<number> => {
|
|
129
|
+
return await model.countDocuments(this.filters).exec()
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
public sumBy = async (model: mongoose.Model<any>, _sum: any, _by: any): Promise<any[]> => {
|
|
133
|
+
const ret = await model.aggregate(
|
|
134
|
+
[
|
|
135
|
+
{
|
|
136
|
+
'$match': this.filters
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
$group: {
|
|
140
|
+
_id: _by,
|
|
141
|
+
totalValue: { "$sum": _sum },
|
|
142
|
+
count: { "$sum": 1 }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
]
|
|
146
|
+
)
|
|
147
|
+
return ret
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
public buildDefaultFilters = (objectSearch: any) => {
|
|
151
|
+
let filters = { $and: [] } as any
|
|
152
|
+
Object.entries(objectSearch).forEach(([key, value]) => {
|
|
153
|
+
if (isNotEmpty(value)) {
|
|
154
|
+
let condition = {} as any
|
|
155
|
+
if (['order', 'orderBy', 'properties', 'populate', 'page', 'limit', 'model', 'searchText'].includes(key)) {
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (key.endsWith('DateRange')) {
|
|
160
|
+
var keyAux = key.replace('Range', '')
|
|
161
|
+
var values = value as any
|
|
162
|
+
if (isNotEmpty(values[0])) {
|
|
163
|
+
condition[keyAux] = {
|
|
164
|
+
...condition[keyAux],
|
|
165
|
+
$gte: new Date(values[0])
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (isNotEmpty(values[1])) {
|
|
170
|
+
condition[keyAux] = {
|
|
171
|
+
...condition[keyAux],
|
|
172
|
+
$lte: new Date(values[1])
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
} else {
|
|
176
|
+
if (!Array.isArray(value)) {
|
|
177
|
+
condition[key] = value
|
|
178
|
+
} else {
|
|
179
|
+
condition[key] = { $in: value }
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
filters.$and.push(condition)
|
|
183
|
+
}
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
if (isNotEmpty(objectSearch.model)) {
|
|
188
|
+
this.addFilterModel(objectSearch.model, filters)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (filters.$and.length === 0)
|
|
192
|
+
delete filters['$and']
|
|
193
|
+
|
|
194
|
+
return filters
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
public addFilterModel = (model: any, filters: any) => {
|
|
198
|
+
Object.entries(model).forEach(([key, value]) => {
|
|
199
|
+
if (isNotEmpty(value)) {
|
|
200
|
+
let condition = {} as any
|
|
201
|
+
condition[key] = value
|
|
202
|
+
filters.$and.push(condition)
|
|
203
|
+
}
|
|
204
|
+
})
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export default Search
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export const isNotEmpty = (obj: any) => {
|
|
2
|
+
return !isEmpty(obj)
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export const isEmpty = (obj: any) => {
|
|
6
|
+
if (!obj) {
|
|
7
|
+
return true
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
if (Array.isArray(obj)) {
|
|
11
|
+
if (obj.length == 0) {
|
|
12
|
+
return true
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (obj === "") {
|
|
17
|
+
return true
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
return false
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const isIterable = (input: any) => {
|
|
24
|
+
if (input === null || input === undefined) {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if ('string' === typeof input) {
|
|
29
|
+
return false
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return typeof input[Symbol.iterator] === 'function'
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const isNotIterable = (input: any) => {
|
|
36
|
+
return !isIterable(input)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const compareAsc = (a: any, b: any) => {
|
|
40
|
+
if (a._id < b._id) {
|
|
41
|
+
return -1;
|
|
42
|
+
}
|
|
43
|
+
if (a._id > b._id) {
|
|
44
|
+
return 1;
|
|
45
|
+
}
|
|
46
|
+
return 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const compareDesc = (a: any, b: any) => {
|
|
50
|
+
if (a._id > b._id) {
|
|
51
|
+
return -1;
|
|
52
|
+
}
|
|
53
|
+
if (a._id < b._id) {
|
|
54
|
+
return 1;
|
|
55
|
+
}
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
{
|
|
2
|
+
"include": [
|
|
3
|
+
"**/*.ts"
|
|
4
|
+
],
|
|
5
|
+
"exclude": [
|
|
6
|
+
"node_modules"
|
|
7
|
+
],
|
|
8
|
+
"buildOnSave": true,
|
|
9
|
+
"compileOnSave": true,
|
|
10
|
+
"declaration": true,
|
|
11
|
+
"compilerOptions": {
|
|
12
|
+
/* Visit https://aka.ms/tsconfig to read more about this file */
|
|
13
|
+
/* Projects */
|
|
14
|
+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
|
15
|
+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
|
16
|
+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
|
17
|
+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
|
18
|
+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
|
19
|
+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
20
|
+
/* Language and Environment */
|
|
21
|
+
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
|
22
|
+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
23
|
+
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
|
24
|
+
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
|
|
25
|
+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
|
26
|
+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
|
27
|
+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
28
|
+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
|
29
|
+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
|
30
|
+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
31
|
+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
32
|
+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
33
|
+
/* Modules */
|
|
34
|
+
"module": "commonjs", /* Specify what module code is generated. */
|
|
35
|
+
"rootDir": "./", /* Specify the root folder within your source files. */
|
|
36
|
+
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
|
|
37
|
+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
38
|
+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
39
|
+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
40
|
+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
41
|
+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
42
|
+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
43
|
+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
44
|
+
// "resolveJsonModule": true, /* Enable importing .json files. */
|
|
45
|
+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
|
46
|
+
/* JavaScript Support */
|
|
47
|
+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
|
48
|
+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
|
49
|
+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
|
50
|
+
/* Emit */
|
|
51
|
+
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
|
52
|
+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
53
|
+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
54
|
+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
55
|
+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
|
56
|
+
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
|
57
|
+
// "removeComments": true, /* Disable emitting comments. */
|
|
58
|
+
// "noEmit": true, /* Disable emitting files from a compilation. */
|
|
59
|
+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
60
|
+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
|
61
|
+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
62
|
+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
63
|
+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
64
|
+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
65
|
+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
66
|
+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
67
|
+
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
68
|
+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
|
69
|
+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
|
70
|
+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
71
|
+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
|
72
|
+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
73
|
+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
|
74
|
+
/* Interop Constraints */
|
|
75
|
+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
76
|
+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
77
|
+
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
|
78
|
+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
79
|
+
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
|
80
|
+
/* Type Checking */
|
|
81
|
+
"strict": true, /* Enable all strict type-checking options. */
|
|
82
|
+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
83
|
+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
84
|
+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
85
|
+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
|
86
|
+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
87
|
+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
|
88
|
+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
|
89
|
+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
90
|
+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
|
91
|
+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
|
92
|
+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
93
|
+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
94
|
+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
95
|
+
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
|
96
|
+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
97
|
+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
|
98
|
+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
99
|
+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
100
|
+
/* Completeness */
|
|
101
|
+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
102
|
+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
103
|
+
}
|
|
104
|
+
}
|