master 2d5551530b73 cached
8 files
21.1 KB
5.2k tokens
1 requests
Download .txt
Repository: darkrishabh/react-native-db-models
Branch: master
Commit: 2d5551530b73
Files: 8
Total size: 21.1 KB

Directory structure:
gitextract_wa48d5y5/

├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── __tests__/
│   └── db_model_test.js
├── asyncstore.js
├── index.js
└── package.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Logs
logs
*.log

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules
.idea
.DS_Store


================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- '0.10'
sudo: false
cache:
  directories:
  - docs/vendor/bundle
  - node_modules
before_install:
  npm install -g

================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2015 thewei

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
![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)
React Native DB Models
===================
![](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)
----------


This 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.

React 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.

[![NPM](https://nodei.co/npm/react-native-db-models.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/react-native-db-models/)

**New Feature added**
DB Emitter added on all write operations to the models. Which helps you maintain a global storage and re-rendering capabilities for your app.

Check the new documentation

----------
Usage
======================

The ideal way to use this library is to have a db.js in your applications somewhere. Which will be required.

**DB.js**
```
var RNDBModel = require('react-native-db-models')

var DB = {
    "app": new RNDBModel.create_db('app'),
    "users": new RNDBModel.create_db('users'),
}

module.exports = DB
```
and require it in your code -

```
var React = require('react-native');
var DB = require('./db.js');
// DB Emitter Initialized

var DBEvents = require('react-native-db-models').DBEvents
var {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image
    } = React;
    
// Only "all" event emitter is available

DBEvents.on("all", function(){
	console.log("Database changed");
})

var App = React.createClass({
	get_users: function(){
		DB.users.get_all(function(result){
			console.log(result);
		})
	},
	render: function(){
		return (
		<View>
			<Text onPress={this.get_users}> Hello </Text>
		</View>
		);
	}
});
```
All methods are async and therefore require a callback method.
======================
You can check all the returned data from the callback. The returned data is more than expected so modify it as per your needs.

----------
**get**

> **get(query_data, callback)**
> query_data: The data to be matched. (eg. {name: "John Doe"})

Example
```
DB.users.get({first_name: "Rishabh"}, function(results){
	console.log(results);
})
```
----------
**get_id**

> **get_id(id, callback)**
> id: ID of the object to be fetched.

Example
```
DB.users.get_id(10, function(results){
	console.log(results);
})
```

----------
**get_all**

> **get_all(callback)**
> Gets the complete table for you.

Example

```
DB.users.get_all(function(result){
			console.log(result);
		})
```

----------
**remove**

> **remove(query_data, callback)**
> query_data: The data to be matched. (eg. {name: "John Doe"})

Example
```
DB.users.remove({first_name: "Rishabh"}, function(removed_data){
	console.log(removed_data);
})
```

----------
**remove_id**

> **remove_id(id, callback)**
> id: ID of the object to be deleted.

Example
```
DB.users.remove({first_name: "Rishabh"}, function(removed_data){
	console.log(removed_data);
})
```
----------
**add**

> **add(data, callback)**
> data: The data to be added. (eg. {name: "John Doe", age: 56})

Example
```
DB.users.add({first_name: "Rishabh", age: 25}, function(added_data){
	console.log(added_data); 
})
```


----------
**update**

> **update(query_data, new_data, callback)**
> query_data: The data to be matched. (eg. {name: "John Doe"})
> new_data: The data to be updated. (eg. {age: 12})

Example
```
DB.users.update({first_name: "Rishabh"}, {age: 25}, function(updated_table){
	console.log(updated_table);
})
```

----------
**update_id**

> **update_id(id, new_data, callback)**
> id: The id of the data to be matched.
> new_data: The data to be updated. (eg. {name: "Ken"})

Example
```
DB.users.update_id(3, {name: "Ken", age: 12}, function(updated_table){
	console.log(updated_table);
})
```
----------
**erase_db**

> **erase_db(callback)**
> Erases the complete table.

Example
```
DB.users.erase_db(function(removed_data){
	console.log(removed_data);
})
```
 
 
 *More methods and features are gonna be added soon. Such as update, replace, constraints*

----------



## License
[![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)

================================================
FILE: __tests__/db_model_test.js
================================================
window.__DEV__ = true;
window.Env = {};

jest.dontMock('../index');

describe('db_model', function() {
    it('checks if DB is created', function() {
        true
    });
});


================================================
FILE: asyncstore.js
================================================
'use strict';

var React = require('react-native');
var Promise = require('promise-es6').Promise;

var AsyncStorage = React.AsyncStorage;

var reactNativeStore = {};
var dbName = "db_store";

var Model = function (tableName, databaseData) {
    this.tableName = tableName;
    this.databaseData = databaseData;
    this._where = null;
    this._limit = 100;
    this._offset = 0;
    return this;
};


reactNativeStore.createDataBase = function () {
    var self = this;
    return new Promise(function (resolve, reject) {

        AsyncStorage.setItem(dbName, JSON.stringify({}), function (err) {
            if (err) {
                reject(err)
            } else {
                resolve();
            }
        });

    });
};


reactNativeStore.saveTable = function (tableName, tableData) {
    var self = this;
    return new Promise(function (resolve, reject) {

        self.getItem(dbName).then(function (databaseData) {
            databaseData[tableName] = tableData || {
                'totalrows': 0,
                'autoinc': 1,
                'rows': {}
            };
            AsyncStorage.setItem(dbName, JSON.stringify(databaseData), function (err) {
                if (err) {
                    reject(err)
                } else {
                    resolve(databaseData);
                }
            })
        });

    });
}


reactNativeStore.table = function (tableName) {
    var self = this;
    return new Promise(function (resolve, reject) {
        return self.getItem(dbName).then(function (databaseData) {

            if (!databaseData)
                self.createDataBase().then(function () {
                    self.saveTable(tableName).then(function (databaseData) {
                        var model = new Model(tableName, databaseData ? databaseData : {});
                        resolve(model);
                    })
                });
            else {

                if (!databaseData[tableName]) {
                    self.saveTable(tableName).then(function (databaseData) {
                        var model = new Model(tableName, databaseData ? databaseData : {});
                        resolve(model);
                    });
                } else {
                    var model = new Model(tableName, databaseData ? databaseData : {});
                    resolve(model);
                }
            }
        })
    });
}

reactNativeStore.getItem = function (key) {
    return new Promise(function (resolve, reject) {
        AsyncStorage.getItem(key, function (err, res) {
            if (err) {
                reject(err);
            } else {
                resolve(JSON.parse(res));
            }
        });
    });
};

// where
Model.prototype.where = function (data) {
    this._where = data || null;
    return this;
}

// limit
Model.prototype.limit = function (data) {
    this._limit = data || 100;
    return this;
}

Model.prototype.offset = function (data) {
    this._offset = data || 0;
    return this;
}

Model.prototype.init = function () {
    this.where();
    this.limit();
    this.offset();
    return this;
}

Model.prototype.update = function (data, callback) {
    var me = this;
    var results = [];
    var rows = this.databaseData[this.tableName]["rows"];

    var hasParams = false;
    if (this._where) {
        hasParams = true;
    }
    if (hasParams) {
        for (var row in rows) {

            var isMatch = true;

            for (var key in this._where) {
                if (rows[row][key] != this._where[key]) {
                    isMatch = false;
                }
            }

            if (isMatch) {

                results.push(this.databaseData[this.tableName]["rows"][row]["_id"]);
                for (var i in data) {
                    this.databaseData[this.tableName]["rows"][row][i] = data[i];
                }
            }

        }
        reactNativeStore.saveTable(this.tableName, this.databaseData[this.tableName]).then(function (data) {
            if (callback) {
                callback(data)
            }
        }, function (err) {
            if (callback) {
                callback(err)
            }
        });
        this.init();

    } else {
        if (callback) {
            callback(null)
        }
    }
};

Model.prototype.updateById = function (id, data, callback) {

    this.where({
        _id: id
    });

    return this.update(data, callback);
}

Model.prototype.remove = function (callback) {

    var results = [];
    var rows = this.databaseData[this.tableName]["rows"];
    var deleted_ids = [];
    var hasParams = false;
    if (this._where) {
        hasParams = true;
    }
    var counter = 0;
    if (hasParams) {
        for (var row in rows) {
            var isMatch = true;

            for (var key in this._where) {

                if (rows[row][key] != this._where[key]) {
                    isMatch = false;
                }
            }
            if (isMatch) {
                counter += 1;
                deleted_ids.push(this.databaseData[this.tableName]["rows"][row]['_id']);
                delete this.databaseData[this.tableName]["rows"][row];
                this.databaseData[this.tableName]["totalrows"]--;
            }

        }

    } else {
        counter = 0;
        for (var row in rows) {
            counter += 1;
            deleted_ids.push(this.databaseData[this.tableName]["rows"][row]['_id']);
            delete this.databaseData[this.tableName]["rows"][row];
            this.databaseData[this.tableName]["totalrows"]--;
        }
    }
    this.init();

    if (counter === deleted_ids.length && callback) {
        reactNativeStore.saveTable(this.tableName, this.databaseData[this.tableName]).then(function (data) {
            if (callback) {
                var return_data = {
                    results: data,
                    deleted_ids: deleted_ids
                }
                callback(return_data)
            }
        }, function (err) {
            results.push(err)
            if (callback) {
                var return_data = {
                    error: err,
                    deleted_ids: deleted_ids
                }
                callback(return_data)
            }
        })
    }
    else if (callback && deleted_ids.length === 0) {
        callback(null)
    }

};

Model.prototype.removeById = function (id, callback) {

    this.where({
        _id: id
    });

    return this.remove(callback);
}

Model.prototype.add = function (data, callback) {
    var autoinc = this.databaseData[this.tableName].autoinc;
    data._id = autoinc;
    this.databaseData[this.tableName].rows[autoinc] = data;
    this.databaseData[this.tableName].autoinc += 1;
    this.databaseData[this.tableName].totalrows += 1;
    reactNativeStore.saveTable(this.tableName, this.databaseData[this.tableName]).then(function (added_data) {
        if (callback) {
            callback(data)
        }
    }, function (err) {
        if (callback) {
            callback(err)
        }
    });

    this.init();
}

Model.prototype.multiAdd = function (data, callback) {
    var self = this;

    data.forEach(function(value, index){
        var autoinc = self.databaseData[self.tableName].autoinc;
        value._id = autoinc + index;
        self.databaseData[self.tableName].rows[autoinc] = value;
        self.databaseData[self.tableName].autoinc += 1;
        self.databaseData[self.tableName].totalrows += 1;
    });

    reactNativeStore.saveTable(this.tableName, this.databaseData[this.tableName]).then(function (added_data) {
        if (callback) {
            callback(data)
        }
    }, function (err) {
        if (callback) {
            callback(err)
        }
    });

    this.init();
}

Model.prototype.get = function (id) {
    this.where({
        _id: id
    });
    return this.find(1);
}

Model.prototype.find = function () {

    var results = [];
    var rows = this.databaseData[this.tableName]["rows"];

    var hasParams = false;
    if (this._where) {
        hasParams = true;
    }

    if (hasParams) {
        for (var row in rows) {
            var isMatch = false;
            for (var key in this._where) {
                if (rows[row][key] == this._where[key]) {
                    isMatch = true;
                } else {
                    isMatch = false;
                    break;
                }
            }

            if (isMatch) {
                results.push(rows[row]);
            }
        }
    } else {
        for (var row in rows) {
            results.push(rows[row]);
        }
    }

    if (typeof(this._limit) == 'number') {
        return results.slice(this._offset, this._limit + this._offset);
    } else {
        this.init();
        return results;
    }


}


module.exports = reactNativeStore;


================================================
FILE: index.js
================================================
'use strict';

var ReactNativeStore = require('./asyncstore');
var Events = require('eventemitter3')
var RNDBModel = {};
RNDBModel.DBEvents = new Events()

RNDBModel.create_db = function(db){
    var me = this;
    me.db_name = db;

    /**
     * @description Finds all the objects based on the query
     * @param query_data
     * @param callback
     */
    me.get = function(query_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.where(query_data).find();
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Finds by ID
     * @param id
     * @param callback
     */
    me.get_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.get(id);
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Gets all the data of the table
     * @param callback
     */
    me.get_all = function( callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.databaseData[me.db_name];
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Adds data to the Table in the DB
     * @param data_to_add
     * @param callback
     */
    me.add = function(data_to_add, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            // Add Data
            collection.add(data_to_add, function(added_data_id){
                if(callback){
                    callback(added_data_id)
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Adds array of data (objects) to the Table in the DB
     * @param data_to_add
     * @param callback
     */
    me.add_all = function(data_to_add, callback){
        var self = this;

        ReactNativeStore.table(me.db_name).then(function(collection){
            // Add Data
            collection.multiAdd(data_to_add, function(added_data){
                if(callback){
                    callback(added_data)
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Removes all the objects matching the query
     * @param query_data
     * @param callback
     */
    me.remove = function(query_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.where(query_data).remove(function(data_removed){
                if(callback){
                    callback(data_removed);
                }
            });
        });
    };

    /**
     * @description Removed object by ID
     * @param id
     * @param callback
     */
    me.remove_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.removeById(id, function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Erases the complete DB
     * @param callback
     */
    me.erase_db = function(callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.remove(function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    }
    /**
     * @description Updates the Table with the query
     * @param query_data
     * @param replace_data
     * @param callback
     */
    me.update = function(query_data, replace_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.where(query_data).update(replace_data, function(data){
                if(callback){
                    callback(data);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Updates the DB Object by ID
     * @param id
     * @param replace_data
     * @param callback
     */
    me.update_id = function(id, replace_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.updateById(id, replace_data, function(data){
                if(callback){
                    callback(data);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Removed object by ID
     * @param id
     * @param callback
     */
    me.remove_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.removeById(id, function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

};

module.exports = RNDBModel;


================================================
FILE: package.json
================================================
{
  "name": "react-native-db-models",
  "version": "0.1.3",
  "description": "Local DB Models for React Native Apps",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/darkrishabh/react-native-db-models.git"
  },
  "keywords": [
    "react native",
    "AsyncStorage",
    "database",
    "local db",
    "DB Events",
    "rerender",
    "Emmit database operations",
    "models",
    "data store",
    "ios"
  ],
  "author": "rmehan",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/darkrishabh/react-native-db-models/issues"
  },
  "homepage": "https://github.com/darkrishabh/react-native-db-models",
  "dependencies": {
    "eventemitter3": "^1.1.1",
    "promise-es6": "^0.1.0",
    "util": "^0.10.3"
  },
  "devDependencies": {
    "react-native": "^0.5.0",
    "jest": "^0.1.40",
    "jest-cli": "^0.4.13"
  }
}
Download .txt
gitextract_wa48d5y5/

├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── __tests__/
│   └── db_model_test.js
├── asyncstore.js
├── index.js
└── package.json
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (23K chars).
[
  {
    "path": ".gitignore",
    "chars": 542,
    "preview": "# Logs\nlogs\n*.log\n\n# Runtime data\npids\n*.pid\n*.seed\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nl"
  },
  {
    "path": ".travis.yml",
    "chars": 142,
    "preview": "language: node_js\nnode_js:\n- '0.10'\nsudo: false\ncache:\n  directories:\n  - docs/vendor/bundle\n  - node_modules\nbefore_ins"
  },
  {
    "path": "LICENSE",
    "chars": 1073,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2015 thewei\n\nPermission is hereby granted, free of charge, to any person obtaining "
  },
  {
    "path": "README.md",
    "chars": 4820,
    "preview": "![React Native DB Models](http://i58.tinypic.com/2akiqee.png) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bg"
  },
  {
    "path": "__tests__/db_model_test.js",
    "chars": 175,
    "preview": "window.__DEV__ = true;\nwindow.Env = {};\n\njest.dontMock('../index');\n\ndescribe('db_model', function() {\n    it('checks if"
  },
  {
    "path": "asyncstore.js",
    "chars": 8819,
    "preview": "'use strict';\n\nvar React = require('react-native');\nvar Promise = require('promise-es6').Promise;\n\nvar AsyncStorage = Re"
  },
  {
    "path": "index.js",
    "chars": 5169,
    "preview": "'use strict';\n\nvar ReactNativeStore = require('./asyncstore');\nvar Events = require('eventemitter3')\nvar RNDBModel = {};"
  },
  {
    "path": "package.json",
    "chars": 912,
    "preview": "{\n  \"name\": \"react-native-db-models\",\n  \"version\": \"0.1.3\",\n  \"description\": \"Local DB Models for React Native Apps\",\n  "
  }
]

About this extraction

This page contains the full source code of the darkrishabh/react-native-db-models GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (21.1 KB), approximately 5.2k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!