Batch author numBooks updates at scan end via authors_num_books_updated

This commit is contained in:
mikiher 2026-07-10 17:37:31 +03:00
parent 7ee5e1bdf6
commit 9d9ab49664
6 changed files with 75 additions and 17 deletions

View file

@ -1,4 +1,4 @@
const { DataTypes, Model } = require('sequelize')
const { DataTypes, Model, fn, col } = require('sequelize')
class BookAuthor extends Model {
constructor(values, options) {
@ -37,6 +37,32 @@ class BookAuthor extends Model {
})
}
/**
* Get number of books for each author
*
* @param {string[]} authorIds
* @returns {Promise<Record<string, number>>}
*/
static async getCountsForAuthors(authorIds) {
if (!authorIds.length) return {}
const rows = await this.findAll({
attributes: ['authorId', [fn('COUNT', col('id')), 'count']],
where: {
authorId: authorIds
},
group: ['authorId'],
raw: true
})
/** @type {Record<string, number>} */
const counts = {}
for (const row of rows) {
counts[row.authorId] = Number(row.count)
}
return counts
}
/**
* Initialize model
* @param {import('../Database').sequelize} sequelize