* Updates one or more items in the collection using a callback function
(
keys: (TKey | unknown) | Array<TKey | unknown>,
configOrCallback:
| ((draft: WritableDeep<TInput>) => void)
| ((drafts: Array<WritableDeep<TInput>>) => void)
| OperationConfig,
maybeCallback?:
| ((draft: WritableDeep<TInput>) => void)
| ((drafts: Array<WritableDeep<TInput>>) => void),
)
| 265 | * Updates one or more items in the collection using a callback function |
| 266 | */ |
| 267 | update( |
| 268 | keys: (TKey | unknown) | Array<TKey | unknown>, |
| 269 | configOrCallback: |
| 270 | | ((draft: WritableDeep<TInput>) => void) |
| 271 | | ((drafts: Array<WritableDeep<TInput>>) => void) |
| 272 | | OperationConfig, |
| 273 | maybeCallback?: |
| 274 | | ((draft: WritableDeep<TInput>) => void) |
| 275 | | ((drafts: Array<WritableDeep<TInput>>) => void), |
| 276 | ) { |
| 277 | if (typeof keys === `undefined`) { |
| 278 | throw new MissingUpdateArgumentError() |
| 279 | } |
| 280 | |
| 281 | const state = this.state |
| 282 | this.lifecycle.validateCollectionUsable(`update`) |
| 283 | |
| 284 | const ambientTransaction = getActiveTransaction() |
| 285 | |
| 286 | // If no ambient transaction exists, check for an onUpdate handler early |
| 287 | if (!ambientTransaction && !this.config.onUpdate) { |
| 288 | throw new MissingUpdateHandlerError() |
| 289 | } |
| 290 | |
| 291 | const isArray = Array.isArray(keys) |
| 292 | const keysArray = isArray ? keys : [keys] |
| 293 | |
| 294 | if (isArray && keysArray.length === 0) { |
| 295 | throw new NoKeysPassedToUpdateError() |
| 296 | } |
| 297 | |
| 298 | const callback = |
| 299 | typeof configOrCallback === `function` ? configOrCallback : maybeCallback! |
| 300 | const config = |
| 301 | typeof configOrCallback === `function` ? {} : configOrCallback |
| 302 | |
| 303 | // Get the current objects or empty objects if they don't exist |
| 304 | const currentObjects = keysArray.map((key) => { |
| 305 | const item = this.state.get(key) |
| 306 | if (!item) { |
| 307 | throw new UpdateKeyNotFoundError(key) |
| 308 | } |
| 309 | |
| 310 | return item |
| 311 | }) as unknown as Array<TInput> |
| 312 | |
| 313 | let changesArray |
| 314 | if (isArray) { |
| 315 | // Use the proxy to track changes for all objects |
| 316 | changesArray = withArrayChangeTracking( |
| 317 | currentObjects, |
| 318 | callback as (draft: Array<TInput>) => void, |
| 319 | ) |
| 320 | } else { |
| 321 | const result = withChangeTracking( |
| 322 | currentObjects[0]!, |
| 323 | callback as (draft: TInput) => void, |
| 324 | ) |
nothing calls this directly
no test coverage detected