Files
notesnook/packages/core/models/topic.js

89 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-02-05 20:57:43 +05:00
import Topics from "../collections/topics";
export default class Topic {
/**
*
* @param {Topics} topics
* @param {Object} topic
*/
constructor(topics, topic) {
this._topic = topic;
this._topics = topics;
this._transactionOpen = false;
}
get totalNotes() {
return this._topic.totalNotes;
2020-02-05 20:57:43 +05:00
}
transaction(ops, saveAfter = true) {
this._transactionOpen = true;
2020-02-05 20:57:43 +05:00
ops().then(() => {
this._transactionOpen = false;
2020-02-05 20:57:43 +05:00
});
if (!saveAfter) return this;
return this._save();
2020-02-05 20:57:43 +05:00
}
has(noteId) {
return this._topic.notes.findIndex(n => n === noteId) > -1;
2020-02-05 20:57:43 +05:00
}
async add(...noteIds) {
const topic = { ...this._topic };
2020-02-05 20:57:43 +05:00
for (let noteId of noteIds) {
let note = this._topics._notebooks._notes.note(noteId);
if (this.has(noteId) || !note) continue;
topic.notes.push(noteId);
2020-02-05 20:57:43 +05:00
if (note.notebook && note.notebook.id && note.notebook.topic) {
if (
note.notebook.id === this._topics.notebookId &&
note.notebook.topic === topic.title
2020-02-05 20:57:43 +05:00
)
return this;
await this._topics._notebooks
2020-02-05 20:57:43 +05:00
.topics(note.notebook.id)
.topic(note.notebook.topic)
.delete(note.id);
}
await this._topics._notebooks._notes.add({
2020-02-05 20:57:43 +05:00
id: noteId,
notebook: { id: this._topics._notebookId, topic: topic.title }
2020-02-05 20:57:43 +05:00
});
topic.totalNotes++;
2020-02-05 20:57:43 +05:00
}
return await this._save(topic);
2020-02-05 20:57:43 +05:00
}
async delete(...noteIds) {
const topic = { ...this._topic };
2020-02-05 20:57:43 +05:00
for (let noteId of noteIds) {
if (!this.has(noteId)) return this;
let index = topic.notes.findIndex(n => n === noteId);
topic.notes.splice(index, 1);
await this._topics._notebooks._notes.add({
2020-02-05 20:57:43 +05:00
id: noteId,
notebook: {}
});
topic.totalNotes--;
2020-02-05 20:57:43 +05:00
}
return await this._save(topic);
2020-02-05 20:57:43 +05:00
}
async _save(topic) {
if (this._transactionOpen) return this;
await this._topics.add(topic);
2020-02-06 18:47:42 +05:00
return this;
2020-02-05 20:57:43 +05:00
}
get all() {
return this._topic.notes
.map(note => {
let fullNote = this._topics._notebooks._notes.note(note);
if (fullNote) return fullNote.data;
})
.filter(v => v);
2020-02-05 20:57:43 +05:00
}
}