Skip to content

jscottnz/db4js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 

Repository files navigation

db4js

A Simple light DB for Javascript

Usage

var Db = require('./db');

Load from (empty) file:

var myDb = Db.create();
myDb.loadFromFile("my.db", {
	keyField : "id",
	indexes : {
		id : Db.indexBuilders.fromKey
	}
}, "id");

Read by ID:

var id = "abcd"
myDb.get("id", id).then(function(data) {
	if(data.indexItems)
		doSomeThing(data.indexItems[0][0])
	else
		error("not found")
}, function(message) {
	error(message);
})

Save:

myDb.save("id", object, errorCB, true).then(function(data) {
		doSomething(data)
})

API

loadFromFile = function(path, metadata, keyField)

loadData = function(data, metadata)

save = function(key, data, error, reindex)

delete = function(key, error)

listKeys = function(forKey, options)

get = function(index, key)

search = function(index, input, keyField, limit)

Index Builders

indexBuilders.fromKey

indexBuilders.fromField

indexBuilders.fromAlias

indexBuilders.fromRecursive

indexBuilders.trigramFromIndex

Example 1

var itemsDb = Db.create();
var itemMetaData = {
	keyField : "text",
	indexes : {
		name : Db.indexBuilders.fromKey,
		unit : function(key, data) {
			return Db.indexBuilders.fromField(key, data, function(obj) {
				return obj.units;
			});
		},
		search : function(index, data) {
			return Db.indexBuilders.fromKey(index, data)
			.then(function(data) { 
				return Db.indexBuilders.trigramFromIndex(index, data)
			});
		},
		count : function(key, data) {
			return Db.indexBuilders.fromField(key, data, function(obj) {
				return obj.count;
			});
		}
	}
};
itemMetaData.indexes.count.sort = function(a, b){return a-b};
itemsDb.loadFromFile(dataFile, itemMetaData, 'text');

Example 2

var recipeDb = Db.create();
var recipeMetaData = {
	keyField : "name",
	indexes : {
		recipeName : Db.indexBuilders.fromKey,
		recipeSearch : function(index, data) {
			return Db.indexBuilders.fromKey(index, data)
			.then(function(data) { 
				return Db.indexBuilders.trigramFromIndex(index, data)
			});
		},
		recipeIngredients : function(key, data) {
			return Db.indexBuilders.fromField(key, data, function(obj) {
				var toReturn = [];
				for (var i = obj.ingredients.length - 1; i >= 0; i--) {
					for (var j = obj.ingredients[i].length - 1; j >= 0; j--) {
						toReturn.push(obj.ingredients[i].i[j])
					};
				};

				return toReturn;
			} );
		}
	}
}

recipeDb.loadFromFile(recipeFile, recipeMetaData, 'name');

About

A Simple light DB for Javascript

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published