Skip to content
This repository has been archived by the owner on Feb 21, 2023. It is now read-only.

multiAddOrUpdate #57

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,3 @@ psd
thumb
sketch
coverage

lib
2 changes: 0 additions & 2 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,3 @@ psd
thumb
sketch
coverage

src
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
47 changes: 47 additions & 0 deletions src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down