@ -2,46 +2,62 @@ const Sequelize = require('sequelize')
const Database = require ( '../../Database' )
module . exports = {
/ * *
* Get authors total count
*
* @ param { string } libraryId
* @ returns { Promise < number > } count
* /
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 } }
*
* @ param { string } libraryId
* @ param { number } limit
* @ returns { Promise < { id : string , name : string , count : number } > }
* /
async getAuthorsWithCount ( libraryId ) {
const authors = await Database . authorModel . findAll ( {
where : [
async getAuthorsWithCount ( libraryId , limit ) {
const authors = await Database . bookA uthorModel. findAll ( {
includ e: [
{
libraryId
} ,
Sequelize . where ( Sequelize . literal ( 'count' ) , {
[ Sequelize . Op . gt ] : 0
} )
] ,
attributes : [
'id' ,
'name' ,
[ Sequelize . literal ( '(SELECT count(*) FROM bookAuthors ba WHERE ba.authorId = author.id)' ) , 'count' ]
model : Database . authorModel ,
as : 'author' , // Use the correct alias as defined in your associations
attributes : [ 'name' ] ,
where : {
libraryId : libraryId
}
}
] ,
order : [
[ 'count' , 'DESC' ]
]
attributes : [ 'authorId' , [ Sequelize . fn ( 'COUNT' , Sequelize . col ( 'authorId' ) ) , 'count' ] ] ,
group : [ 'authorId' , 'author.id' ] , // Include 'author.id' to satisfy GROUP BY with JOIN
order : [ [ Sequelize . literal ( 'count' ) , 'DESC' ] ] ,
limit : limit
} )
return authors . map ( au => {
return authors . map ( ( au ) => {
return {
id : au . i d,
name : au . name ,
count : au . dataValues . count
id : au . authorI d,
name : au . author . name ,
count : au . get ( 'count' ) // Use get method to access aliased attributes
}
} )
} ,
/ * *
* Search authors
* @ param { string } libraryId
* @ param { string } query
*
* @ param { string } libraryId
* @ param { string } query
* @ param { number } limit
* @ param { number } offset
* @ returns { o bject[ ] } oldAuthor with numBooks
* @ returns { Promise < O bject[ ] > } oldAuthor with numBooks
* /
async search ( libraryId , query , limit , offset ) {
const authors = await Database . authorModel . findAll ( {
@ -52,9 +68,7 @@ module.exports = {
libraryId
} ,
attributes : {
include : [
[ Sequelize . literal ( '(SELECT count(*) FROM bookAuthors ba WHERE ba.authorId = author.id)' ) , 'numBooks' ]
]
include : [ [ Sequelize . literal ( '(SELECT count(*) FROM bookAuthors ba WHERE ba.authorId = author.id)' ) , 'numBooks' ] ]
} ,
limit ,
offset