Skip to content

Commit

Permalink
added analytics model and some apis
Browse files Browse the repository at this point in the history
  • Loading branch information
NitinVangipuram committed Feb 26, 2024
1 parent f2afaa6 commit 5d9ff7b
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { Authenticate } from "./middlewares/Authenticate";
// import { Authorize } from "./middlewares/Authorize";
import connectDB from "./config/connectDB";
// import notifications from "./models/notifications";
import User_Schema from "./models/user"; // Adjust the import path according to your project structure
import Analytics from "./models/analytics";



Expand Down Expand Up @@ -59,6 +61,31 @@ app.use("/api/user", userRouter);
app.use("/api/manager", managerRoutes);


app.get("/api/usercount", async (req: Request, res: Response) => {
try {
const count = await User_Schema.countDocuments({}); // Get the count of all user documents
res.status(200).json({ count }); // Send the count in a JSON object
} catch (error) {
console.error("Error fetching users count:", error);
res.status(500).send("An error occurred while fetching the count of users.");
}
});
app.get("/api/userstats", async (req: Request, res: Response) => {
try {
// Fetch all analytics data sorted by date
const allAnalytics = await Analytics.find({}).sort({ date: 1 });
// Optionally, format data before sending
const formattedData = allAnalytics.map(entry => ({
date: entry.date,
visitors: entry.uniqueVisitorsCount,
}));
console.log(formattedData);
res.json(formattedData);
} catch (error) {
console.error('Error fetching visitor stats:', error);
res.status(500).send('Internal Server Error');
}
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createHttpError(404));
Expand Down
23 changes: 23 additions & 0 deletions src/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import user_model from '../models/user';
import { createSession } from '../services/createSession';
import { JWTLoadData } from '../Interface/interfaces';
import { sendNotification } from '../config/firebaseWeb';
import Analytics from '../models/analytics';

const webSigninHandler = async (req: Request, res: Response): Promise<Response | undefined> => {
try {
Expand Down Expand Up @@ -35,6 +36,27 @@ const webSigninHandler = async (req: Request, res: Response): Promise<Response |
user = newUser;
isNewUser = true;
}
const today = new Date();
today.setHours(0, 0, 0, 0);

const analyticsRecord = await Analytics.findOne({ date: today });
if (analyticsRecord) {
// If record exists for today and the user's ID is not in visitorIds, add it
if (!analyticsRecord.visitorIds.includes(user._id.toString())) {
analyticsRecord.visitorIds.push(user._id.toString());
analyticsRecord.uniqueVisitorsCount += 1;
await analyticsRecord.save();
console.log("Updated analytics record for today:", analyticsRecord); // Log updated analytics record
}
} else {
// If no record exists for today, create a new one
const newRecord = await Analytics.create({
date: today,
uniqueVisitorsCount: 1,
visitorIds: [user._id.toString()]
});
console.log("Created new analytics record for today:" , newRecord);
}
// console.log(user);
//create session
const payload: JWTLoadData = {
Expand All @@ -47,6 +69,7 @@ const webSigninHandler = async (req: Request, res: Response): Promise<Response |
const token = createSession(payload);
if (isNewUser) return res.status(201).json({ token, user });
return res.status(200).json({ token, user });
//
} catch (err) {
console.log(err);
return res.status(500).send("Some Error Occured while fetching user info");
Expand Down
30 changes: 30 additions & 0 deletions src/models/analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import mongoose, { Document, Schema } from 'mongoose';

interface IAnalytics extends Document {
date: Date;
uniqueVisitorsCount: number;
visitorIds: string[];
}

const analyticsSchema: Schema = new Schema({
date: {
type: Date,
unique: true,
required: true
},
uniqueVisitorsCount: {
type: Number,
required: true,
default: 0
},
visitorIds: {
type: [String],
default: []
}
}, {
timestamps: true
});

const Analytics = mongoose.model<IAnalytics>('Analytics', analyticsSchema);

export default Analytics;

0 comments on commit 5d9ff7b

Please sign in to comment.