( client: SmartThingsClient, limit: number, perRequestLimit: number, params: DeviceHistoryRequest, )
| 85 | export const calculateRequestLimit = (limit: number): number => limit > maxItemsPerRequest ? maxItemsPerRequest : limit |
| 86 | |
| 87 | export const getHistory = async ( |
| 88 | client: SmartThingsClient, |
| 89 | limit: number, |
| 90 | perRequestLimit: number, |
| 91 | params: DeviceHistoryRequest, |
| 92 | ): Promise<DeviceActivity[]> => { |
| 93 | // if limit is > ${maxHistoryItemsPerRequest} we need a loop; |
| 94 | // warn user if more than some number of requests will be made |
| 95 | if (limit > perRequestLimit) { |
| 96 | const requestsToMake = Math.ceil(limit / maxItemsPerRequest) |
| 97 | if (requestsToMake > maxRequestsBeforeWarning) { |
| 98 | // prompt user if it's okay to continue |
| 99 | const answer = await select({ |
| 100 | message: `Querying ${limit} history items will result in ${requestsToMake} requests.\n` + |
| 101 | 'Are you sure you want to continue?', |
| 102 | choices: [ |
| 103 | { name: 'Yes, I understand this might take a long time and/or hit API rate limits.', value: 'yes' }, |
| 104 | { name: 'No, cancel the request.', value: 'cancel' }, |
| 105 | { |
| 106 | name: `Continue but limit results to ${maxItemsPerRequest * maxRequestsBeforeWarning}`, |
| 107 | value: 'reduce', |
| 108 | }, |
| 109 | ], |
| 110 | }) |
| 111 | if (answer === 'reduce') { |
| 112 | limit = maxRequestsBeforeWarning * maxItemsPerRequest |
| 113 | } else if (answer === 'cancel') { |
| 114 | return cancelCommand('user canceled request') |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | const history = await client.history.devices(params) |
| 119 | const items: DeviceActivity[] = [...history.items] |
| 120 | while (items.length < limit && history.hasNext()) { |
| 121 | await history.next() |
| 122 | // The API allows the user to continue to view history from before the specified "after" |
| 123 | // with paging so we stop processing if we get items that come before the specified "after". |
| 124 | if ((params.after && history.items[0].epoch <= params.after)) { |
| 125 | break |
| 126 | } |
| 127 | items.push(...history.items.slice(0, limit - items.length)) |
| 128 | } |
| 129 | return items |
| 130 | } |
no test coverage detected