From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- files/es/web/api/idbobjectstore/add/index.html | 193 +++++++++++++++++++++++ files/es/web/api/idbobjectstore/index.html | 207 +++++++++++++++++++++++++ 2 files changed, 400 insertions(+) create mode 100644 files/es/web/api/idbobjectstore/add/index.html create mode 100644 files/es/web/api/idbobjectstore/index.html (limited to 'files/es/web/api/idbobjectstore') diff --git a/files/es/web/api/idbobjectstore/add/index.html b/files/es/web/api/idbobjectstore/add/index.html new file mode 100644 index 0000000000..1a28ff194c --- /dev/null +++ b/files/es/web/api/idbobjectstore/add/index.html @@ -0,0 +1,193 @@ +--- +title: IDBObjectStore.add +slug: Web/API/IDBObjectStore/add +tags: + - API + - Add + - Almacenamiento + - Base de datos + - IDBObjectStore + - IndexedDB + - Referencia +translation_of: Web/API/IDBObjectStore/add +--- +

{{ APIRef("IDBObjectStore") }}

+
+

El metodo add() de la interfaz {{domxref("IDBObjectStore")}} retorna un objeto {{domxref("IDBRequest")}}, y, un hilo separado, crea un clone estructurado del valor, y almacena el valor clonado en el almacén de objetos. Esto es para agregar nevos registros a un almacén de objetos.

+

Para determinar si la operación de agregar fue completada satisfactoriamente, escucha el evento complete de la transaccion en adicion al evento success de la peticion IDBojectStore.add, porque la transaccion y todavía puede fallar después de lanzar el evento success. En otras palabras, el eventos success sólo es lanzado cuando la transacción ha sido puesta en cola satisfactoriamente.

+

El método agregar es un método de sólo inserción. Si un registro ya existe en el almacén de objetos con el argumento key como su clave, entonces un error ConstrainError es lanzado en el objeto petición devuelto. Para actualizar registros existentes, debes usar el método {{domxref("IDBObjectStore.put")}} en su lugar.

+
+

Sintaxis

+
var request = objectStore.add(myItem, optionalKey);
+

Retorno

+

Un objeto {{domxref("IDBRequest")}} en el que los eventos subsecuentes relacionados a esta operación son lanzados.

+

Excepciones

+

Este método puede generar un {{domxref("DOMException")}} con un {{domxref("DOMError")}} de uno de los siguiente tipos:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExcepciónDescripción
ReadOnlyErrorLa transacción asociada con esta operación está en un modo de sólo lectura.
TransactionInactiveErrorEsta transacción de {{domxref("IDBObjectStore")}}'s está inactiva.
DataError +

Cualquiera de los siguientes condiciones aplica:

+
    +
  • El almacén de objetos usa llaves en línea o tiene un generador de llaves, y una argumento llave fue proporcionado.
  • +
  • El almacén de objetos usa llaves fuera de línea y no tiene un generador de llaves, y un argumento llave fue proporcionado.
  • +
  • El almacén de objetos usa llaves en línea pero no un generador de llaves, y la ruta de la llave del almacén de objetos no da una llave válida.
  • +
  • El argumento llave fue proporcionado pero no contiene una llave válida.
  • +
+
InvalidStateErrorEl {{domxref("IDBObjectStore")}} ha sido borrado o removido.
DataCloneErrorLos datos siendo almacenados no pueden ser clonados por el algoritmo de clonado estructurado interno.
+

Ejemplo

+

En el siguiente código, abrimos una transacción read/write en nuestra base de datos y agregado algunos datos al almacén de datos usando add(). También ten en cuenta que las funciones adjuntas a los manejadores de eventos de la transacción para informar en la salida de la apertura de transacciones en el evento de éxito o falla. Para un ejemplo completo funcionando, mira nuestra aplicación To-do Notifications (ver ejemplo).

+
// Abrimos nuestra base de datos
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // Almacenar el resultado de la apertura de la base de datos en la variable db. Esta es usada mucho después
+  db = DBOpenRequest.result;
+
+  // Ejecuta la función addData() para agregar los datos
+  addData();
+};
+
+function addData() {
+  // Crea un nuevo objeto listo para ser insertado en la IDB
+  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];
+
+  // Inicia una transacción de lectura/escritura db transaction, lista para agregar los datos
+  var transaction = db.transaction(["toDoList"], "readwrite");
+
+  // Informa sobre el éxito de la inicio de la transacción
+  transaction.oncomplete = function(event) {
+    note.innerHTML += '<li>Transaction completed: database modification finished.</li>';
+  };
+
+
+  transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+  };
+
+  // Crea una almacén de objetos en la transacción
+  var objectStore = transaction.objectStore("toDoList");
+
+  // Agrega nuestro objeto newItem al almacén de objetos
+  var objectStoreRequest = objectStore.add(newItem[0]);
+
+  objectStoreRequest.onsuccess = function(event) {
+    //Informa sobre el éxito de nuestro nuevo elemento en la base de datos
+    note.innerHTML += '<li>New item added to database.</li>';
+  };
+};
+

Parámetros

+
+
+ value
+
+ El valor para ser almacenado.
+
+ key
+
+ La llave a usar para identificar el registro. Si no es especificada, el resultado es nulo.
+
+

Especificación

+ + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('IndexedDB', '#widl-IDBObjectStore-add-IDBRequest-any-value-any-key', 'add()')}}{{Spec2('IndexedDB')}} 
+

Compatibilidad de navegadores

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Soporte básico23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
+
+
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Soporte básico4.4{{CompatGeckoMobile("22.0")}}1.0.11022{{CompatNo}}
+
+

