/** @module controllers */
const BaseDatabaseController = require("./BaseDatabaseController");
/** Class representing a term controller. */
class TermController extends BaseDatabaseController {
/** Create a term controller. */
constructor() {
super();
}
/**
* Get an term by id.
*
* @param {number} id
* @returns {Promise<object>}
*/
async byId(id) {
const termResponse = await this._query('SELECT * FROM terms WHERE id = ?', id);
if (termResponse.length !== 1) {
return null;
}
return termResponse[0];
}
/**
* Get an term by the term's text.
*
* @param {string} term
* @returns {Promise<object>}
*/
async byTermText(term) {
const termResponse = await this._query('SELECT * FROM terms WHERE term = ?', term);
if (termResponse.length !== 1) {
return null;
}
return termResponse[0];
}
/**
* Insert a term.
*
* @param {string} term
* @returns {Promise<object>}
*/
async insert(term) {
const response = await this._query('INSERT INTO terms (term) VALUES (?)', term.term);
return await this.byId(response.insertId);
}
/**
* Insert many terms.
*
* @param {string[]} terms
* @returns {Promise<number[]>}
*/
async insertMany(terms) {
await this._startTransaction();
const insertIds = [];
for (const term of terms) {
const insertResponse = await this._query('INSERT INTO terms (term) VALUES (?)', term);
insertIds.push(insertResponse.insertId);
}
await this._endTransaction();
return insertIds;
}
/**
* Link a term to a book.
*
* @param {number} termId
* @param {number} bookId
* @returns {Promise<void>}
*/
async linkTermBook(termId, bookId) {
await this._query('INSERT INTO books_terms (books_id, terms_id) VALUES (?, ?)', bookId, termId);
}
}
module.exports = TermController;