( monitorSlug: CheckIn['monitorSlug'], callback: () => T, upsertMonitorConfig?: MonitorConfig, )
| 212 | * to create a monitor automatically when sending a check in. |
| 213 | */ |
| 214 | export function withMonitor<T>( |
| 215 | monitorSlug: CheckIn['monitorSlug'], |
| 216 | callback: () => T, |
| 217 | upsertMonitorConfig?: MonitorConfig, |
| 218 | ): T { |
| 219 | function runCallback(): T { |
| 220 | const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig); |
| 221 | const now = timestampInSeconds(); |
| 222 | |
| 223 | function finishCheckIn(status: FinishedCheckIn['status']): void { |
| 224 | captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now }); |
| 225 | } |
| 226 | // Default behavior without isolateTrace |
| 227 | let maybePromiseResult: T; |
| 228 | try { |
| 229 | maybePromiseResult = callback(); |
| 230 | } catch (e) { |
| 231 | finishCheckIn('error'); |
| 232 | throw e; |
| 233 | } |
| 234 | |
| 235 | if (isThenable(maybePromiseResult)) { |
| 236 | return maybePromiseResult.then( |
| 237 | r => { |
| 238 | finishCheckIn('ok'); |
| 239 | return r; |
| 240 | }, |
| 241 | e => { |
| 242 | finishCheckIn('error'); |
| 243 | throw e; |
| 244 | }, |
| 245 | ) as T; |
| 246 | } |
| 247 | finishCheckIn('ok'); |
| 248 | |
| 249 | return maybePromiseResult; |
| 250 | } |
| 251 | |
| 252 | return withIsolationScope(() => (upsertMonitorConfig?.isolateTrace ? startNewTrace(runCallback) : runCallback())); |
| 253 | } |
| 254 | |
| 255 | /** |
| 256 | * Call `flush()` on the current client, if there is one. See {@link Client.flush}. |
no test coverage detected