|
| 1 | +import { RDS_BASE_API_URL } from "../constants/urls"; |
| 2 | +import { UserBackend } from "../typeDefinitions/userBackend.types"; |
| 3 | +import * as response from "../constants/responses"; |
| 4 | + |
| 5 | +export const getDiscordIds = async ( |
| 6 | + userIds: string[] | string |
| 7 | +): Promise<string[] | string> => { |
| 8 | + try { |
| 9 | + const url = `${RDS_BASE_API_URL}/users/userId`; |
| 10 | + |
| 11 | + const numberOfBatches = Math.ceil(userIds.length / 6); |
| 12 | + |
| 13 | + const fetchCollection = [] as Array<Promise<Response>[]>; |
| 14 | + |
| 15 | + //for storing the data returned |
| 16 | + const fetchResponseCollection = [] as Array<UserBackend[]>; |
| 17 | + |
| 18 | + let indexCollection = 0; |
| 19 | + let numberOfFetchCalls = 0; |
| 20 | + |
| 21 | + const discordIds = [] as Array<string>; |
| 22 | + |
| 23 | + //adding all batch |
| 24 | + for (let i = 0; i < numberOfBatches; i++) { |
| 25 | + const batch: Promise<Response>[] = []; |
| 26 | + fetchCollection.push(batch); |
| 27 | + } |
| 28 | + |
| 29 | + //CF workers only allow 6 outgoing simultaneous request, so in order to retrieve all the data |
| 30 | + //we are making fetch calls in the batches of 6 |
| 31 | + |
| 32 | + for (let i = 0; i < userIds.length; i++) { |
| 33 | + fetchCollection[indexCollection].push(fetch(`${url}/${userIds[i]}`)); |
| 34 | + numberOfFetchCalls++; |
| 35 | + |
| 36 | + if (numberOfFetchCalls == 6) { |
| 37 | + indexCollection++; |
| 38 | + numberOfFetchCalls = 0; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + //now we will make parallel requests in the batches of 6. |
| 43 | + //and extract the data in response array |
| 44 | + |
| 45 | + for (let i = 0; i < numberOfBatches; i++) { |
| 46 | + const responses = await Promise.all(fetchCollection[i]); |
| 47 | + const json: Promise<UserBackend>[] = responses.map((response) => |
| 48 | + response.json() |
| 49 | + ); |
| 50 | + const data = await Promise.all(json); |
| 51 | + |
| 52 | + fetchResponseCollection.push(data); |
| 53 | + } |
| 54 | + |
| 55 | + //data contains arrays of User objects |
| 56 | + //we are looping over nested arrays and extracting discordIds |
| 57 | + |
| 58 | + fetchResponseCollection.forEach((dataArray: UserBackend[]) => { |
| 59 | + dataArray.forEach((data: UserBackend) => { |
| 60 | + if (data.user.discordId) { |
| 61 | + discordIds.push(data.user.discordId); |
| 62 | + } |
| 63 | + }); |
| 64 | + }); |
| 65 | + |
| 66 | + return discordIds; |
| 67 | + } catch (e) { |
| 68 | + return response.INTERNAL_SERVER_ERROR; |
| 69 | + } |
| 70 | +}; |
0 commit comments