From 95cdb23efbab63d3acccc28f0c891f8c3b3403f5 Mon Sep 17 00:00:00 2001 From: CoffeeKnyte <67730400+CoffeeKnyte@users.noreply.github.com> Date: Tue, 30 Apr 2024 11:14:55 -0400 Subject: [PATCH] split getAuthorsWithCount to 2 lighter functions getAuthorsWithCount - now only gets the top 10 authors (in that library) by number of books getAuthorsTotalCount - new function to only get total number of authors (in that library) --- server/utils/queries/authorFilters.js | 49 +++++++++++++++++---------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/server/utils/queries/authorFilters.js b/server/utils/queries/authorFilters.js index c6a08a61..e13158fe 100644 --- a/server/utils/queries/authorFilters.js +++ b/server/utils/queries/authorFilters.js @@ -2,35 +2,48 @@ const Sequelize = require('sequelize') const Database = require('../../Database') module.exports = { + /** + * Get authors total count + * @param {string} libraryId + * @returns {{id:string, name:string, count:number}} + */ + async getAuthorsTotalCount(libraryId) { + const authorsCount = await Database.authorModel.count({ + where: { + libraryId: libraryId + } + }); + return authorsCount; + }, + /** * Get authors with count of num books * @param {string} libraryId * @returns {{id:string, name:string, count:number}} */ async getAuthorsWithCount(libraryId) { - const authors = await Database.authorModel.findAll({ - where: [ - { - libraryId - }, - Sequelize.where(Sequelize.literal('count'), { - [Sequelize.Op.gt]: 0 - }) - ], + const authors = await Database.bookAuthorModel.findAll({ + include: [{ + model: Database.authorModel, + as: 'author', // Use the correct alias as defined in your associations + attributes: ['name'], + where: { + libraryId: libraryId + } + }], attributes: [ - 'id', - 'name', - [Sequelize.literal('(SELECT count(*) FROM bookAuthors ba WHERE ba.authorId = author.id)'), 'count'] + 'authorId', + [Sequelize.fn('COUNT', Sequelize.col('authorId')), 'count'] ], - order: [ - ['count', 'DESC'] - ] + group: ['authorId', 'author.id'], // Include 'author.id' to satisfy GROUP BY with JOIN + order: [[Sequelize.literal('count'), 'DESC']], + limit: 10 }) return authors.map(au => { return { - id: au.id, - name: au.name, - count: au.dataValues.count + id: au.authorId, + name: au.author.name, + count: au.get('count') // Use get method to access aliased attributes } }) },