implemented activities api

This commit is contained in:
SrGooglo 2025-01-25 19:45:58 +00:00
parent c4050f7fb3
commit e0ae3ca064
2 changed files with 83 additions and 0 deletions

View File

@ -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
}
}

View File

@ -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
}
}