-
Notifications
You must be signed in to change notification settings - Fork 4
/
api-service.ts
167 lines (154 loc) · 7.29 KB
/
api-service.ts
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
import { APIGatewayEvent, Callback, Context } from 'aws-lambda';
import { CachedDB, isServiceKnown, mongodbService } from './src/api/service';
import { ServiceNames } from './src/service-names';
import { config } from './src/api/config';
import { buildError, buildResponse } from './src/api/response-util';
import { getBlips, getBlipsForReVote } from './src/services/blips-service';
import { logError, logDebug, logInfo } from './src/lib/utils';
import { inspect } from 'util';
const cachedDb: CachedDB = { dbName: config.dbname, db: null, client: null };
// each service called should return a Object with 1 property
export function _executeService(event: APIGatewayEvent, context: Context, callback: Callback<any>) {
const ipAddress = event.requestContext.identity.sourceIp;
const postBody = JSON.parse(event.body);
let service = ServiceNames.noservice;
let serviceName = 'noservice';
if (postBody && postBody.service) {
serviceName = postBody.service;
service = ServiceNames[serviceName];
}
let serviceResult: any;
if (service === ServiceNames.alive) {
logDebug('I pass through here ' + ServiceNames[service]);
serviceResult = { alive: `true` };
sendResponse(serviceName, serviceResult, callback);
} else if (isServiceKnown(service)) {
// https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
// https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs
logDebug('I pass through here ' + ServiceNames[service]);
if (!cachedDb.db) {
logDebug('Connect to the db ' + cachedDb);
}
context.callbackWaitsForEmptyEventLoop = false;
mongodbService(cachedDb, service, postBody, ipAddress).subscribe(
serviceResult => sendResponse(serviceName, serviceResult, callback),
error => {
logError('error in the mongodbService execution: ' + inspect(error));
sendError(serviceName, error, callback, 200);
},
() => logDebug('Mongo service ' + ServiceNames[service] + ' executed'),
);
} else if (service === ServiceNames.noservice) {
logDebug('I pass through here ' + ServiceNames[service]);
serviceResult = { error: `No Service received` };
sendResponse(serviceName, serviceResult, callback);
} else {
logDebug('I pass through here ' + 'default');
serviceResult = { error: `Service ${serviceName} not defined` };
sendResponse(serviceName, serviceResult, callback);
}
}
let buildCsvResponse = function(params: any, service: ServiceNames, ipAddress, callback: Callback<any>) {
getBlips(cachedDb, service, params, ipAddress).subscribe(
serviceResult => sendCsvResponse(serviceResult, callback),
error => {
logError('executeMongoService error ' + inspect(error));
sendError(service.toString(), error, callback, 300);
},
() => logDebug('Mongo service ' + ServiceNames[service] + ' executed'),
);
};
let buildCsvResponseForRevote = function(params: any, service: ServiceNames, ipAddress, callback: Callback<any>) {
getBlipsForReVote(cachedDb, service, params, ipAddress).subscribe(
serviceResult => sendCsvResponse(serviceResult, callback),
error => {
logError('executeMongoService error ' + inspect(error));
sendError(service.toString(), error, callback, 300);
},
() => logDebug('Mongo service ' + ServiceNames[service] + ' executed'),
);
};
function extractUrlParams(event: APIGatewayEvent) {
if (event.queryStringParameters) {
return {
baseUrl: event.queryStringParameters['serviceUrl'] || '',
radarUrl: event.queryStringParameters['radarUrl'] || '',
};
}
return { baseUrl: '', radarUrl: '' };
}
export function getAllBlips(event: APIGatewayEvent, context: Context, callback: Callback<any>) {
const ipAddress = event.requestContext.identity.sourceIp;
context.callbackWaitsForEmptyEventLoop = false;
let service = ServiceNames.calculateBlipsFromAllEvents;
logDebug('executing getting all blips with service: ' + ServiceNames.calculateBlipsFromAllEvents);
const urlParams = extractUrlParams(event);
let params = {
...urlParams,
thresholdForRevote: event.queryStringParameters
? event.queryStringParameters['thresholdForRevote']
: config.thresholdForRevote,
};
buildCsvResponse(params, service, ipAddress, callback);
}
export function getBlipsForEvent(event: APIGatewayEvent, context: Context, callback: Callback<any>) {
const ipAddress = event.requestContext.identity.sourceIp;
context.callbackWaitsForEmptyEventLoop = false;
let params = {
votingEvent: { _id: event.pathParameters['id'] },
thresholdForRevote: event.queryStringParameters
? event.queryStringParameters['thresholdForRevote']
: config.thresholdForRevote,
};
let service = ServiceNames.calculateBlips;
logDebug('executing getting blips per event with service: ' + ServiceNames.calculateBlips);
buildCsvResponse(params, service, ipAddress, callback);
}
export function getBlipsForRevote(event: APIGatewayEvent, context: Context, callback: Callback<any>) {
const ipAddress = event.requestContext.identity.sourceIp;
context.callbackWaitsForEmptyEventLoop = false;
let params = {
votingEvent: { _id: event.pathParameters['id'] },
thresholdForRevote: event.queryStringParameters
? event.queryStringParameters['thresholdForRevote']
: config.thresholdForRevote,
};
let service = ServiceNames.calculateBlips;
logDebug('executing getting blips for revote per event with service: ' + ServiceNames.calculateBlips);
buildCsvResponseForRevote(params, service, ipAddress, callback);
}
function sendCsvResponse(serviceResult: any, callback: Callback<any>, statusCode: number = 200) {
logInfo('response: ' + serviceResult);
const response = {
statusCode,
body: serviceResult,
};
addHeadersForCORS(response);
logInfo('response sent' + response);
callback(null, response);
}
function sendResponse(serviceName: string, serviceResult: any, callback: Callback<any>, statusCode: number = 200) {
const responseObj = buildResponse(serviceName, statusCode, serviceResult);
send(responseObj, callback, statusCode);
}
function sendError(serviceName: string, error: any, callback: Callback<any>, statusCode: number = 200) {
const responseObj = buildError(serviceName, error, statusCode);
send(responseObj, callback, statusCode);
}
function send(responseObj: any, callback: Callback<any>, statusCode: number = 200) {
const response = {
statusCode,
body: JSON.stringify(responseObj),
};
addHeadersForCORS(response);
logInfo('response sent' + response);
callback(null, response);
}
function addHeadersForCORS(response) {
response.headers = {
'Access-Control-Allow-Origin': '*', // Required for CORS support to work
// "Access-Control-Allow-Methods" : 'GET,PUT,POST,DELETE',
// "Access-Control-Allow-Headers" : "X-Requested-With, Content-Type",
'Access-Control-Allow-Credentials': true, // Required for cookies, authorization headers with HTTPS
};
}