From e0ae3ca0649de3efd91b6ab80dcf02e739781504 Mon Sep 17 00:00:00 2001 From: SrGooglo Date: Sat, 25 Jan 2025 19:45:58 +0000 Subject: [PATCH] implemented `activities` api --- .../main/routes/activity/recent/get.js | 23 +++++++ .../main/routes/events/client/post.js | 60 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 packages/server/services/main/routes/activity/recent/get.js create mode 100644 packages/server/services/main/routes/events/client/post.js diff --git a/packages/server/services/main/routes/activity/recent/get.js b/packages/server/services/main/routes/activity/recent/get.js new file mode 100644 index 00000000..7b7d1d80 --- /dev/null +++ b/packages/server/services/main/routes/activity/recent/get.js @@ -0,0 +1,23 @@ +import { RecentActivity } from "@db_models" + +export default { + middlewares: [ + "withAuthentication", + ], + fn: async (req, res) => { + const { type } = req.query + const user_id = req.auth.session.user_id + + const query = { + user_id: user_id, + } + + if (type) { + query.type = type + } + + const activities = await RecentActivity.find(query) + + return activities + } +} \ No newline at end of file diff --git a/packages/server/services/main/routes/events/client/post.js b/packages/server/services/main/routes/events/client/post.js new file mode 100644 index 00000000..b80e603b --- /dev/null +++ b/packages/server/services/main/routes/events/client/post.js @@ -0,0 +1,60 @@ +import { RecentActivity } from "@db_models" + +const IdToTypes = { + "player.play": "track_played" +} + +export default { + middlewares: [ + "withAuthentication", + ], + fn: async (req, res) => { + const user_id = req.auth.session.user_id + let { id, payload } = req.body + + if (!id) { + throw new OperationError(400, "Event id is required") + } + + if (!payload) { + throw new OperationError(400, "Event payload is required") + } + + id = id.toLowerCase() + + if (!IdToTypes[id]) { + throw new OperationError(400, `Event id ${id} is not supported`) + } + + const type = IdToTypes[id] + + // get latest 20 activities + const latestActivities = await RecentActivity.find({ + user_id: user_id, + type: type, + }) + .limit(20) + .sort({ created_at: -1 }) + + // check if the activity is already in some position and remove + latestActivities.find((activity, index) => { + if (activity.payload === payload && activity.type === type) { + latestActivities.splice(index, 1) + } + }) + + // if the list is full, remove the oldest activity and add the new one + if (latestActivities.length >= 20) { + await RecentActivity.findByIdAndDelete(latestActivities[latestActivities.length - 1]._id) + } + + const activity = await RecentActivity.create({ + user_id: user_id, + type: type, + payload: payload, + created_at: new Date(), + }) + + return activity + } +} \ No newline at end of file