2020-08-12 17:08:37 -04:00
|
|
|
const moment = require("moment");
|
|
|
|
const knex = require("../knex");
|
|
|
|
const Snippet = require("./Snippet");
|
2017-12-24 15:04:08 -05:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {String} trigger
|
|
|
|
* @returns {Promise<Snippet>}
|
|
|
|
*/
|
|
|
|
async function getSnippet(trigger) {
|
2020-08-12 17:08:37 -04:00
|
|
|
const snippet = await knex("snippets")
|
|
|
|
.where("trigger", trigger)
|
2017-12-24 15:04:08 -05:00
|
|
|
.first();
|
|
|
|
|
|
|
|
return (snippet ? new Snippet(snippet) : null);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {String} trigger
|
|
|
|
* @param {String} body
|
|
|
|
* @returns {Promise<void>}
|
|
|
|
*/
|
2018-09-20 15:54:47 -04:00
|
|
|
async function addSnippet(trigger, body, createdBy = 0) {
|
2017-12-24 15:04:08 -05:00
|
|
|
if (await getSnippet(trigger)) return;
|
|
|
|
|
2020-08-12 17:08:37 -04:00
|
|
|
return knex("snippets").insert({
|
2017-12-24 15:04:08 -05:00
|
|
|
trigger,
|
|
|
|
body,
|
|
|
|
created_by: createdBy,
|
2020-08-12 17:08:37 -04:00
|
|
|
created_at: moment.utc().format("YYYY-MM-DD HH:mm:ss")
|
2017-12-24 15:04:08 -05:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {String} trigger
|
2017-12-31 19:16:05 -05:00
|
|
|
* @returns {Promise<void>}
|
2017-12-24 15:04:08 -05:00
|
|
|
*/
|
|
|
|
async function deleteSnippet(trigger) {
|
2020-08-12 17:08:37 -04:00
|
|
|
return knex("snippets")
|
|
|
|
.where("trigger", trigger)
|
2017-12-24 15:04:08 -05:00
|
|
|
.delete();
|
|
|
|
}
|
|
|
|
|
2017-12-31 19:16:05 -05:00
|
|
|
/**
|
|
|
|
* @returns {Promise<Snippet[]>}
|
|
|
|
*/
|
2017-12-24 15:04:08 -05:00
|
|
|
async function getAllSnippets() {
|
2020-08-12 17:08:37 -04:00
|
|
|
const snippets = await knex("snippets")
|
2017-12-24 15:04:08 -05:00
|
|
|
.select();
|
|
|
|
|
|
|
|
return snippets.map(s => new Snippet(s));
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
get: getSnippet,
|
|
|
|
add: addSnippet,
|
|
|
|
del: deleteSnippet,
|
|
|
|
all: getAllSnippets,
|
|
|
|
};
|