UNPKG

benchling_typescript_sdk

Version:

Typescript SDK for Benchling API

62 lines (50 loc) 1.69 kB
export function chunkQueries<T extends Record<string, any>>( paramQuery: T, chunkSize: number, limitedKeys: (keyof NonNullable<T>)[] ): T[] { const presentKeys = limitedKeys.filter( (key) => key in paramQuery && typeof paramQuery[key] === "string" ); if (presentKeys.length === 0) { return [paramQuery]; } if (presentKeys.length === 1) { const key = presentKeys[0]; const values = (paramQuery[key] as string).split(",").map((v) => v.trim()); if (values.length <= chunkSize) { return [paramQuery]; } return chunkArray(values, chunkSize).map((chunk) => ({ ...paramQuery, [key]: chunk.join(","), // Rejoin the chunked array into a comma-separated string })); // console.log(res); } const keysWithMoreThanChunkSize = presentKeys.filter( (key) => (paramQuery[key] as string).split(",").length > chunkSize ); if (keysWithMoreThanChunkSize.length === 0) { return [paramQuery]; } if (keysWithMoreThanChunkSize.length === 1) { const key = keysWithMoreThanChunkSize[0]; const values = (paramQuery[key] as string).split(",").map((v) => v.trim()); return chunkArray(values, chunkSize).map((chunk) => ({ ...paramQuery, [key]: chunk.join(","), // Rejoin the chunked array into a comma-separated string })); } throw new Error( `More than one limited key has more than ${chunkSize} items: ${keysWithMoreThanChunkSize.join( ", " )}` ); } export function chunkArray<T>(array: T[], chunkSize: number): T[][] { const chunks: T[][] = []; for (let i = 0; i < array.length; i += chunkSize) { chunks.push(array.slice(i, i + chunkSize)); } return chunks; }