trilium/src/services/repository.js

83 lines
2 KiB
JavaScript
Raw Normal View History

2018-03-31 21:07:58 +08:00
"use strict";
const sql = require('./sql');
const syncTableService = require('../services/sync_table');
let entityConstructor;
async function setEntityConstructor(constructor) {
entityConstructor = constructor;
}
2018-03-31 21:07:58 +08:00
async function getEntities(query, params = []) {
const rows = await sql.getRows(query, params);
return rows.map(entityConstructor);
2018-03-31 21:07:58 +08:00
}
async function getEntity(query, params = []) {
const row = await sql.getRowOrNull(query, params);
2018-03-31 21:07:58 +08:00
if (!row) {
return null;
}
return entityConstructor(row);
2018-03-31 21:07:58 +08:00
}
2018-03-31 21:07:58 +08:00
async function getNote(noteId) {
return await getEntity("SELECT * FROM notes WHERE noteId = ?", [noteId]);
2018-03-31 21:07:58 +08:00
}
2018-01-30 12:35:36 +08:00
2018-04-01 11:08:22 +08:00
async function getBranch(branchId) {
return await getEntity("SELECT * FROM branches WHERE branchId = ?", [branchId]);
}
async function getImage(imageId) {
return await getEntity("SELECT * FROM images WHERE imageId = ?", [imageId]);
}
2018-04-01 23:42:12 +08:00
async function getLabel(labelId) {
return await getEntity("SELECT * FROM labels WHERE labelId = ?", [labelId]);
}
async function getRelation(relationId) {
return await getEntity("SELECT * FROM relations WHERE relationId = ?", [relationId]);
}
async function getOption(name) {
return await getEntity("SELECT * FROM options WHERE name = ?", [name]);
}
2018-03-31 21:07:58 +08:00
async function updateEntity(entity) {
if (entity.beforeSaving) {
2018-04-02 00:45:35 +08:00
await entity.beforeSaving();
2018-03-31 21:07:58 +08:00
}
2018-01-30 12:35:36 +08:00
2018-03-31 21:07:58 +08:00
const clone = Object.assign({}, entity);
2018-01-30 12:35:36 +08:00
2018-03-31 21:07:58 +08:00
delete clone.jsonContent;
2018-01-31 09:12:19 +08:00
await sql.transactional(async () => {
2018-04-02 00:45:35 +08:00
await sql.replace(entity.constructor.tableName, clone);
2018-01-31 09:12:19 +08:00
2018-04-02 00:45:35 +08:00
const primaryKey = entity[entity.constructor.primaryKeyName];
2018-03-31 21:07:58 +08:00
2018-05-23 07:29:18 +08:00
if (entity.constructor.tableName !== 'options' || entity.isSynced) {
await syncTableService.addEntitySync(entity.constructor.tableName, primaryKey);
}
2018-04-02 00:45:35 +08:00
});
}
2018-03-31 21:07:58 +08:00
module.exports = {
getEntities,
getEntity,
getNote,
2018-04-01 11:08:22 +08:00
getBranch,
getImage,
2018-04-01 23:42:12 +08:00
getLabel,
getRelation,
getOption,
updateEntity,
setEntityConstructor
2018-03-31 21:07:58 +08:00
};