vanta-api 1.2.7 → 1.3.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/api-features.js +40 -11
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vanta-api",
3
- "version": "1.2.7",
3
+ "version": "1.3.0",
4
4
  "description": "Advanced API features and security configuration for Node.js/MongoDB.",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -15,10 +15,14 @@ const logger = winston.createLogger({
15
15
  });
16
16
 
17
17
  export class ApiFeatures {
18
- constructor(model, query = {}, userRole = "guest") {
18
+ constructor(model, query = {}, userRole = "") {
19
19
  this.model = model;
20
20
  this.query = { ...query };
21
- this.userRole = userRole;
21
+ if (!userRole || ! Object.keys(securityConfig.accessLevels).includes(userRole)) {
22
+ this.userRole = 'guest';
23
+ } else {
24
+ this.userRole = userRole;
25
+ }
22
26
 
23
27
  this.pipeline = [];
24
28
  this.countPipeline = [];
@@ -62,21 +66,46 @@ export class ApiFeatures {
62
66
  return this;
63
67
  }
64
68
 
65
- limitFields() {
66
- if (!this.query.fields) return this;
67
- const validFields = Object.keys(this.model.schema.paths).filter(
68
- (f) => !securityConfig.forbiddenFields.includes(f)
69
- );
70
- const project = {};
69
+ limitFields(input = "") {
70
+ const rawFields = [input, this.query.fields].filter(Boolean).join(",");
71
+ if (!rawFields) return this;
72
+
73
+ const validFields = Object.keys(this.model.schema.paths).filter(
74
+ (f) => !securityConfig.forbiddenFields.includes(f)
75
+ );
76
+
77
+ const fieldsArray = rawFields
78
+ .split(",")
79
+ .map((f) => f.trim())
80
+ .filter(Boolean);
81
+
82
+ const includeFields = new Set();
83
+ const excludeFields = new Set();
84
+
85
+ fieldsArray.forEach((f) => {
86
+ if (f.startsWith("-")) excludeFields.add(f.slice(1));
87
+ else includeFields.add(f);
88
+ });
71
89
 
72
- this.query.fields.split(",").forEach((f) => {
90
+ const project = {};
91
+
92
+ if (includeFields.size > 0) {
93
+ includeFields.forEach((f) => {
73
94
  if (validFields.includes(f)) project[f] = 1;
74
95
  });
96
+ } else if (excludeFields.size > 0) {
97
+ validFields.forEach((f) => {
98
+ if (!excludeFields.has(f)) project[f] = 1;
99
+ });
100
+ }
75
101
 
76
- if (Object.keys(project).length) this.pipeline.push({ $project: project });
77
- return this;
102
+ if (Object.keys(project).length) {
103
+ this.pipeline.push({ $project: project });
78
104
  }
79
105
 
106
+ return this;
107
+ }
108
+
80
109
  paginate() {
81
110
  const { maxLimit } = securityConfig.accessLevels[this.userRole] || {
82
111
  maxLimit: 100,