-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
183 lines (149 loc) · 7.96 KB
/
Copy pathindex.js
File metadata and controls
183 lines (149 loc) · 7.96 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
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
const fs = require('fs');
const path = require('path');
// Read HTML file at startup
const html = fs.readFileSync(path.join(__dirname, 'index.html'), { encoding: 'utf8' });
// AWS SDK v3 imports
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, PutCommand, ScanCommand } = require('@aws-sdk/lib-dynamodb');
// Create DynamoDB client
const client = new DynamoDBClient({ region: process.env.AWS_REGION || 'us-east-1' });
const dynamo = DynamoDBDocumentClient.from(client);
exports.handler = async (event, context) => {
try {
console.log('🚀 Handler started');
console.log('Event:', JSON.stringify(event, null, 2));
// First, get existing records from DynamoDB
let tableQuery = null;
try {
console.log('🔍 Scanning DynamoDB table...');
const scanCommand = new ScanCommand({
TableName: "formStore"
});
tableQuery = await dynamo.send(scanCommand);
console.log('✅ DynamoDB Scan Success!');
console.log('📊 Records found:', tableQuery.Count);
} catch (scanError) {
console.error('❌ DynamoDB Scan Error:', scanError);
tableQuery = { Items: [] };
}
// Process form data and save to DynamoDB if present
if (event.queryStringParameters && Object.keys(event.queryStringParameters).length > 0) {
try {
console.log('💾 Saving new form data...');
const putCommand = new PutCommand({
TableName: "formStore",
Item: {
PK: "form",
SK: context.awsRequestId,
timestamp: new Date().toISOString(),
sourceIP: event.requestContext?.http?.sourceIp || 'unknown',
userAgent: event.headers?.['user-agent'] || 'unknown',
form: event.queryStringParameters
}
});
await dynamo.send(putCommand);
console.log('✅ Successfully saved to DynamoDB:', context.awsRequestId);
// Refresh the table data after inserting new record
const refreshScanCommand = new ScanCommand({
TableName: "formStore"
});
tableQuery = await dynamo.send(refreshScanCommand);
console.log('🔄 Refreshed data, new count:', tableQuery.Count);
} catch (dbError) {
console.error('❌ DynamoDB Put Error:', dbError);
}
}
// Apply dynamic functions
console.log('🔧 Processing HTML template...');
let modifiedHTML = dynamicForm(html, event.queryStringParameters);
modifiedHTML = dynamictable(modifiedHTML, tableQuery);
console.log('✅ HTML processing complete');
const response = {
statusCode: 200,
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-cache'
},
body: modifiedHTML,
};
return response;
} catch (error) {
console.error('💥 Handler Error:', error);
return {
statusCode: 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
error: 'Internal Server Error',
message: error.message,
requestId: context.awsRequestId
})
};
}
};
function dynamicForm(html, queryStringParameters) {
let formResults = '';
if (queryStringParameters && Object.keys(queryStringParameters).length > 0) {
formResults = '<div class="result"><h4>✅ Form Submission Saved Successfully!</h4><ul>';
Object.entries(queryStringParameters).forEach(([key, value]) => {
if (value && value.trim() !== '') {
formResults += `<li><strong>${key}:</strong> ${value}</li>`;
}
});
formResults += '</ul><p><em>Data has been stored in DynamoDB table "formStore"</em></p></div>';
} else {
formResults = '<div class="result" style="background: #fff3cd; border-color: #ffeaa7; color: #856404;"><h4>ℹ️ Ready to Process Form Data</h4><p>Fill out the form below to see dynamic processing in action!</p></div>';
}
return html.replace('{formResults}', formResults);
}
function dynamictable(html, tableQuery) {
console.log('🏗️ Building table HTML...');
let table = "";
if (tableQuery && tableQuery.Items && tableQuery.Items.length > 0) {
console.log('✅ Found items, building table...');
// Create a proper HTML table
table = `
<div style="overflow-x: auto; margin: 15px 0; border: 2px solid #007bff; border-radius: 8px; padding: 15px; background: #f8f9fa;">
<h5 style="color: #007bff; margin-top: 0;">📊 Form Submissions Database</h5>
<table style="width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 14px; background: white;">
<thead>
<tr style="background-color: #007bff; color: white;">
<th style="border: 1px solid #ddd; padding: 12px; text-align: left;">Submission ID</th>
<th style="border: 1px solid #ddd; padding: 12px; text-align: left;">Timestamp</th>
<th style="border: 1px solid #ddd; padding: 12px; text-align: left;">Name</th>
<th style="border: 1px solid #ddd; padding: 12px; text-align: left;">Location</th>
<th style="border: 1px solid #ddd; padding: 12px; text-align: left;">Details</th>
</tr>
</thead>
<tbody>
`;
for (let i = 0; i < tableQuery.Items.length; i++) {
const item = tableQuery.Items[i];
const formData = item.form || {};
table += `
<tr style="background-color: ${i % 2 === 0 ? '#ffffff' : '#f9f9f9'};">
<td style="border: 1px solid #ddd; padding: 8px; font-family: monospace; font-size: 10px;">${(item.SK || 'N/A').substring(0, 8)}...</td>
<td style="border: 1px solid #ddd; padding: 8px;">${item.timestamp ? new Date(item.timestamp).toLocaleString() : 'N/A'}</td>
<td style="border: 1px solid #ddd; padding: 8px;"><strong>${formData.name || 'N/A'}</strong></td>
<td style="border: 1px solid #ddd; padding: 8px;">${formData.location || 'N/A'}</td>
<td style="border: 1px solid #ddd; padding: 8px;">
<details>
<summary style="cursor: pointer; color: #007bff;">View All</summary>
<pre style="margin: 5px 0; font-size: 11px; background: #f8f9fa; padding: 5px; border-radius: 3px;">${JSON.stringify(formData, null, 2)}</pre>
</details>
</td>
</tr>
`;
}
table += `
</tbody>
</table>
<p style="color: #6c757d; font-size: 12px; margin-bottom: 0;"><em>📊 Total records: ${tableQuery.Items.length} | Last updated: ${new Date().toLocaleString()}</em></p>
</div>
`;
console.log('✅ Table HTML built successfully');
} else {
console.log('⚠️ No items found');
table = '<div style="padding: 20px; background: #f8f9fa; border-radius: 5px; text-align: center; color: #6c757d; border: 2px dashed #dee2e6;"><p>📋 No records found in DynamoDB table.</p><p><em>Submit the form above to create your first record!</em></p></div>';
}
return html.replace("{table}", `<h4>📊 DynamoDB Records:</h4>${table}`);
}