-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
handler.js
82 lines (68 loc) · 1.66 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
// handler.js
'use strict';
const express = require('express');
const serverless = require('serverless-http');
const MongoClient = require('mongodb').MongoClient;
const faker = require('faker');
const mongoClusterName = '';
const mongoUser = '';
const mongoDbName = '';
const mongoPass = '';
const mongoConnStr = `mongodb+srv://${mongoUser}:${mongoPass}@${mongoClusterName}-tdoka.mongodb.net/${mongoDbName}?retryWrites=true`;
const getPetType = () => {
const msNow = Date.now();
if (msNow % 2 === 0) {
return 'cat';
}
return 'dog';
}
const getPet = () => {
return {
type: getPetType(),
name: faker.name.findName(),
};
}
const client = new MongoClient(mongoConnStr, {
useNewUrlParser: true,
});
let db;
const createConn = async () => {
await client.connect();
db = client.db('test');
};
const performQuery = async () => {
const pets = db.collection('pets');
const newPet = getPet();
return {
insertedPet: newPet,
mongoResult: await pets.insertOne(newPet),
};
};
const app = express();
app.get('/hello', async function (req, res) {
if (!client.isConnected()) {
// Cold start or connection timed out. Create new connection.
try {
await createConn();
} catch (e) {
res.json({
error: e.message,
});
return;
}
}
// Connection ready. Perform insert and return result.
try {
res.json(await performQuery());
return;
} catch (e) {
res.send({
error: e.message,
});
return;
}
});
module.exports = {
app,
hello: serverless(app),
};