forked from TeamCodeStream/codestream-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_request.js
More file actions
255 lines (226 loc) · 6.96 KB
/
Copy pathapi_request.js
File metadata and controls
255 lines (226 loc) · 6.96 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// base class for all incoming requests
// this class provides the basis for the flow of a typical request, from initialization to authorization to processing
// to data persistence, etc.
'use strict';
const APIRequestData = require('./api_request_data');
const ErrorHandler = require(process.env.CSSVC_BACKEND_ROOT + '/shared/server_utils/error_handler');
class APIRequest {
constructor (options = {}) {
Object.assign(this, options);
this.responseIssued = false; // this gets set when once the response has been issued
this.responseData = {}; // prepare for any response data to be put in here
this.transforms = {}; // prepare for any transforms by the request to be put in here
this.data = new APIRequestData({ // wrapper for all collections relevant to this request
api: this.api,
request: this.request
});
this.user = this.request.user; // current user
this._setRequestPhases();
}
// Default requests have at least these phases
// Derived requests can override this behavior either by overriding the method in question or by changing the
// whole structure of the request ... for consistency it is recommended to change the structure only when necessary to
// suit a specialized application ... in general this structure should work very well for the vast majority of requests
_setRequestPhases () {
this.REQUEST_PHASES = [
// initializion of data
'initialize',
// a priori authorization of the request (ACL)
'authorize',
// process the request, this is the meat of it
'process',
// any changes are written to the database here
'persist',
// send the response back to the client
'handleResponse',
// do any post-processing, meaning any processing of the request that goes on after the response is sent back to the client
'postProcess',
// perform any additional persistence to the database, same as persist but here it is recognized that we have already sent
// a response to the client
'postProcessPersist',
// final cleanup
'cleanup',
// close the request
'close'
];
// This indicates the phase that handles a response, this phase will get executed regardless of the output of other phases
this.RESPONSE_PHASE = 'handleResponse';
}
// execute a request phase
async executePhase (phase) {
if (typeof this[phase] !== 'function') {
return;
}
// for monitoring, start a new segment (or span?) for every phase
if (this.api.services.newrelic) {
await new Promise((resolve, reject) => {
this.api.services.newrelic.startSegment(phase, true, async () => {
try {
await this[phase]();
} catch (eee){
reject(eee);
}
resolve();
});
});
} else {
await this[phase]();
}
if (phase === this.RESPONSE_PHASE) {
this.responseIssued = true;
}
}
// initialize the request
async initialize () {
if (this.request.abortWith) {
// middleware error
this.statusCode = this.request.abortWith.status;
throw this.request.abortWith.error;
}
this.request.keepOpen = true;
await this.makeData();
}
// make the local data cache for this request
async makeData () {
await this.data.makeData();
if (this.data.users && this.user) {
// if we've authenticated the request and matched to a user,
// we can add that user to the cache here
this.data.users.addModelToCache(this.user);
}
}
// finish with this request
async finish (error) {
// must execute the response phase, no matter what!
if (
error &&
!this.responseIssued &&
typeof this[this.RESPONSE_PHASE] === 'function'
) {
this.gotError = error;
try {
await this[this.RESPONSE_PHASE]();
}
catch (responsePhaseError) {
if (responsePhaseError) {
this.error('Error handling response: ' + responsePhaseError);
this.reportError(responsePhaseError);
}
}
}
else if (error) {
this.warn(ErrorHandler.log(error));
}
if (error) {
this.close();
}
}
// fulfill the request
async fulfill () {
this.responseIssued = false;
// execute each phase of the request, aborting at any time on error
let gotError;
for (let i in this.REQUEST_PHASES) {
const phase = this.REQUEST_PHASES[i];
try {
await this.executePhase(phase);
}
catch (error) {
gotError = error;
break;
}
}
await this.finish(gotError);
}
// deauthorize this request by sending a 403 (or other status code explicitly set by the request)
deauthorize (error, statusCode) {
this.statusCode = statusCode || 403;
this.responseData = error || 'not authorized'; // set the response to the error
}
// default authorize function, authorize the request (which by default means forbidding the request, this function should be overridden!)
async authorize () {
// don't authorize by default, this must be overridden for proper ACL
this.warn(`Default ACL check fails, override authorize() method for this request: ${this.request.method} ${this.request.url}`);
this.deauthorize();
throw true;
}
// persist all database changes to the database
async persist () {
await this.data.persist();
}
// persist all database changes to the database, after the request has been fully processed
async postProcessPersist () {
// nothing different to do here
await this.persist();
}
// handle the request response
async handleResponse () {
if (this.gotError) {
return await this.handleErrorResponse();
}
else if (this.responseHandled) {
return;
}
this.statusCode = this.statusCode || 200;
this.response.
set('X-Request-Id', this.request.id).
status(this.statusCode).
send(this.responseData);
}
// handle an error that occurred during the request processing
async handleErrorResponse () {
if (!this.statusCode) {
if (
(this.gotError && !this.gotError.code) ||
(typeof this.gotError === 'object' && this.gotError.internal)
) {
this.statusCode = 500; // internal errors get a 500
this.reportError(this.gotError);
}
else {
this.statusCode = 403; // others get a 403
}
}
this.warn(ErrorHandler.log(this.gotError));
this.responseData = ErrorHandler.toClient(this.gotError);
this.response.set('X-Request-Id', this.request.id);
this.response.status(this.statusCode).send(this.responseData);
}
// report error to monitoring service
reportError (error) {
if (this.api.services.newrelic) {
this.api.services.newrelic.noticeError(error);
}
}
// close out this request
async close () {
if (this.response) {
this.response.emit('complete');
}
this.closed = true;
}
// does this request have a "for testing" header?
isForTesting () {
return !!(
this.request &&
this.request.headers &&
this.request.headers['x-cs-test-num']
);
}
critical (text) {
this.api.logger.critical(text, this.request.id);
}
error (text) {
this.api.logger.error(text, this.request.id);
}
warn (text) {
this.api.logger.warn(text, this.request.id);
}
log (text) {
this.api.logger.log(text, this.request.id);
}
debug (text) {
this.api.logger.debug(text, this.request.id);
}
}
module.exports = APIRequest;