-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontrollerHelpers.js
More file actions
200 lines (172 loc) · 5.55 KB
/
controllerHelpers.js
File metadata and controls
200 lines (172 loc) · 5.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import crypto from 'crypto';
import { convertToArray } from './helpers.js';
/**
* Common parameter validation patterns
*/
const REQUIRED_PARAMS = {
TECHNOLOGY: 'technology',
GEO: 'geo',
RANK: 'rank',
VERSION: 'version'
};
/**
* Validate required parameters for a request
* @param {Object} params - Request query parameters
* @param {Array} required - Array of required parameter names
* @returns {Array|null} - Array of errors or null if valid
*/
const validateRequiredParams = (params, required) => {
const errors = [];
for (const param of required) {
if (!params[param]) {
errors.push([param, `missing ${param} parameter`]);
}
}
return errors.length > 0 ? errors : null;
};
/**
* Send error response for missing parameters
* @param {Object} res - Response object
* @param {Array} errors - Array of error tuples
*/
const sendValidationError = (res, errors) => {
res.statusCode = 400;
res.end(JSON.stringify({
success: false,
errors: errors.map(([key, message]) => ({ [key]: message }))
}));
};
/**
* Get the latest date from a collection
* @param {Object} firestore - Firestore instance
* @param {string} collection - Collection name
* @returns {string|null} - Latest date or null
*/
const getLatestDate = async (firestore, collection) => {
// Query for latest date
const query = firestore.collection(collection).orderBy('date', 'desc').limit(1);
const snapshot = await query.get();
if (!snapshot.empty) {
return snapshot.docs[0].data().date;
}
return null;
};
/**
* Validate array parameter against Firestore limit
* @param {string} value - Comma-separated values or single value
* @param {string} fieldName - Field name for error messages (optional)
* @returns {Array} - Validated array
* @throws {Error} - If array exceeds Firestore limit
*/
const validateArrayParameter = (value, fieldName = 'parameter') => {
if (!value) return [];
const valueArray = convertToArray(value);
if (valueArray.length > FIRESTORE_IN_LIMIT) {
const error = new Error(`Too many values specified for ${fieldName}. Maximum ${FIRESTORE_IN_LIMIT} allowed.`);
error.statusCode = 400;
throw error;
}
return valueArray;
};
/**
* Handle controller errors with consistent error response format
* @param {Object} res - Response object
* @param {Error} error - Error object
* @param {string} operation - Description of the operation that failed
*/
const handleControllerError = (res, error, operation) => {
console.error(`Error ${operation}:`, error);
const statusCode = error.statusCode || 500;
res.statusCode = statusCode;
// Use custom error message for client errors (4xx), generic message for server errors (5xx)
const errorMessage = statusCode >= 400 && statusCode < 500 ? error.message : `Failed to ${operation}`;
res.end(JSON.stringify({
errors: [{ error: errorMessage }]
}));
};
const generateETag = (jsonData) => {
return crypto.createHash('md5').update(jsonData).digest('hex');
};
const sendJSONResponse = (res, data, statusCode = 200) => {
const jsonData = JSON.stringify(data);
const etag = generateETag(jsonData);
res.setHeader('ETag', `"${etag}"`);
res.statusCode = statusCode;
res.end(jsonData);
};
const isModified = (req, etag) => {
const ifNoneMatch = req.headers['if-none-match'] || (req.get && req.get('if-none-match'));
return !ifNoneMatch || ifNoneMatch !== `"${etag}"`;
};
/**
* Generic query executor
* Handles query execution and response for simple queries
* @param {Object} req - Request object
* @param {Object} res - Response object
* @param {string} collection - Firestore collection name
* @param {Function} queryBuilder - Function to build the query
* @param {Function} dataProcessor - Optional function to process results
*/
const executeQuery = async (req, res, collection, queryBuilder, dataProcessor = null) => {
try {
const params = req.query;
// Build and execute query
const query = await queryBuilder(params);
const snapshot = await query.get();
let data = snapshot.docs.map(doc => doc.data());
// Process data if processor provided
if (dataProcessor) {
data = dataProcessor(data, params);
}
// Send response with ETag support
const jsonData = JSON.stringify(data);
const etag = generateETag(jsonData);
res.setHeader('ETag', `"${etag}"`);
if (!isModified(req, etag)) {
res.statusCode = 304;
res.end();
return;
}
res.statusCode = 200;
res.end(jsonData);
} catch (error) {
// Handle validation errors specifically
if (error.message.includes('Too many technologies')) {
res.statusCode = 400;
res.end(JSON.stringify({
success: false,
errors: [{ technology: error.message }]
}));
return;
}
handleControllerError(res, error, `querying ${collection}`);
}
};
// Firestore 'in' operator limit
const FIRESTORE_IN_LIMIT = 30;
/**
* Technology array validation helper (backward compatibility wrapper)
* @param {string} technologyParam - Comma-separated technology string
* @returns {Array|null} - Array of technologies or null if too many
*/
const validateTechnologyArray = (technologyParam) => {
try {
return validateArrayParameter(technologyParam, 'technology');
} catch (error) {
return null; // Maintain backward compatibility - return null on validation failure
}
};
export {
REQUIRED_PARAMS,
FIRESTORE_IN_LIMIT,
validateRequiredParams,
sendValidationError,
getLatestDate,
validateArrayParameter,
handleControllerError,
executeQuery,
validateTechnologyArray,
generateETag,
sendJSONResponse,
isModified
};