diff --git a/.gitignore b/.gitignore index 89e8234..87d6313 100644 --- a/.gitignore +++ b/.gitignore @@ -13,5 +13,3 @@ psd thumb sketch coverage - -lib diff --git a/.npmignore b/.npmignore index 62adcfa..87d6313 100644 --- a/.npmignore +++ b/.npmignore @@ -13,5 +13,3 @@ psd thumb sketch coverage - -src diff --git a/package.json b/package.json index acf6188..e169998 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { "name": "react-native-store", - "version": "0.4.1", + "version": "0.4.2", "description": "A simple database base on react-native AsyncStorage.", - "main": "./lib/index.js", + "main": "./src/index.js", "scripts": { "watch": "babel src --watch --presets es2015,stage-0 --out-dir lib", "build": "babel src --presets es2015,stage-0 --out-dir lib", diff --git a/src/model.js b/src/model.js index b460acc..dc01afa 100644 --- a/src/model.js +++ b/src/model.js @@ -84,6 +84,53 @@ class Model { return this.model.rows; } + // multi add or update + async multiAddOrUpdate(data, uniques) { + await this.initModel(); + for (var key in data) { + + // Update + + var existingRowIndex = -1; + + for (var i = 0; i < this.model.totalrows; i++) { + var isFound = true; + uniques.forEach((u_attr)=>{ + if (this.model.rows[i][u_attr] != data[u_attr]) { + isFound = false; + } + }); + + if (isFound) { + existingRowIndex = i; + break; + } + } + + if (existingRowIndex != -1) { + this.model.rows[existingRowIndex] = data; + continue; + } + + // Add + + var value = data[key]; + var autoinc = this.model.autoinc++; + if (this.model.rows[autoinc]) { + return Util.error("ReactNativeStore error: Storage already contains _id '" + autoinc + "'"); + } + if (value._id) { + return Util.error("ReactNativeStore error: Don't need _id with add method"); + } + value._id = autoinc; + this.model.rows[autoinc] = value; + this.model.totalrows++; + } + this.database[this.modelName] = this.model; + await AsyncStorage.setItem(this.dbName, JSON.stringify(this.database)); + return this.model.rows; + } + // update async update(data, filter) { await this.initModel();