Skip to content

Commit 4cc8fe7

Browse files
authored
Merge pull request #48 from oslabs-beta/react3
React3
2 parents 997b1b4 + 7559be4 commit 4cc8fe7

22 files changed

+643
-411
lines changed

.env

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# import dotenv from 'dotenv';
2-
31
# dotenv.config(); //
42
# Server Configuration
53
PORT=3000
@@ -11,7 +9,6 @@ AWS_SECRET_ACCESS_KEY="GLV3QVs/loqagUxg/TMob5T+VnbWEoonPJX0ZxiF"
119
AWS_SESSION_TOKEN_KEY="IQoJb3JpZ2luX2VjEGEaCXVzLWVhc3QtMSJHMEUCIQDA07XhxdfJSlGiBkb01mEphUQuvbN9Bw3BaBfHNSYPcAIgNk0kLlkLnFRxc41W8WLZqC7x65qH7DzNRY+mrB0NcWUq6wIIehAAGgw5MTM1MjQ5NDA2MTIiDHmtFygbJdLUbngQRSrIAh0p76fbXskc8Mpj294yowBG33InJvLc1CetdDpwVev/AM3ZtJgPFjQUjTuFdmd7mQFe/n8PvotL9Wh/+YbFjTfni8HDN9Y30B+M32baG0xbUka0NXd//bFMOCMLEpmCH5WbAFwlHlpGXxva1mOQOXXzbweQ51WCaou+GZpxL3a+sIxLHwF4dex7CBkLzyTYpBh7W1kBlXOPC+oxP9356BpZKaXBC3g3zYV6Ws80pizmZqEoVjQlmCQyLLLLQSV8GnpxIoV8o2xlTbZfx9MKyDIEJkOiEe3uH95si2ZSbQghZ/9WwWkY7lxmE75m4k+eNGDdOfUApYXJA1S4diBoxhsTwjBHJ+cWIGYPwyHCPNsdx25mmv3PO9lstESEV/7bRL4v9+v1PL7WGdfC06XcDtFYlFszoJ7Osn7scYVOV751BJRm3dlsPnYwo+uYvQY6pwGZpA4DQi35uSBzl2AaohInC3MO4+ikBqEBEAKlDgp2iquYFr8DeWFPDjfl25N7Hu0VQimL6ljLgTgy5mZ6AmyNLTQL051u3yiw3DopGHQT2hF8cEltINwirXOfaNEBrhXRrbcKENTGe5xfcIgDZf2IygEzBxGkSoEZo0rhaoNFWDBKQDvM1gzakDrHI4GI2+OgJVo2r8MIyQj37rXbrlw8Ke7fh/AIpw=="
1210
AWS_REGION="us-east-1"
1311

14-
1512
VITE_COGNITO_USER_POOL_ID='us-east-1_p9EHXxO94'
1613
VITE_COGNITO_CLIENT_ID='1b5155v1t176k3afcj6ms964l8'
1714
COGNITO_USER_POOL_ID='us-east-1_p9EHXxO94'

.gitignore

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,12 @@ pnpm-debug.log*
1111
lerna-debug.log*
1212

1313
node_modules
14+
,env
1415
dist
1516
dist-ssr
1617
*.local
1718

