| 17 | }; |
| 18 | |
| 19 | async function task({ logger }: { logger: Logger }) { |
| 20 | let incrementId = 999999999; |
| 21 | logger.time('thread-messages-count'); |
| 22 | do { |
| 23 | const threads = await prisma.threads.findMany({ |
| 24 | select: { |
| 25 | messages: { select: { id: true } }, |
| 26 | messageCount: true, |
| 27 | id: true, |
| 28 | incrementId: true, |
| 29 | }, |
| 30 | where: { incrementId: { lt: incrementId } }, |
| 31 | orderBy: { incrementId: 'desc' }, |
| 32 | take: batchSize, |
| 33 | }); |
| 34 | const queries = []; |
| 35 | for (let thread of threads) { |
| 36 | if (!thread.messages.length || thread.messages.length === 0) { |
| 37 | logger.log({ 'thread will be deleted': thread.id }); |
| 38 | queries.push( |
| 39 | prisma.threads.delete({ |
| 40 | where: { id: thread.id }, |
| 41 | }) |
| 42 | ); |
| 43 | } else if (thread.messageCount !== thread.messages.length) { |
| 44 | logger.log({ 'thread will be updated': thread.id }); |
| 45 | queries.push( |
| 46 | prisma.threads.update({ |
| 47 | where: { id: thread.id }, |
| 48 | data: { messageCount: thread.messages.length }, |
| 49 | }) |
| 50 | ); |
| 51 | } |
| 52 | } |
| 53 | logger.timeLog('thread-messages-count'); |
| 54 | await prisma.$transaction(queries); |
| 55 | if (threads.length === batchSize) { |
| 56 | incrementId = threads[batchSize - 1].incrementId; |
| 57 | logger.log({ incrementId }); |
| 58 | } else { |
| 59 | break; |
| 60 | } |
| 61 | } while (true); |
| 62 | logger.timeEnd('thread-messages-count'); |
| 63 | } |