-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (71 loc) · 2.32 KB
/
index.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
import express from "express";
import cors from "cors";
import expressAsyncHandler from "express-async-handler";
import authorizeRequest from "./middleware/authorizeRequest.js";
import { notFound, errorHandler } from "./middleware/errorHandlers.js";
import OAuth from "./services/OAuth.js";
import Gmail from "./services/GmailManager.js";
// DELETE BEFORE PROD
// import dotenv from "dotenv";
// dotenv.config();
// ====================
const app = express();
const oauth = new OAuth();
app.use(express.json());
// TO BE CONFIGURED WHEN DEPLOYING TO GCP
// ALLOWED_CLIENT_ORIGIN
// define the origins which can make POST request to the microservice
// app.use(cors({ origin: process.env.ALLOWED_CLIENT_ORIGIN, methods: "POST" }));
// ===================
app.get("/authenticate", (req, res) => {
const authUrl = oauth.generateUrl();
res.redirect(authUrl);
});
app.get(
"/token",
expressAsyncHandler(async (req, res) => {
try {
const { code } = req.query;
const token = await oauth.generateToken(code);
if (token) {
res.send("Authentication successful");
} else {
throw new Error(
"An error occured while token was being generated"
);
}
} catch (error) {
console.log(error);
throw new Error(error);
}
})
);
app.post(
"/mailer",
authorizeRequest,
expressAsyncHandler(async (req, res) => {
try {
const { messageObj, recipientsObj } = req.body;
const { from, to, cc, bcc } = recipientsObj;
if (messageObj && recipientsObj) {
const gmail = new Gmail();
await gmail.initialize();
await gmail.sendEmail(from, to, cc, bcc, messageObj);
res.send("Email has been sent");
} else {
throw new Error("Message and recipients object required");
}
} catch (error) {
console.log(error);
throw new Error(error);
}
})
);
// ERROR HANDLING MIDDLEWARE
app.use(notFound);
app.use(errorHandler);
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Application is listening on port ${PORT}...`);
});