Skip to content

Commit

Permalink
fixed metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
phucd5 committed Dec 2, 2023
1 parent 6cc3c50 commit 7a93ef7
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 15 deletions.
16 changes: 8 additions & 8 deletions server/__tests__/controllers/metricsTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ describe("createMetrics", () => {
const mockMetricsData = {
clicks: 0,
total_distribution: 50,
metrics_name: "TestMetric",
};
// Mock the save function to return an object with the input data
MetricsModel.prototype.save = jest.fn().mockImplementation(function () {
return { ...mockMetricsData, _id: this._id };
});

const req = httpMocks.createRequest({
body: { total_distribution: 50 },
body: { total_distribution: 50, metrics_name: "TestMetric" },
});
const res = httpMocks.createResponse();

Expand All @@ -31,19 +31,17 @@ describe("createMetrics", () => {

expect(MetricsModel.prototype.save).toHaveBeenCalled();
expect(res.statusCode).toBe(200);
expect(responseData.clicks).toBe(mockMetricsData.clicks);
expect(responseData.total_distribution).toBe(
mockMetricsData.total_distribution
);
expect(responseData).toMatchObject(mockMetricsData);
expect(responseData).toHaveProperty("_id");
});

it("should return 500 on server errors", async () => {
MetricsModel.prototype.save = jest.fn().mockImplementation(() => {
throw new Error("Internal Server Error");
});

const req = httpMocks.createRequest({
body: { total_distribution: 50 },
body: { total_distribution: 50, metrics_name: "TestMetric" },
});
const res = httpMocks.createResponse();

Expand Down Expand Up @@ -78,7 +76,9 @@ describe("incrementClicks", () => {
{ new: true }
);
expect(res.statusCode).toBe(200);
expect(JSON.parse(res._getData())).toEqual(mockMetricsData);
expect(JSON.parse(res._getData())).toEqual({
message: "Metrics incremented sucessfully",
});
});
it("should return 404 if the metrics record is not found", async () => {
MetricsModel.findOneAndUpdate = jest.fn().mockResolvedValue(null);
Expand Down
31 changes: 24 additions & 7 deletions server/controllers/metrics.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
/**
* Metrics Controller
*
* This file serves as the controller for metrics-related operations in the API.
* It includes functionalities for managing metrics records such as creating new records,
* incrementing click counts, and retrieving metrics data by name.
*
* Dependencies:
* - MetricsModel: The Mongoose model used for metrics data interactions with the MongoDB database.
* - Handlers: Utility functions for handling various HTTP response scenarios, such as server errors,
* successful responses, and resource not found errors.
*/

import MetricsModel from "../models/Metrics.js";
import {
handleServerError,
Expand All @@ -15,11 +28,14 @@ import {
*/
export const createMetrics = async (req, res) => {
try {
const totalDistribution = req.body.total_distribution || 50; // Default to 50 if not provided
const { total_distribution = 50, metrics_name } = req.body;

const metrics = new MetricsModel({
clicks: 0,
total_distribution: totalDistribution,
total_distribution,
metrics_name,
});

await metrics.save();
handleSuccess(res, metrics);
} catch (err) {
Expand All @@ -37,9 +53,10 @@ export const createMetrics = async (req, res) => {
*/
export const incrementClicks = async (req, res) => {
try {
const { metricsName } = req.body;
const { metrics_name } = req.body;
console.log(metrics_name);
const metrics = await MetricsModel.findOneAndUpdate(
{ metrics_name: metricsName },
{ metrics_name: metrics_name },
{ $inc: { clicks: 1 } },
{ new: true }
);
Expand All @@ -48,7 +65,7 @@ export const incrementClicks = async (req, res) => {
return handleNotFound(res, "Metrics record not found");
}

handleSuccess(res, metrics);
handleSuccess(res, { message: "Metrics incremented sucessfully" });
} catch (err) {
handleServerError(res, err);
}
Expand All @@ -64,9 +81,9 @@ export const incrementClicks = async (req, res) => {
*/
export const getMetricsByName = async (req, res) => {
try {
const { metricsName } = req.body;
const { metrics_name } = req.body;
const metrics = await MetricsModel.findOne({
metrics_name: metricsName,
metrics_name: metrics_name,
});

if (!metrics) {
Expand Down
2 changes: 2 additions & 0 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import authRoutes from "./routes/auth.js";
import messageRoutes from "./routes/message.js";
import replyRoutes from "./routes/reply.js";
import userRoutes from "./routes/user.js";
import metricRoutes from "./routes/metrics.js";

// Load environment variables from .env file
dotenv.config();
Expand Down Expand Up @@ -56,6 +57,7 @@ app.use("/auth", authRoutes);
app.use("/message", messageRoutes);
app.use("/reply", replyRoutes);
app.use("/user", userRoutes);
app.use("/metrics", metricRoutes);

const server = app.listen(PORT, console.log(`Server running on port ${PORT}`));

Expand Down

0 comments on commit 7a93ef7

Please sign in to comment.