[
  {
    "path": ".gitignore",
    "content": "# Logs\nlogs\n*.log\n\n# Runtime data\npids\n*.pid\n*.seed\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (http://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directory\n# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git\nnode_modules\n.idea\n.DS_Store\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\nnode_js:\n- '0.10'\nsudo: false\ncache:\n  directories:\n  - docs/vendor/bundle\n  - node_modules\nbefore_install:\n  npm install -g"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2015 thewei\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "![React Native DB Models](http://i58.tinypic.com/2akiqee.png) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fdarkrishabh%2Freact-native-db-models.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fdarkrishabh%2Freact-native-db-models?ref=badge_shield)\nReact Native DB Models\n===================\n![](https://travis-ci.org/darkrishabh/react-native-db-models.svg?branch=master) ![License](https://img.shields.io/badge/License-MIT-yellowgreen.svg)  [![npm version](https://badge.fury.io/js/react-native-db-models.svg)](http://badge.fury.io/js/react-native-db-models)\n----------\n\n\nThis wrapper is built on top of [React Native Store](https://github.com/thewei/react-native-store) and provides a better and improved Database layer for asynchronous DB transactions.\n\nReact Native DB Models fixes a lot of problems in react native store and also the DB class on top helps to provide more functionality and easy developing options.\n\n[![NPM](https://nodei.co/npm/react-native-db-models.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/react-native-db-models/)\n\n**New Feature added**\nDB Emitter added on all write operations to the models. Which helps you maintain a global storage and re-rendering capabilities for your app.\n\nCheck the new documentation\n\n----------\nUsage\n======================\n\nThe ideal way to use this library is to have a db.js in your applications somewhere. Which will be required.\n\n**DB.js**\n```\nvar RNDBModel = require('react-native-db-models')\n\nvar DB = {\n    \"app\": new RNDBModel.create_db('app'),\n    \"users\": new RNDBModel.create_db('users'),\n}\n\nmodule.exports = DB\n```\nand require it in your code -\n\n```\nvar React = require('react-native');\nvar DB = require('./db.js');\n// DB Emitter Initialized\n\nvar DBEvents = require('react-native-db-models').DBEvents\nvar {\n    AppRegistry,\n    StyleSheet,\n    Text,\n    View,\n    Image\n    } = React;\n    \n// Only \"all\" event emitter is available\n\nDBEvents.on(\"all\", function(){\n\tconsole.log(\"Database changed\");\n})\n\nvar App = React.createClass({\n\tget_users: function(){\n\t\tDB.users.get_all(function(result){\n\t\t\tconsole.log(result);\n\t\t})\n\t},\n\trender: function(){\n\t\treturn (\n\t\t<View>\n\t\t\t<Text onPress={this.get_users}> Hello </Text>\n\t\t</View>\n\t\t);\n\t}\n});\n```\nAll methods are async and therefore require a callback method.\n======================\nYou can check all the returned data from the callback. The returned data is more than expected so modify it as per your needs.\n\n----------\n**get**\n\n> **get(query_data, callback)**\n> query_data: The data to be matched. (eg. {name: \"John Doe\"})\n\nExample\n```\nDB.users.get({first_name: \"Rishabh\"}, function(results){\n\tconsole.log(results);\n})\n```\n----------\n**get_id**\n\n> **get_id(id, callback)**\n> id: ID of the object to be fetched.\n\nExample\n```\nDB.users.get_id(10, function(results){\n\tconsole.log(results);\n})\n```\n\n----------\n**get_all**\n\n> **get_all(callback)**\n> Gets the complete table for you.\n\nExample\n\n```\nDB.users.get_all(function(result){\n\t\t\tconsole.log(result);\n\t\t})\n```\n\n----------\n**remove**\n\n> **remove(query_data, callback)**\n> query_data: The data to be matched. (eg. {name: \"John Doe\"})\n\nExample\n```\nDB.users.remove({first_name: \"Rishabh\"}, function(removed_data){\n\tconsole.log(removed_data);\n})\n```\n\n----------\n**remove_id**\n\n> **remove_id(id, callback)**\n> id: ID of the object to be deleted.\n\nExample\n```\nDB.users.remove({first_name: \"Rishabh\"}, function(removed_data){\n\tconsole.log(removed_data);\n})\n```\n----------\n**add**\n\n> **add(data, callback)**\n> data: The data to be added. (eg. {name: \"John Doe\", age: 56})\n\nExample\n```\nDB.users.add({first_name: \"Rishabh\", age: 25}, function(added_data){\n\tconsole.log(added_data); \n})\n```\n\n\n----------\n**update**\n\n> **update(query_data, new_data, callback)**\n> query_data: The data to be matched. (eg. {name: \"John Doe\"})\n> new_data: The data to be updated. (eg. {age: 12})\n\nExample\n```\nDB.users.update({first_name: \"Rishabh\"}, {age: 25}, function(updated_table){\n\tconsole.log(updated_table);\n})\n```\n\n----------\n**update_id**\n\n> **update_id(id, new_data, callback)**\n> id: The id of the data to be matched.\n> new_data: The data to be updated. (eg. {name: \"Ken\"})\n\nExample\n```\nDB.users.update_id(3, {name: \"Ken\", age: 12}, function(updated_table){\n\tconsole.log(updated_table);\n})\n```\n----------\n**erase_db**\n\n> **erase_db(callback)**\n> Erases the complete table.\n\nExample\n```\nDB.users.erase_db(function(removed_data){\n\tconsole.log(removed_data);\n})\n```\n \n \n *More methods and features are gonna be added soon. Such as update, replace, constraints*\n\n----------\n\n\n\n## License\n[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fdarkrishabh%2Freact-native-db-models.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fdarkrishabh%2Freact-native-db-models?ref=badge_large)"
  },
  {
    "path": "__tests__/db_model_test.js",
    "content": "window.__DEV__ = true;\nwindow.Env = {};\n\njest.dontMock('../index');\n\ndescribe('db_model', function() {\n    it('checks if DB is created', function() {\n        true\n    });\n});\n"
  },
  {
    "path": "asyncstore.js",
    "content": "'use strict';\n\nvar React = require('react-native');\nvar Promise = require('promise-es6').Promise;\n\nvar AsyncStorage = React.AsyncStorage;\n\nvar reactNativeStore = {};\nvar dbName = \"db_store\";\n\nvar Model = function (tableName, databaseData) {\n    this.tableName = tableName;\n    this.databaseData = databaseData;\n    this._where = null;\n    this._limit = 100;\n    this._offset = 0;\n    return this;\n};\n\n\nreactNativeStore.createDataBase = function () {\n    var self = this;\n    return new Promise(function (resolve, reject) {\n\n        AsyncStorage.setItem(dbName, JSON.stringify({}), function (err) {\n            if (err) {\n                reject(err)\n            } else {\n                resolve();\n            }\n        });\n\n    });\n};\n\n\nreactNativeStore.saveTable = function (tableName, tableData) {\n    var self = this;\n    return new Promise(function (resolve, reject) {\n\n        self.getItem(dbName).then(function (databaseData) {\n            databaseData[tableName] = tableData || {\n                'totalrows': 0,\n                'autoinc': 1,\n                'rows': {}\n            };\n            AsyncStorage.setItem(dbName, JSON.stringify(databaseData), function (err) {\n                if (err) {\n                    reject(err)\n                } else {\n                    resolve(databaseData);\n                }\n            })\n        });\n\n    });\n}\n\n\nreactNativeStore.table = function (tableName) {\n    var self = this;\n    return new Promise(function (resolve, reject) {\n        return self.getItem(dbName).then(function (databaseData) {\n\n            if (!databaseData)\n                self.createDataBase().then(function () {\n                    self.saveTable(tableName).then(function (databaseData) {\n                        var model = new Model(tableName, databaseData ? databaseData : {});\n                        resolve(model);\n                    })\n                });\n            else {\n\n                if (!databaseData[tableName]) {\n                    self.saveTable(tableName).then(function (databaseData) {\n                        var model = new Model(tableName, databaseData ? databaseData : {});\n                        resolve(model);\n                    });\n                } else {\n                    var model = new Model(tableName, databaseData ? databaseData : {});\n                    resolve(model);\n                }\n            }\n        })\n    });\n}\n\nreactNativeStore.getItem = function (key) {\n    return new Promise(function (resolve, reject) {\n        AsyncStorage.getItem(key, function (err, res) {\n            if (err) {\n                reject(err);\n            } else {\n                resolve(JSON.parse(res));\n            }\n        });\n    });\n};\n\n// where\nModel.prototype.where = function (data) {\n    this._where = data || null;\n    return this;\n}\n\n// limit\nModel.prototype.limit = function (data) {\n    this._limit = data || 100;\n    return this;\n}\n\nModel.prototype.offset = function (data) {\n    this._offset = data || 0;\n    return this;\n}\n\nModel.prototype.init = function () {\n    this.where();\n    this.limit();\n    this.offset();\n    return this;\n}\n\nModel.prototype.update = function (data, callback) {\n    var me = this;\n    var results = [];\n    var rows = this.databaseData[this.tableName][\"rows\"];\n\n    var hasParams = false;\n    if (this._where) {\n        hasParams = true;\n    }\n    if (hasParams) {\n        for (var row in rows) {\n\n            var isMatch = true;\n\n            for (var key in this._where) {\n                if (rows[row][key] != this._where[key]) {\n                    isMatch = false;\n                }\n            }\n\n            if (isMatch) {\n\n                results.push(this.databaseData[this.tableName][\"rows\"][row][\"_id\"]);\n                for (var i in data) {\n                    this.databaseData[this.tableName][\"rows\"][row][i] = data[i];\n                }\n            }\n\n        }\n        reactNativeStore.saveTable(this.tableName, this.databaseData[this.tableName]).then(function (data) {\n            if (callback) {\n                callback(data)\n            }\n        }, function (err) {\n            if (callback) {\n                callback(err)\n            }\n        });\n        this.init();\n\n    } else {\n        if (callback) {\n            callback(null)\n        }\n    }\n};\n\nModel.prototype.updateById = function (id, data, callback) {\n\n    this.where({\n        _id: id\n    });\n\n    return this.update(data, callback);\n}\n\nModel.prototype.remove = function (callback) {\n\n    var results = [];\n    var rows = this.databaseData[this.tableName][\"rows\"];\n    var deleted_ids = [];\n    var hasParams = false;\n    if (this._where) {\n        hasParams = true;\n    }\n    var counter = 0;\n    if (hasParams) {\n        for (var row in rows) {\n            var isMatch = true;\n\n            for (var key in this._where) {\n\n                if (rows[row][key] != this._where[key]) {\n                    isMatch = false;\n                }\n            }\n            if (isMatch) {\n                counter += 1;\n                deleted_ids.push(this.databaseData[this.tableName][\"rows\"][row]['_id']);\n                delete this.databaseData[this.tableName][\"rows\"][row];\n                this.databaseData[this.tableName][\"totalrows\"]--;\n            }\n\n        }\n\n    } else {\n        counter = 0;\n        for (var row in rows) {\n            counter += 1;\n            deleted_ids.push(this.databaseData[this.tableName][\"rows\"][row]['_id']);\n            delete this.databaseData[this.tableName][\"rows\"][row];\n            this.databaseData[this.tableName][\"totalrows\"]--;\n        }\n    }\n    this.init();\n\n    if (counter === deleted_ids.length && callback) {\n        reactNativeStore.saveTable(this.tableName, this.databaseData[this.tableName]).then(function (data) {\n            if (callback) {\n                var return_data = {\n                    results: data,\n                    deleted_ids: deleted_ids\n                }\n                callback(return_data)\n            }\n        }, function (err) {\n            results.push(err)\n            if (callback) {\n                var return_data = {\n                    error: err,\n                    deleted_ids: deleted_ids\n                }\n                callback(return_data)\n            }\n        })\n    }\n    else if (callback && deleted_ids.length === 0) {\n        callback(null)\n    }\n\n};\n\nModel.prototype.removeById = function (id, callback) {\n\n    this.where({\n        _id: id\n    });\n\n    return this.remove(callback);\n}\n\nModel.prototype.add = function (data, callback) {\n    var autoinc = this.databaseData[this.tableName].autoinc;\n    data._id = autoinc;\n    this.databaseData[this.tableName].rows[autoinc] = data;\n    this.databaseData[this.tableName].autoinc += 1;\n    this.databaseData[this.tableName].totalrows += 1;\n    reactNativeStore.saveTable(this.tableName, this.databaseData[this.tableName]).then(function (added_data) {\n        if (callback) {\n            callback(data)\n        }\n    }, function (err) {\n        if (callback) {\n            callback(err)\n        }\n    });\n\n    this.init();\n}\n\nModel.prototype.multiAdd = function (data, callback) {\n    var self = this;\n\n    data.forEach(function(value, index){\n        var autoinc = self.databaseData[self.tableName].autoinc;\n        value._id = autoinc + index;\n        self.databaseData[self.tableName].rows[autoinc] = value;\n        self.databaseData[self.tableName].autoinc += 1;\n        self.databaseData[self.tableName].totalrows += 1;\n    });\n\n    reactNativeStore.saveTable(this.tableName, this.databaseData[this.tableName]).then(function (added_data) {\n        if (callback) {\n            callback(data)\n        }\n    }, function (err) {\n        if (callback) {\n            callback(err)\n        }\n    });\n\n    this.init();\n}\n\nModel.prototype.get = function (id) {\n    this.where({\n        _id: id\n    });\n    return this.find(1);\n}\n\nModel.prototype.find = function () {\n\n    var results = [];\n    var rows = this.databaseData[this.tableName][\"rows\"];\n\n    var hasParams = false;\n    if (this._where) {\n        hasParams = true;\n    }\n\n    if (hasParams) {\n        for (var row in rows) {\n            var isMatch = false;\n            for (var key in this._where) {\n                if (rows[row][key] == this._where[key]) {\n                    isMatch = true;\n                } else {\n                    isMatch = false;\n                    break;\n                }\n            }\n\n            if (isMatch) {\n                results.push(rows[row]);\n            }\n        }\n    } else {\n        for (var row in rows) {\n            results.push(rows[row]);\n        }\n    }\n\n    if (typeof(this._limit) == 'number') {\n        return results.slice(this._offset, this._limit + this._offset);\n    } else {\n        this.init();\n        return results;\n    }\n\n\n}\n\n\nmodule.exports = reactNativeStore;\n"
  },
  {
    "path": "index.js",
    "content": "'use strict';\n\nvar ReactNativeStore = require('./asyncstore');\nvar Events = require('eventemitter3')\nvar RNDBModel = {};\nRNDBModel.DBEvents = new Events()\n\nRNDBModel.create_db = function(db){\n    var me = this;\n    me.db_name = db;\n\n    /**\n     * @description Finds all the objects based on the query\n     * @param query_data\n     * @param callback\n     */\n    me.get = function(query_data, callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            var results = collection.where(query_data).find();\n            if(callback){\n                callback(results)\n            }\n        });\n    };\n\n    /**\n     * @description Finds by ID\n     * @param id\n     * @param callback\n     */\n    me.get_id = function(id, callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            var results = collection.get(id);\n            if(callback){\n                callback(results)\n            }\n        });\n    };\n\n    /**\n     * @description Gets all the data of the table\n     * @param callback\n     */\n    me.get_all = function( callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            var results = collection.databaseData[me.db_name];\n            if(callback){\n                callback(results)\n            }\n        });\n    };\n\n    /**\n     * @description Adds data to the Table in the DB\n     * @param data_to_add\n     * @param callback\n     */\n    me.add = function(data_to_add, callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            // Add Data\n            collection.add(data_to_add, function(added_data_id){\n                if(callback){\n                    callback(added_data_id)\n                }\n                RNDBModel.DBEvents.emit(\"all\")\n            });\n        });\n    };\n\n    /**\n     * @description Adds array of data (objects) to the Table in the DB\n     * @param data_to_add\n     * @param callback\n     */\n    me.add_all = function(data_to_add, callback){\n        var self = this;\n\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            // Add Data\n            collection.multiAdd(data_to_add, function(added_data){\n                if(callback){\n                    callback(added_data)\n                }\n                RNDBModel.DBEvents.emit(\"all\")\n            });\n        });\n    };\n\n    /**\n     * @description Removes all the objects matching the query\n     * @param query_data\n     * @param callback\n     */\n    me.remove = function(query_data, callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            collection.where(query_data).remove(function(data_removed){\n                if(callback){\n                    callback(data_removed);\n                }\n            });\n        });\n    };\n\n    /**\n     * @description Removed object by ID\n     * @param id\n     * @param callback\n     */\n    me.remove_id = function(id, callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            collection.removeById(id, function(data_removed){\n                if(callback){\n                    callback(data_removed);\n                }\n                RNDBModel.DBEvents.emit(\"all\")\n            });\n        });\n    };\n\n    /**\n     * @description Erases the complete DB\n     * @param callback\n     */\n    me.erase_db = function(callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            collection.remove(function(data_removed){\n                if(callback){\n                    callback(data_removed);\n                }\n                RNDBModel.DBEvents.emit(\"all\")\n            });\n        });\n    }\n    /**\n     * @description Updates the Table with the query\n     * @param query_data\n     * @param replace_data\n     * @param callback\n     */\n    me.update = function(query_data, replace_data, callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            collection.where(query_data).update(replace_data, function(data){\n                if(callback){\n                    callback(data);\n                }\n                RNDBModel.DBEvents.emit(\"all\")\n            });\n        });\n    };\n\n    /**\n     * @description Updates the DB Object by ID\n     * @param id\n     * @param replace_data\n     * @param callback\n     */\n    me.update_id = function(id, replace_data, callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            collection.updateById(id, replace_data, function(data){\n                if(callback){\n                    callback(data);\n                }\n                RNDBModel.DBEvents.emit(\"all\")\n            });\n        });\n    };\n\n    /**\n     * @description Removed object by ID\n     * @param id\n     * @param callback\n     */\n    me.remove_id = function(id, callback){\n        ReactNativeStore.table(me.db_name).then(function(collection){\n            collection.removeById(id, function(data_removed){\n                if(callback){\n                    callback(data_removed);\n                }\n                RNDBModel.DBEvents.emit(\"all\")\n            });\n        });\n    };\n\n};\n\nmodule.exports = RNDBModel;\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"react-native-db-models\",\n  \"version\": \"0.1.3\",\n  \"description\": \"Local DB Models for React Native Apps\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"jest\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/darkrishabh/react-native-db-models.git\"\n  },\n  \"keywords\": [\n    \"react native\",\n    \"AsyncStorage\",\n    \"database\",\n    \"local db\",\n    \"DB Events\",\n    \"rerender\",\n    \"Emmit database operations\",\n    \"models\",\n    \"data store\",\n    \"ios\"\n  ],\n  \"author\": \"rmehan\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/darkrishabh/react-native-db-models/issues\"\n  },\n  \"homepage\": \"https://github.com/darkrishabh/react-native-db-models\",\n  \"dependencies\": {\n    \"eventemitter3\": \"^1.1.1\",\n    \"promise-es6\": \"^0.1.0\",\n    \"util\": \"^0.10.3\"\n  },\n  \"devDependencies\": {\n    \"react-native\": \"^0.5.0\",\n    \"jest\": \"^0.1.40\",\n    \"jest-cli\": \"^0.4.13\"\n  }\n}\n"
  }
]