trilium/src/services/script_context.js

68 lines
2.1 KiB
JavaScript
Raw Normal View History

const log = require('./log');
const protected_session = require('./protected_session');
const notes = require('./notes');
const attributes = require('./attributes');
const date_notes = require('./date_notes');
const Repository = require('./repository');
function ScriptContext(noteId, dataKey) {
this.dataKey = protected_session.getDataKey(dataKey);
this.repository = new Repository(dataKey);
this.getNoteById = async function(noteId) {
return this.repository.getNote(noteId);
};
2018-01-29 01:08:57 +08:00
this.getNotesWithAttribute = async function (attrName, attrValue) {
2018-01-30 09:57:55 +08:00
return await attributes.getNotesWithAttribute(this.dataKey, attrName, attrValue);
2018-01-29 01:08:57 +08:00
};
this.getNoteWithAttribute = async function (attrName, attrValue) {
2018-01-31 10:25:47 +08:00
const notes = await this.getNotesWithAttribute(attrName, attrValue);
2018-01-29 01:08:57 +08:00
return notes.length > 0 ? notes[0] : null;
};
2018-01-31 10:25:47 +08:00
this.createNote = async function (parentNoteId, name, jsonContent, extraOptions = {}) {
const note = {
2018-01-29 08:30:14 +08:00
title: name,
2018-01-31 10:25:47 +08:00
content: extraOptions.json ? JSON.stringify(jsonContent, null, '\t') : jsonContent,
target: 'into',
2018-01-29 08:30:14 +08:00
isProtected: extraOptions.isProtected !== undefined ? extraOptions.isProtected : false,
type: extraOptions.type,
mime: extraOptions.mime
};
if (extraOptions.json) {
note.type = "code";
note.mime = "application/json";
}
if (!note.type) {
note.type = "text";
2018-01-29 09:52:05 +08:00
note.mime = "text/html";
}
2018-01-31 10:25:47 +08:00
const noteId = (await notes.createNewNote(parentNoteId, note, this.dataKey)).noteId;
if (extraOptions.attributes) {
for (const attrName in extraOptions.attributes) {
await attributes.createAttribute(noteId, attrName, extraOptions.attributes[attrName]);
}
}
return noteId;
};
this.createAttribute = attributes.createAttribute;
2018-01-31 10:25:47 +08:00
this.updateEntity = this.repository.updateEntity;
this.log = function(message) {
log.info(`Script: ${message}`);
};
this.getDateNoteId = date_notes.getDateNoteId;
}
module.exports = ScriptContext;