This repository was archived by the owner on Apr 18, 2024. It is now read-only.
forked from anomalyco/sst
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda.js
More file actions
46 lines (36 loc) · 1.34 KB
/
Copy pathlambda.js
File metadata and controls
46 lines (36 loc) · 1.34 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
import * as mongodb from "mongodb";
const MongoClient = mongodb.MongoClient;
// Once we connect to the database once, we'll store that connection
// and reuse it so that we don't have to connect to the database on every request.
let cachedDb = null;
async function connectToDatabase() {
if (cachedDb) {
return cachedDb;
}
// Connect to our MongoDB database hosted on MongoDB Atlas
const client = await MongoClient.connect(process.env.MONGODB_URI);
// Specify which database we want to use
cachedDb = await client.db("sample_mflix");
return cachedDb;
}
export async function handler(event, context) {
// By default, the callback waits until the runtime event loop is empty
// before freezing the process and returning the results to the caller.
// Setting this property to false requests that AWS Lambda freeze the
// process soon after the callback is invoked, even if there are events
// in the event loop.
context.callbackWaitsForEmptyEventLoop = false;
// Get an instance of our database
const db = await connectToDatabase();
// Make a MongoDB MQL Query
const movies = await db
.collection("movies")
.find({}, { projection: { title: 1, plot: 1, metacritic: 1, cast: 1 } })
.sort({ metacritic: -1 })
.limit(20)
.toArray();
return {
statusCode: 200,
body: JSON.stringify(movies, null, 2),
};
}