Ver también

+ diff --git a/files/es/web/api/idbobjectstore/index.html b/files/es/web/api/idbobjectstore/index.html new file mode 100644 index 0000000000..32bb499284 --- /dev/null +++ b/files/es/web/api/idbobjectstore/index.html @@ -0,0 +1,207 @@ +--- +title: IDBObjectStore +slug: Web/API/IDBObjectStore +tags: + - API +translation_of: Web/API/IDBObjectStore +--- +

{{APIRef("IndexedDB")}}

+ +
+

The IDBObjectStore interface of the IndexedDB API represents an object store in a database. Records within an object store are sorted according to their keys. This sorting enables fast insertion, look-up, and ordered retrieval.

+
+ +

Methods

+ +
+
{{domxref("IDBObjectStore.add")}}
+
Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store.
+
{{domxref("IDBObjectStore.clear")}}
+
Creates and immediately returns an {{domxref("IDBRequest")}} object, and clears this object store in a separate thread. This is for deleting all current records out of an object store.
+
{{domxref("IDBObjectStore.delete")}}
+
returns an {{domxref("IDBRequest")}} object, and, in a separate thread, deletes the current object store. This is for deleting individual records out of an object store.
+
{{domxref("IDBObjectStore.get")}}
+
returns an {{domxref("IDBRequest")}} object, and, in a separate thread, returns the object store selected by the specified key. This is for retrieving specific records from an object store.
+
{{domxref("IDBObjectStore.createIndex")}}
+
Creates a new index during a version upgrade, returning a new {{domxref("IDBIndex")}} object in the connected database.
+
{{domxref("IDBObjectStore.deleteIndex")}}
+
Destroys the specified index in the connected database, used during a version upgrade.
+
{{domxref("IDBObjectStore.index")}}
+
Opens an index from this object store after which it can, for example, be used to return a sequence of records sorted by that index using a cursor.
+
{{domxref("IDBObjectStore.put")}}
+
Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for updating existing records in an object store when the transaction's mode is readwrite.
+
{{domxref("IDBObjectStore.openCursor")}} 
+
Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, returns a new {{domxref("IDBCursorWithValue")}} object. Used for iterating through an object store by primary key with a cursor.
+
+ +

Properties

+ +
+
{{domxref("IDBObjectStore.indexNames")}} {{readonlyInline}}
+
A list of the names of indexes on objects in this object store.
+
{{domxref("IDBObjectStore.keyPath")}} {{readonlyInline}}
+
The key path of this object store. If this attribute is null, the application must provide a key for each modification operation.
+
{{domxref("IDBObjectStore.name")}} {{readonlyInline}}
+
The name of this object store.
+
{{domxref("IDBObjectStore.transaction")}} {{readonlyInline}}
+
The name of the transaction to which this object store belongs.
+
{{domxref("IDBObjectStore.autoIncrement")}} {{readonlyInline}}
+
The value of the auto increment flag for this object store.
+
+ +

Obsolete methods

+ +
+
{{domxref("IDBObjectStore.openKeyCursor")}} 
+
Returns an {{domxref("IDBRequest")}} object, and, in a separate thread, returns a new {{domxref("IDBCursorWithValue")}}. Used for iterating through an object store with a key. However, this is now handled by {{domxref("IDBObjectStore.openCursor")}}, if a value is specified.
+
+ +

Example

+ +

This example shows a variety of different uses of ObjectStores, from updating the data structure with {{domxref("IDBObjectStore.createIndex")}} inside an onupgradeneeded function, to adding a new item to our object store with {{domxref("IDBObjectStore.add")}}. For a full working example, see our To-do Notifications app (view example live.)

+ +
// Let us open our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in the db variable.
+  db = DBOpenRequest.result;
+};
+
+// This event handles the event whereby a new version of the database needs to be created
+// Either one has not been created before, or a new version number has been submitted via the
+// window.indexedDB.open line above
+DBOpenRequest.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  db.onerror = function(event) {
+    note.innerHTML += '<li>Error loading database.</li>';
+  };
+
+  // Create an objectStore for this database
+
+  var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" });
+
+  // define what data items the objectStore will contain
+
+  objectStore.createIndex("hours", "hours", { unique: false });
+  objectStore.createIndex("minutes", "minutes", { unique: false });
+  objectStore.createIndex("day", "day", { unique: false });
+  objectStore.createIndex("month", "month", { unique: false });
+  objectStore.createIndex("year", "year", { unique: false });
+
+  objectStore.createIndex("notified", "notified", { unique: false });
+
+  note.innerHTML += '<li>Object store created.</li>';
+};
+
+// Create a new item to add in to the object store
+var newItem = [
+  { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: 'December', year: 2013, notified: "no" }
+];
+
+// open a read/write db transaction, ready for adding the data
+var transaction = db.transaction(["toDoList"], "readwrite");
+
+// report on the success of opening the transaction
+transaction.oncomplete = function(event) {
+  note.innerHTML += '<li>Transaction opened for task addition.</li>';
+};
+
+transaction.onerror = function(event) {
+  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
+};
+
+// create an object store on the transaction
+var objectStore = transaction.objectStore("toDoList");
+// add our newItem object to the object store
+var objectStoreRequest = objectStore.add(newItem[0]);
+
+objectStoreRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>New item added to database.</li>';
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBObjectStore', 'IDBObjectStore')}}{{Spec2('IndexedDB')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.11022{{CompatNo}}
+
+ +

See also

+ + -- cgit v1.2.3-54-g00ecf