From cf5151de7e36db3b275fbbba6b9738fda3575d56 Mon Sep 17 00:00:00 2001 From: Artemy Egorov Date: Tue, 25 Apr 2023 17:42:50 +0300 Subject: [PATCH] Stats (#8) * feat: sent notes stats * fix: unused var in notes * refactor: stats increment * feat: received notes, deleted notes * fix: received notes stats inc * refactor: stats * fix: inc received * feat: api for stats * doc: update changelog --- changelog.md | 1 + core.js | 24 ++++++++++++++++++++++-- index.js | 9 +++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/changelog.md b/changelog.md index 2b6763e..b6ee5c3 100644 --- a/changelog.md +++ b/changelog.md @@ -23,6 +23,7 @@ - [ ] Settings for publish notes, such as: delete after reading, number of reads before deleting, adding your own data (name, picture, status in the settings) to the note. - [ ] Api for upload photos - [ ] Inserting a photo in a note +- [x] Maintaining statistics on sent notes, the number of notes received, number of deleted notes # AnoPaper v1.0.0 diff --git a/core.js b/core.js index ef4df5c..1a93480 100644 --- a/core.js +++ b/core.js @@ -26,11 +26,22 @@ class NotesCore { let db = connection.db(process.env.MONGO_DB); this.notes = db.collection("notes"); + this.stats = db.collection("stats"); } async getNote(_id) { try { - return await this.notes.findOne({ _id }); + let note = await this.notes.findOne({ _id }); + if (note !== null) await this.incStats("receivedNotes"); + return note; + } catch { + return null; + } + } + + async getStats(_id) { + try { + return await this.stats.findOne({ _id }); } catch { return null; } @@ -38,6 +49,7 @@ class NotesCore { async deleteNote(_id) { try { + await this.incStats("deletedNotes"); return await this.notes.deleteOne({ _id }); } catch { return null; @@ -49,17 +61,25 @@ class NotesCore { note._id = sha3(JSON.stringify(note)); note.time = Date.now(); note.pub = true; - note.pubTime = note.time; await this.notes.updateOne( { _id: note._id }, { $set: note }, { upsert: true } ); + await this.incStats("sentNotes"); return note._id; } catch { return null; } } + + async incStats(_id) { + await this.stats.updateOne( + { _id }, + { $inc: { value: 1 } }, + { upsert: true } + ); + } } module.exports = { diff --git a/index.js b/index.js index b60b603..fd77ff8 100644 --- a/index.js +++ b/index.js @@ -107,6 +107,15 @@ app.get("/get-note/:delorno/:id", async (req, res) => { } }); +app.get("/stats/:id", async (req, res) => { + let stats = await core.getStats(req.params.id); + if (stats) { + res.json(stats); + } else { + res.status(404).send("There is no stats with such id"); + } +}); + app.use(express.static("dist")); app.get("*", function (req, res) {