Notes/src/services/script_context.js

75 lines
2.5 KiB
JavaScript
Raw Normal View History

const log = require('./log');
const noteService = require('./notes');
2018-02-24 22:44:45 -05:00
const sql = require('./sql');
const utils = require('./utils');
2018-04-02 20:46:46 -04:00
const dateUtils = require('./date_utils');
const labelService = require('./labels');
const dateNoteService = require('./date_notes');
const config = require('./config');
2018-03-31 09:07:58 -04:00
const repository = require('./repository');
const axios = require('axios');
function ScriptContext(startNote, allNotes) {
this.modules = {};
this.notes = utils.toObject(allNotes, note => [note.noteId, note]);
this.apis = utils.toObject(allNotes, note => [note.noteId, new ScriptApi(startNote, note)]);
this.require = moduleNoteIds => {
return moduleName => {
const candidates = allNotes.filter(note => moduleNoteIds.includes(note.noteId));
const note = candidates.find(c => c.title === moduleName);
if (!note) {
throw new Error("Could not find module note " + moduleName);
}
return this.modules[note.noteId].exports;
}
};
}
function ScriptApi(startNote, currentNote) {
this.startNote = startNote;
this.currentNote = currentNote;
2018-03-04 10:32:53 -05:00
2018-03-04 12:06:35 -05:00
this.axios = axios;
this.utils = {
unescapeHtml: utils.unescapeHtml,
2018-04-02 20:46:46 -04:00
isoDateTimeStr: dateUtils.dateStr,
isoDateStr: date => dateUtils.dateStr(date).substr(0, 10)
};
this.getInstanceName = () => config.General ? config.General.instanceName : null;
2018-04-01 12:45:35 -04:00
this.getNote = repository.getNote;
this.getBranch = repository.getBranch;
this.getLabel = repository.getLabel;
this.getImage = repository.getImage;
this.getEntity = repository.getEntity;
this.getEntities = repository.getEntities;
this.getNotesWithLabel = async function (labelName, labelValue) {
return await labelService.getNotesWithLabel(labelName, labelValue);
2018-01-28 12:08:57 -05:00
};
this.getNoteWithLabel = async function (labelName, labelValue) {
const notes = await this.getNotesWithLabel(labelName, labelValue);
2018-01-28 12:08:57 -05:00
return notes.length > 0 ? notes[0] : null;
};
this.createNote = async function(parentNoteId, title, content = "", extraOptions = {}) {
return await noteService.createNote(parentNoteId, title, content, extraOptions);
};
this.createLabel = labelService.createLabel;
this.log = message => log.info(`Script ${currentNote.noteId}: ${message}`);
this.getRootCalendarNoteId = dateNoteService.getRootCalendarNoteId;
this.getDateNoteId = dateNoteService.getDateNoteId;
2018-02-24 22:44:45 -05:00
this.transaction = sql.doInTransaction;
}
module.exports = ScriptContext;