/** @module controllers */
const BaseDatabaseController = require("./BaseDatabaseController");
/** Class representing a author controller. */
class AuthorController extends BaseDatabaseController {
/** Create a author controller. */
constructor() {
super();
}
/**
* Get an author by id.
*
* @param {number} id
* @returns {Promise<object>}
*/
async byId(id) {
const authorResponse = await this._query('SELECT * FROM authors WHERE id = ?', id);
if (authorResponse.length !== 1) {
return null;
}
return authorResponse[0];
}
/**
* Get an author by name.
*
* @param {string} name
* @returns {Promise<object>}
*/
async byName(name) {
const authorResponse = await this._query('SELECT * FROM authors WHERE name = ?', name);
if (authorResponse.length !== 1) {
return null;
}
return authorResponse[0];
}
/**
* Get authors by book.
*
* @param {number} bookId
* @returns {Promise<object[]>}
*/
async byBook(bookId) {
const authorsResponse = await this._query('SELECT * FROM authors AS a JOIN books_authors AS ba WHERE a.id = ba.authors_id AND ba.books_id = ?', bookId);
return authorsResponse;
}
/**
* Insert an author.
*
* @param {string} name
* @param {string} personalName
* @returns {Promise<object>}
*/
async insert(name, personalName) {
const response = await this._query('INSERT INTO authors (name, personal_name) VALUES (?, ?)', name, personalName);
return await this.byId(response.insertId);
}
/**
* Link an author to a book.
*
* @param {number} authorId
* @param {number} bookId
* @returns {Promise<void>}
*/
async linkAuthorBook(authorId, bookId) {
await this._query('INSERT INTO books_authors (books_id, authors_id) VALUES (?, ?)', bookId, authorId);
}
}
module.exports = AuthorController;