trilium/src/services/repository.js

81 lines
2.1 KiB
JavaScript
Raw Normal View History

const sql = require('./sql');
const protected_session = require('./protected_session');
const Note = require('../entities/note');
const NoteRevision = require('../entities/note_revision');
const NoteTree = require('../entities/note_tree');
const Attribute = require('../entities/attribute');
2018-01-31 09:12:19 +08:00
const sync_table = require('../services/sync_table');
class Repository {
constructor(dataKey) {
this.dataKey = protected_session.getDataKey(dataKey);
}
async getEntities(query, params = []) {
const rows = await sql.getRows(query, params);
for (const row of rows) {
row.dataKey = this.dataKey;
}
return rows.map(row => this.createEntityFromRow(row));
}
async getEntity(query, params = []) {
const row = await sql.getRowOrNull(query, params);
if (!row) {
return null;
}
row.dataKey = this.dataKey;
return this.createEntityFromRow(row);
}
async getNote(noteId) {
return await this.getEntity("SELECT * FROM notes WHERE noteId = ?", [noteId]);
}
createEntityFromRow(row) {
let entity;
if (row.attributeId) {
entity = new Attribute(this, row);
}
else if (row.noteRevisionId) {
entity = new NoteRevision(this, row);
}
else if (row.noteTreeId) {
entity = new NoteTree(this, row);
}
else if (row.noteId) {
entity = new Note(this, row);
}
else {
throw new Error('Unknown entity type for row: ' + JSON.stringify(row));
}
return entity;
}
2018-01-30 12:35:36 +08:00
async updateEntity(entity) {
if (entity.beforeSaving) {
entity.beforeSaving();
}
const clone = Object.assign({}, entity);
2018-01-30 12:35:36 +08:00
delete clone.dataKey;
delete clone.jsonContent;
delete clone.repository;
2018-01-31 10:25:47 +08:00
await sql.replace(entity.constructor.tableName, clone);
2018-01-31 09:12:19 +08:00
const primaryKey = entity[entity.constructor.primaryKeyName];
await sync_table.addEntitySync(entity.constructor.tableName, primaryKey);
2018-01-30 12:35:36 +08:00
}
}
module.exports = Repository;