treojs/idb-request

Remove an item

Closed this issue · 1 comments

I have setup my collection to have a keyPath using the id of an item. How would I remove this using a store? My code is below but is not working. It is throwing a DataError: Data provided to an operation does not meet requirements.

async removeById(collection, id) {
  const txn = await this.createTransaction(collection);
  const store = txn.objectStore(collection);
  const request = store.get(id);
  let entity = undefined;

  // I am not sure this is correct to use a cursor since I am doing store.get()
  await requestCursor(request, cursor => {
    entity = cursor.value;
    cursor.continue();
  });

  if (!entity) {
    throw new NotFoundError(`An entity with id = ${id} was not found in the ${collection} `
      + `collection on the ${this.name} indexedDB database.`);
  }

  store.delete(id);
  await requestTransaction(txn);
  return entity;
}

I figured it out. This is how you would remove an item.

async removeById(collection, id) {
  const txn = await this.createTransaction(collection, true);
  const store = txn.objectStore(collection);
  const request = store.get(id);
  let entity = undefined;

  await requestCursor(request, (item, stop) => {
    entity = item;
    stop();
  });

  if (entity) {
    store.delete(id);
    await requestTransaction(txn);
  }

  return entity;
}