({
thread,
onboardingTimestamp,
token,
lastExternalMessageId,
logger,
}: {
thread: threads;
lastExternalMessageId?: string;
onboardingTimestamp: Date;
token: string;
logger: Logger;
})
| 166 | } |
| 167 | |
| 168 | async function crawlExistingThread({ |
| 169 | thread, |
| 170 | onboardingTimestamp, |
| 171 | token, |
| 172 | lastExternalMessageId, |
| 173 | logger, |
| 174 | }: { |
| 175 | thread: threads; |
| 176 | lastExternalMessageId?: string; |
| 177 | onboardingTimestamp: Date; |
| 178 | token: string; |
| 179 | logger: Logger; |
| 180 | }) { |
| 181 | const messagesInThread: DiscordMessage[] = []; |
| 182 | |
| 183 | const threadId = thread.externalThreadId; |
| 184 | if (!threadId) { |
| 185 | logger.error({ |
| 186 | 'crawlExistingThread finished': 'missing externalThreadId', |
| 187 | }); |
| 188 | return []; |
| 189 | } |
| 190 | |
| 191 | let hasMore = true; |
| 192 | // before will have the last messageId from request to be used on next pagination request |
| 193 | let before; |
| 194 | // cursor/after should be the first messageId receive from the last run |
| 195 | let after = lastExternalMessageId; |
| 196 | while (hasMore) { |
| 197 | const query = { |
| 198 | // before should have priority because the API always return messages sort by timestamp desc |
| 199 | // so in the second run we will have a cursor assign, we should use it to get messages from the cursorId forward |
| 200 | // but if there is more than the limit, we will need to paginate backwards, so in case of hasMore |
| 201 | // we will need to use the "before" parameter, that has the oldest message from the latest batch |
| 202 | ...(before ? { before } : { after }), |
| 203 | }; |
| 204 | // if query has after, it means we should clean up the after variable to receive a new cursor |
| 205 | if ('after' in query) { |
| 206 | after = undefined; |
| 207 | } |
| 208 | |
| 209 | // messages are return in desc timestamp order |
| 210 | const [err, response] = await to( |
| 211 | DiscordApi.getMessages({ |
| 212 | limit: LIMIT, |
| 213 | externalId: threadId, |
| 214 | query, |
| 215 | token, |
| 216 | }) |
| 217 | ); |
| 218 | if (err) { |
| 219 | logger.error({ crawlExistingThread: err }); |
| 220 | return []; |
| 221 | } |
| 222 | const messages = response as DiscordMessage[]; |
| 223 | // if there is less than the limit, means that there is no more messages |
| 224 | if (messages.length < LIMIT) { |
| 225 | hasMore = false; |
no test coverage detected