-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
88 lines (73 loc) · 1.9 KB
/
handler.js
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
'use strict';
const { MongoClient } = require("mongodb");
const AWS = require('aws-sdk');
let cachedDb = null;
/*
* Instantiate Secrets Manager
*/
const sm = new AWS.SecretsManager({
region: "us-east-1"
});
/*
* Generic method for retrieving secrets from Secret Manager
*/
const getSecrets = async (SecretId) => {
return await new Promise((resolve, reject) => {
sm.getSecretValue( { SecretId }, (err, result) => {
if(err) reject(err);
if(result) resolve(JSON.parse(result.SecretString));
});
});
}
/*
* Fetch MongoDB credentials, specifically
*/
const getMongoCredentials = async (event) => {
const { mongoUri, mongoUser, mongoPass } = await getSecrets('mongoCredentials');
return [ mongoUri, mongoUser, mongoPass ];
}
/*
* Core function for connecting to database
*/
async function connectToDatabase() {
// If already connected, return
if (cachedDb) {
return cachedDb;
}
// Connect
const [ mongoUri, mongoUser, mongoPass ] = await getMongoCredentials();
const uri = `mongodb+srv://${mongoUser}:${mongoPass}${mongoUri}`;
const client = new MongoClient(uri);
await client.connect();
// Select database, cache, and return
const db = await client.db("data");
cachedDb = db;
return db;
}
/*
* Retrieve home value and rental data from database
*/
const retrievePrices = async() => {
const db = await connectToDatabase();
const prices = db.collection("prices");
const all = await prices.find().toArray();
return all;
}
/*
* Main Lambda handler function
*/
module.exports.getData = async (event) => {
const data = await retrievePrices();
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify(
data,
null,
2
),
};
};