18-
# Editor directories and files
19+
# Editor directories and fil-es
1920
.vscode/*
2021
!.vscode/extensions.json
2122
.idea
@@ -25,3 +26,6 @@ dist-ssr
2526
*.njsproj
2627
*.sln
2728
*.sw?
29+
30+
# Aws
31+
backend/.aws/*

Dockerfile-preview

Whitespace-only changes.

Dockerfile-server

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,12 @@ FROM node:23.6.0
33

44
# Set the working directory.
55
WORKDIR /server
6-
7-
8-
# Copy package files and install dependencies.
96
COPY ./package.json /server
10-
11-
12-
COPY ./backend/serve.js /server
13-
COPY ./backend/externalIDGenerator.js /server
14-
COPY ./backend/cloudwatch.js /server
157
RUN npm install
168

9+
# Copy package files and install dependencies.
10+
COPY ./backend /server
11+
1712
# Copy the rest of your application code.
1813
# Expose the port Vite is running on.
1914
EXPOSE 81

backend/.aws/config

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[default]
2+
region=us-east-1
3+
output=json

backend/cloudwatch.js

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,40 @@ import {
33
CloudWatchServiceException, // Handles specific errors from CloudWatch
44
GetMetricDataCommand, // Sends a request to fetch metric data
55
} from '@aws-sdk/client-cloudwatch';
6+
import { fromIni } from '@aws-sdk/credential-providers';
7+
const region = 'us-east-1';
68

7-
const client = new CloudWatchClient({ region: 'us-east-1' });
8-
let response;
9-
const InstanceId = 'i-0610f2356e0d72fcd';
9+
async function MixedMetrix(metricMap) {
10+
const client = new CloudWatchClient({
11+
region,
12+
credentials: fromIni({
13+
profile: 'default',
14+
}),
15+
});
16+
let response;
17+
const InstanceId = 'i-0610f2356e0d72fcd';
1018

19+
const { metric, data, graph } = metricMap;
20+
const queries = [];
1121

22+
let currentTime = new Date();
23+
currentTime.setSeconds(0);
24+
while (currentTime.getMinutes() % 5 !== 0) {
25+
currentTime.setMinutes(currentTime.getMinutes() - 1);
26+
}
1227

13-
async function MixedMetrix(metricMap) {
14-
console.log('in metricmix: ', metricMap);
15-
const { graph, metric, data } = metricMap;
16-
const queries = [];
28+
let pastHour = new Date(currentTime);
29+
pastHour.setHours(pastHour.getHours() - 1);
1730

18-
31+
let num = 0;
1932

2033
for (let i = 0; i < metric.length; i++) {
34+
let id = metric[i].toLowerCase() + graph[i] + num.toString();
35+
num++;
2136
queries.push(
2237
{
2338
// MetricDataQuery
24-
Id: metric[i], // required
39+
Id: id, // required
2540
MetricStat: {
2641
// MetricStat
2742
Metric: {
@@ -48,20 +63,19 @@ async function MixedMetrix(metricMap) {
4863
// Input object describes the data we're requesting from CloudWatch
4964
// GetMetricDataInput
5065
MetricDataQueries: queries,
51-
StartTime: new Date('2025-01-18T23:05:00.000Z'), // required
52-
EndTime: new Date('2025-01-18T23:30:00.000Z'), // required
53-
ScanBy: 'TimestampDescending', // Gets the newest data first
54-
MaxDatapoints: 1000, // Max Datapoints 100,000
66+
StartTime: pastHour, // required
67+
EndTime: currentTime, // required
68+
ScanBy: 'TimestampAscending', // Gets the newest data first
69+
MaxDatapoints: 10000, // Max Datapoints 100,000
5570
};
5671

5772
const command = new GetMetricDataCommand(input); //Creates the request to send to CloudWatch using the input
5873
try {
5974
// Sends the request and waits for the response
6075
response = await client.send(command);
76+
//console.log('response meta: ', response);
6177

62-
console.log('response results', response.MetricDataResults);
63-
64-
return response; // logs the metric data and entire response if successful
78+
return response.MetricDataResults; // logs the metric data and entire response if successful
6579
} catch (caught) {
6680
if (caught instanceof CloudWatchServiceException) {
6781
// if theres a CloudWatch error, it logs the error name and message

backend/controllers/authMiddleware.js

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ const authenticateToken = async (req, res, next) => {
3939

4040
// Decode the JWT to get the kid (key id)
4141
const decodedHeader = jwt.decode(token, { complete: true })?.header;
42-
4342
//if decodedheader exists, grab the key id
4443
const kid = decodedHeader?.kid;
4544

@@ -49,7 +48,6 @@ const authenticateToken = async (req, res, next) => {
4948
.status(400)
5049
.json({ error: 'Invalid token: Missing kid in token header' });
5150
}
52-
5351
// Fetch the public key using the kid
5452
const publicKey = await getKey({ kid });
5553

backend/data.js

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,6 @@ export const awsData = async () => {
157157
try {
158158
// Sends the request and waits for the response
159159
response = await client.send(command);
160-
161160
return response; // logs the metric data and entire response if successful
162161
} catch (caught) {
163162
if (caught instanceof CloudWatchServiceException) {
@@ -172,7 +171,6 @@ export const awsData = async () => {
172171
for (const metric of response.MetricDataResults) {
173172
for (let i = 0; i < metric.Timestamps.length; i++) {
174173
// console.log('Metric:', metric.Id, 'Value:', metric.Values[i]); // Debugging output
175-
176174
const query = `
177175
INSERT INTO aws_metrics
178176
(aws_account_id, metric_name, metric_value, timestamp, service_name, region)
@@ -233,7 +231,6 @@ export const awsHourData = async () => {
233231
ScanBy: 'TimestampAscending', // Gets the oldest data first
234232
MaxDatapoints: 1000, // Max Datapoints 100,000
235233
};
236-
237234
const command = new GetMetricDataCommand(input); //Creates the request to send to CloudWatch using the input
238235
try {
239236
// Sends the request and waits for the response

backend/fetch.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
export async function AWSdata(graphs) {
2-
console.log('in fetch', graphs);
3-
42
try {
53
let res = await fetch('http://localhost:81/data', {
64
headers: {
@@ -9,9 +7,9 @@ export async function AWSdata(graphs) {
97
method: 'POST',
108
body: JSON.stringify(graphs),
119
});
12-
console.log('res: ', res);
10+
1311
let data = await res.json();
14-
console.log('data in fetch.js: ', data);
12+
1513
return data;
1614
} catch (error) {
1715
console.error(error);

backend/metrics.js

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import client from "./modal.js"; // Import PostgreSQL client from modal.js
2-
import { awsData } from "./data.js"; // Import the awsData function from data.js
1+
import client from './modal.js'; // Import PostgreSQL client from modal.js
2+
import { awsData } from './data.js'; // Import the awsData function from data.js
33

44
// Function to transform fetched metric data
55
const transformMetrics = (metricResults) => {
@@ -9,7 +9,6 @@ const transformMetrics = (metricResults) => {
99
values: result.Values || [],
1010
}));
1111
};
12-
1312
// Function to save the transformed metrics data into PostgreSQL (using UPSERT)
1413
const saveMetricsToDatabase = async (awsAccountId, transformedMetrics) => {
1514
for (const metric of transformedMetrics) {
@@ -21,14 +20,13 @@ const saveMetricsToDatabase = async (awsAccountId, transformedMetrics) => {
2120
null, // instanceId (if available, otherwise null)
2221
metric.values[i],
2322
metric.timestamps[i],
24-
"Average", // Stat (you can modify based on data)
25-
"%", // Unit (you can modify based on data)
23+
'Average', // Stat (you can modify based on data)
24+
'%', // Unit (you can modify based on data)
2625
60 // Period (you can modify based on data)
2726
);
2827
}
2928
}
3029
};
31-
3230
// Function to update or insert the metric using UPSERT logic
3331
async function updateMetric(
3432
awsAccountId,
@@ -64,9 +62,9 @@ async function updateMetric(
6462
unit,
6563
period,
6664
]);
67-
console.log("Metric updated successfully");
65+
console.log('Metric updated successfully');
6866
} catch (err) {
69-
console.error("Error updating metric:", err);
67+
console.error('Error updating metric:', err);
7068
}
7169
}
7270

@@ -75,7 +73,7 @@ const getAwsAccountIdByEmail = async (email) => {
7573
const query = `SELECT aws_account_id FROM aws_accounts WHERE user_id = (SELECT id FROM users WHERE email = $1)`;
7674
const result = await client.query(query, [email]);
7775
if (result.rows.length === 0) {
78-
throw new Error("AWS account not found for the provided email.");
76+
throw new Error('AWS account not found for the provided email.');
7977
}
8078
return result.rows[0].aws_account_id;
8179
};
@@ -84,30 +82,29 @@ const getAwsAccountIdByEmail = async (email) => {
8482
const Workflow = async () => {
8583
try {
8684
// Get the AWS account ID from the email
87-
const awsAccountId = await getAwsAccountIdByEmail("[email protected]");
85+
const awsAccountId = await getAwsAccountIdByEmail('[email protected]');
8886
if (!awsAccountId) {
89-
throw new Error("No AWS account found for the provided email.");
87+
throw new Error('No AWS account found for the provided email.');
9088
}
91-
//testing Account ID
92-
console.log("AWS Account ID:", awsAccountId);
93-
89+
//CAN BE DELETED --> testing Account ID
90+
console.log('AWS Account ID:', awsAccountId);
9491
// Fetch the data from AWS CloudWatch
9592
const data = await awsData();
96-
console.log("Fetched AWS Data:", data); // Log the raw AWS data to inspect it
93+
console.log('Fetched AWS Data:', data); // Log the raw AWS data to inspect it
9794

9895
// Check if data.MetricDataResults exists
9996
if (!data.MetricDataResults) {
100-
throw new Error("MetricDataResults not found in AWS data.");
97+
throw new Error('MetricDataResults not found in AWS data.');
10198
}
10299

103100
// Transform the data
104101
const transformedMetrics = transformMetrics(data.MetricDataResults);
105-
console.log("Transformed Metrics:", transformedMetrics); // Log the transformed metrics
102+
console.log('Transformed Metrics:', transformedMetrics); // Log the transformed metrics
106103

107104
// Save the transformed metrics into the database
108105
await saveMetricsToDatabase(awsAccountId, transformedMetrics);
109106
} catch (err) {
110-
console.error("Error in the workflow:", err);
107+
console.error('Error in the workflow:', err);
111108
} finally {
112109
await client.end(); // Close connection after all queries
113110
}

backend/serve.js

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,15 @@ app.use(cors());
1010
app.use(express.json());
1111
app.use(express.urlencoded({ extended: true }));
1212

13-
app.get('/random', (req, res) => {
14-
let id = externalIdGenerator();
13+
app.get('/random', async (req, res) => {
14+
let id = await externalIdGenerator();
1515
return res.status(200).json({ id });
1616
});
1717

18-
app.post('/data', (req, res) => {
18+
app.post('/data', async (req, res) => {
1919
const { graph, metric, data } = req.body;
20-
let result = MixedMetrix({ graph, metric, data });
21-
22-
return res.status(200).json(result);
20+
let result = await MixedMetrix({ graph, metric, data });
21+
return res.status(200).json({result});
2322
});
2423

2524
app.use((req, res) => res.status(404).send('No Data'));

backend/server.js

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,6 @@ app.get('/data', async (req, res) => {
3131
});
3232

3333

34-
app.get('/random', (req, res) => {
35-
let id = externalIdGenerator();
36-
res.status(200).json({ id });
37-
});
38-
3934
app.get('/protected', authenticateToken, (req, res) => {
4035
res.status(200).json('Success, accessed a protected route');
4136
});

0 commit comments

Comments
 (0)