Skip to content

Commit a58ed27

Browse files
committed
Updated handlers
1 parent a95e843 commit a58ed27

File tree

2 files changed

+137
-35
lines changed

2 files changed

+137
-35
lines changed

node/CustomersQueryHandler.js

+84-35
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,106 @@
1-
// Module dependencies
21
const MongoClient = require('mongodb').MongoClient;
3-
4-
// Atlas connection outside of Lambda handler
2+
const ObjectID = require('mongodb').ObjectID;
53
const atlasUri = process.env['MONGODB_ATLAS_CLUSTER_URI'];
64

7-
// Cache DB connection for future use
5+
const COLLNAME = 'Customers';
6+
87
let cachedDb;
98

10-
// AWS event handler
11-
exports.handler = (evt, ctx, cb) => {
9+
exports.GET_handler = (evt, ctx, cb) => {
1210

13-
// Set to false to allow re-use of database connections across lambda calls
14-
// See http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
15-
ctx.callbackWaitsForEmptyEventLoop = false;
11+
// Set to false to allow re-use of database connections across lambda calls
12+
// See http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
13+
ctx.callbackWaitsForEmptyEventLoop = false;
1614

17-
// Executes query
18-
function executeQuery(db, coll, query, options, cb) {
15+
var options = { limit: 50 }; // to-do paging
1916

20-
// Find documents in tasks collection
21-
db.collection(coll).find(query, options).toArray(function(err, docs) {
22-
if (err) process.exit(1);
23-
cb(null, docs);
24-
});
17+
var query = {};
18+
if ('id' in evt) {
19+
query._id = ObjectID.createFromHexString(evt.id);
20+
}
2521

26-
}
22+
executeQuery(cachedDb, COLLNAME, query, options, cb);
23+
};
24+
25+
exports.GET_Renewals_handler = (evt, ctx, cb) => {
2726

28-
try {
27+
// Set to false to allow re-use of database connections across lambda calls
28+
// See http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
29+
ctx.callbackWaitsForEmptyEventLoop = false;
2930

30-
if (!cachedDb || !cachedDb.serverConfig.isConnected()) {
31+
var options = { limit: 50 }; // to-do paging
3132

32-
console.log(`=== CONNECTING TO MONGODB ATLAS ===`);
33+
var query = {};
3334

34-
MongoClient.connect(atlasUri, (err, db) => {
35+
if ('policyType' in evt) {
36+
query['policies.policyType'] = evt.policyType;
37+
}
3538

36-
if (err) {
37-
console.error(`An error occurred! ${err}`);
38-
process.exit(1);
39-
}
39+
if ('expiresInDays' in evt) {
4040

41-
// Assign db connection to variable for further use
42-
cachedDb = db;
41+
var startDt = new Date();
42+
var endDt = new Date(startDt.getTime() + (evt.expiresInDays * 24 * 60 * 60 * 1000));
4343

44-
// Execute query
45-
executeQuery(cachedDb, evt.collection, evt.query, evt.options, cb);
44+
query['policies.nextRenewalDt'] = { '$gte': startDt, '$lte': endDt };
45+
}
4646

47-
});
47+
if (('locLat' in evt) && ('locLon' in evt) && ('mileRadius' in evt)) {
4848

49-
} else {
50-
executeQuery(cachedDb, evt.collection, evt.query, evt.options, cb);
51-
}
49+
var lon = evt.locLon;
50+
var lat = evt.locLat;
51+
var radius = evt.mileRadius / 3959; // to radians
5252

53-
} catch (err) {
54-
console.error(`An error occurred! ${err}`);
53+
var geoQuery = { "$geoWithin" : { "$centerSphere" : [[lat,lon],radius] }};
54+
55+
if ('policyType' in evt) {
56+
switch (evt.policyType) {
57+
58+
case 'home':
59+
query['policies.address.location'] = geoQuery;
60+
break;
61+
62+
case 'auto':
63+
query['address.location'] = geoQuery;
64+
break;
65+
}
5566
}
67+
}
68+
69+
executeQuery(cachedDb, COLLNAME, query, options, cb);
70+
};
71+
72+
function executeQuery(db, collName, query, options, cb) {
73+
74+
function execute(db, collName, query, options, cb) {
75+
76+
console.log('QUERY on ' + collName + ': ' + JSON.stringify(query));
77+
78+
db.collection(collName).find(query, options).toArray(function(err, docs) {
79+
if (err) process.exit(1);
80+
81+
console.log('FOUND ' + docs.length + ' documents.');
82+
83+
cb(null, docs);
84+
});
85+
}
86+
87+
try {
88+
if (!cachedDb || !cachedDb.serverConfig.isConnected()) {
89+
90+
console.log('=== CONNECTING TO MONGODB ATLAS ===');
5691

92+
MongoClient.connect(atlasUri, (err, db) => {
93+
if (err) {
94+
console.error(`An error occurred! ${err}`);
95+
process.exit(1);
96+
}
97+
cachedDb = db;
98+
execute(cachedDb, collName, query, options, cb);
99+
});
100+
} else {
101+
execute(cachedDb, collName, query, options, cb);
102+
}
103+
} catch (err) {
104+
console.error(`An error occurred! ${err}`);
105+
}
57106
}

python/CustomersCommandHandler.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from __future__ import print_function
2+
3+
import datetime
4+
import json
5+
import os
6+
import pymongo
7+
from bson.codec_options import CodecOptions
8+
9+
atlasUri = os.environ['MONGODB_ATLAS_CLUSTER_URI']
10+
11+
# =====================================
12+
# Connection to Atlas outside of Lambda handler(s)
13+
# =====================================
14+
print('Loading function')
15+
print('=== CONNECTING TO MONGODB ATLAS ===')
16+
17+
MONGOCLIENT = pymongo.MongoClient(atlasUri, readPreference='secondaryPreferred')
18+
print("=== DONE - DB NAME: " + MONGOCLIENT.get_default_database().name + " ===")
19+
20+
# ==========================================================
21+
def PATCH_UpdateContactInfo_lambda_handler(event, context):
22+
# ==========================================================
23+
# assures filter element position against index element position
24+
from collections import OrderedDict
25+
filter = OrderedDict()
26+
27+
if 'id' not in event:
28+
raise ValueError('Missing argument: id')
29+
30+
from bson import ObjectId
31+
filter['_id'] = ObjectId(event['id'])
32+
33+
update = {
34+
"$set" : {
35+
"cell" : event['cell'],
36+
"email" : event['email']
37+
}
38+
}
39+
40+
try:
41+
from pymongo.collection import ReturnDocument
42+
43+
# Collection handle with majority write
44+
result = MONGOCLIENT.SingleView.Customers \
45+
.with_options(write_concern=pymongo.write_concern.WriteConcern(w=2)) \
46+
.find_one_and_update( filter, update, return_document=ReturnDocument.AFTER )
47+
48+
from bson.json_util import dumps
49+
return dumps(result)
50+
51+
except Exception as err:
52+
print(err)
53+
raise

0 commit comments

Comments
 (0)