Skip to content
This repository has been archived by the owner on Aug 7, 2024. It is now read-only.

Commit

Permalink
feat: global view stats (#1470)
Browse files Browse the repository at this point in the history
  • Loading branch information
eddiejaoude committed Aug 12, 2022
1 parent 17573d7 commit c81f540
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
18 changes: 18 additions & 0 deletions models/Stats.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import mongoose from "mongoose";

const StatsSchema = new mongoose.Schema({
views: {
type: Number,
default: 0,
},
clicks: {
type: Number,
default: 0,
},
date: {
type: Date,
default: new Date(new Date().toLocaleDateString()),
},
});

module.exports = mongoose.models.Stats || mongoose.model("Stats", StatsSchema);
29 changes: 29 additions & 0 deletions pages/api/users/[username].js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from "path";

import Profile from "../../../models/Profile";
import Link from "../../../models/Link";
import Stats from "../../../models/Stats";
import connectMongo from "../../../config/mongo";

export default async function handler(req, res) {
Expand Down Expand Up @@ -47,6 +48,34 @@ export default async function handler(req, res) {
}
}

const date = new Date(new Date().toLocaleDateString());
const getPlatformStats = await Stats.findOne({ date });
if (getPlatformStats) {
try {
await Stats.update(
{
date,
},
{
$inc: { views: 1 },
}
);
} catch (e) {
console.log("ERROR incrementing platform stats", e);
}
}

if (!getPlatformStats) {
try {
await Stats.create({
date,
views: 1,
});
} catch (e) {
console.log("ERROR creating platform stats", e);
}
}

if (!data.displayStatsPublic) {
return res.status(200).json(data);
}
Expand Down

0 comments on commit c81f540

Please sign in to comment.