-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
235 lines (198 loc) · 8.03 KB
/
app.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Import necessary modules
require('dotenv').config();
const express = require("express");
const app = express();
const AWS = require("aws-sdk");
const bodyParser = require("body-parser");
const path = require("path");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const { v4: uuidv4 } = require('uuid'); // For generating unique IDs
// Initialize AWS SDK and clients
AWS.config.update({
region: process.env.AWS_REGION,
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});
const dynamoDb = new AWS.DynamoDB.DocumentClient();
const sns = new AWS.SNS(); // Initialize SNS client
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); // Parse JSON bodies
// Session and cookie middleware with expiration time
app.use(cookieParser());
app.use(session({
secret: "your_secret_key", // Change this to a secret key for session encryption
resave: true,
saveUninitialized: true,
cookie: {
secure: true, // Set secure to true if using HTTPS
maxAge: 10 * 60 * 1000 // 10 minutes in milliseconds
}
}));
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// Function to fetch questions from DynamoDB
async function fetchQuestions() {
const params = {
TableName: "Questions"
};
try {
const data = await dynamoDb.scan(params).promise();
return data.Items;
} catch (err) {
console.error("Error fetching questions from DynamoDB:", err);
return [];
}
}
// Function to fetch answers from DynamoDB
async function fetchAnswers() {
const params = {
TableName: "Answers"
};
try {
const data = await dynamoDb.scan(params).promise();
return data.Items;
} catch (err) {
console.error("Error fetching answers from DynamoDB:", err);
return [];
}
}
// Function to insert data into DynamoDB with a specified primary key
async function insertIntoDynamoDB(tableName, primaryKey, data) {
const params = {
TableName: tableName,
Item: {
[primaryKey]: uuidv4(), // Generate a unique ID for the primary key
...data
}
};
try {
await dynamoDb.put(params).promise();
} catch (err) {
console.error(`Error inserting data into ${tableName}:`, err);
throw err;
}
}
// Function to publish a message to an SNS topic
async function publishToSns(message) {
const params = {
Message: message,
TopicArn: process.env.SNS_TOPIC_ARN // Set your SNS Topic ARN in your environment variables
};
try {
await sns.publish(params).promise();
console.log("Message published to SNS:", message);
} catch (err) {
console.error("Error publishing message to SNS:", err);
}
}
// Route to handle GET requests for fetching questions
app.get("/questions", async function(req, res) {
try {
const questions = await fetchQuestions();
res.json(questions);
} catch (err) {
console.error("Error fetching questions:", err);
res.status(500).send("Error fetching questions.");
}
});
// Route to handle GET requests for fetching answers
app.get("/answers", async function(req, res) {
try {
const answers = await fetchAnswers();
res.json(answers);
} catch (err) {
console.error("Error fetching answers:", err);
res.status(500).send("Error fetching answers.");
}
});
// Route to handle POST requests for submitting queries
app.post("/submitQuery", async function(req, res) {
const { name, email, query } = req.body; // Extract data from the POST request
try {
// Insert the query into the "queries" table in DynamoDB with "queryid" as the primary key
await insertIntoDynamoDB("Queries", "queryid", { name, email, query });
console.log("Query inserted into 'queries' table successfully:", query);
// Publish a notification to SNS
await publishToSns(`New query submitted by ${name}: ${query}`);
res.redirect("/"); // Redirect after successful submission
} catch (err) {
console.error("Error inserting query into 'queries' table:", err);
res.status(500).send("Error submitting query.");
}
});
// Route to handle POST requests for submitting questions with image URLs
app.post("/submitQuestion", async function(req, res) {
const question = req.body.question; // Extract question from the POST request
try {
// Insert the question into the "questions" table in DynamoDB with "questionid" as the primary key
await insertIntoDynamoDB("Questions", "questionid", { question: question });
console.log("Question inserted into 'questions' table successfully:", question);
// Optionally publish a notification to SNS
await publishToSns(`New question submitted: ${question}`);
res.redirect("/nn.html"); // Redirect after successful submission
} catch (err) {
console.error("Error inserting question into 'questions' table:", err);
res.status(500).send("Error submitting question.");
}
});
// Route to handle POST requests for submitting emails
app.post("/submitEmail", async function(req, res) {
const email = req.body.email; // Extract email from the POST request
console.log("Email:", email); // Print the email to the console
try {
// Insert the email into the "emails" table in DynamoDB with "emailid" as the primary key
await insertIntoDynamoDB("Emails", "emailid", { email: email });
console.log("Email inserted into 'emails' table successfully:", email);
// Publish a notification to SNS
await publishToSns(`New email submitted: ${email}`);
res.redirect("/about"); // Redirect after email submission
} catch (err) {
console.error("Error inserting email into 'emails' table:", err);
res.status(500).send("Error submitting email.");
}
});
// Route to handle POST requests for submitting answers
app.post("/submitAnswer", async function(req, res) {
const answer = req.body.answer; // Extract answer from the POST request
try {
// Insert the answer into the "answers" table in DynamoDB with "answerid" as the primary key
await insertIntoDynamoDB("Answers", "answerid", { answer: answer });
console.log("Answer inserted into 'answers' table successfully:", answer);
// Optionally publish a notification to SNS
await publishToSns(`New answer submitted: ${answer}`);
res.redirect("/"); // Redirect after successful submission
} catch (err) {
console.error("Error inserting answer into 'answers' table:", err);
res.status(500).send("Error submitting answer.");
}
});
// Route to handle requests for "/another_page.html"
app.get("/another_page.html", function(req, res) {
res.sendFile(path.join(__dirname, 'another_page.html'));
});
// Route to handle requests for "/"
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Route to handle requests for "/nn.html"
app.get("/nn.html", function(req, res) {
res.sendFile(path.join(__dirname, 'nn.html'));
});
// Route to handle requests for "/about"
app.get("/about", function(req, res) {
res.sendFile(path.join(__dirname, "hom.html"));
});
// Route to handle requests for "/answers.html"
app.get("/answers.html", function(req, res) {
res.sendFile(path.join(__dirname, 'answers.html'));
});
// Route to handle requests for "/contact.html"
app.get("/contact.html", function(req, res) {
res.sendFile(path.join(__dirname, 'contact.html'));
});
// Start the server
app.listen(1903, function() {
console.log("Server listening on port 8080");
});