* Utility: Split a date range into chunks to avoid timeout issues with large imports * Returns array of [from, to] date pairs in YYYY-MM-DD format * * @param from - Start date in YYYY-MM-DD format * @param to - End date in YYYY-MM-DD format * @param chunkSizeDays - Number of days per
(
from: string,
to: string,
options?: {
chunkSizeDays?: number;
},
)
| 76 | * @param chunkSizeDays - Number of days per chunk (default: 1) |
| 77 | */ |
| 78 | public getDateChunks( |
| 79 | from: string, |
| 80 | to: string, |
| 81 | options?: { |
| 82 | chunkSizeDays?: number; |
| 83 | }, |
| 84 | ): Array<[string, string]> { |
| 85 | const chunks: Array<[string, string]> = []; |
| 86 | |
| 87 | const startDate = new Date(from); |
| 88 | const endDate = new Date(to); |
| 89 | const chunkSizeDays = options?.chunkSizeDays ?? 1; |
| 90 | |
| 91 | // Handle case where from and to are the same date |
| 92 | if (startDate.getTime() === endDate.getTime()) { |
| 93 | return [[from, to]]; |
| 94 | } |
| 95 | |
| 96 | const cursor = new Date(startDate); |
| 97 | |
| 98 | while (cursor <= endDate) { |
| 99 | const chunkStart = cursor.toISOString().split('T')[0]!; |
| 100 | |
| 101 | // Calculate chunk end: move forward by (chunkSizeDays - 1) to get the last day of the chunk |
| 102 | const chunkEndDate = new Date(cursor); |
| 103 | chunkEndDate.setDate(chunkEndDate.getDate() + (chunkSizeDays - 1)); |
| 104 | |
| 105 | // Don't go past the end date |
| 106 | const chunkEnd = |
| 107 | chunkEndDate > endDate |
| 108 | ? endDate.toISOString().split('T')[0]! |
| 109 | : chunkEndDate.toISOString().split('T')[0]!; |
| 110 | |
| 111 | chunks.push([chunkStart, chunkEnd]); |
| 112 | |
| 113 | // Move cursor to the next chunk start (after the current chunk) |
| 114 | cursor.setDate(cursor.getDate() + chunkSizeDays); |
| 115 | |
| 116 | if (cursor > endDate) break; |
| 117 | } |
| 118 | |
| 119 | return chunks; |
| 120 | } |
| 121 | } |