Skip to content

Commit

Permalink
Fix some bugs, update README.md, add context
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrieljmj committed Nov 1, 2015
1 parent 7e85522 commit 2d22512
Show file tree
Hide file tree
Showing 7 changed files with 137 additions and 20 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules/
npm-debug.log
test*
src/model_class.js
src/model_class.js
.test.context.json
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
jatabase
=========
This is advisable when you need a local simple database without any security -- is a JSON file.
![](https://img.shields.io/badge/status-development-red.svg) ![](https://img.shields.io/npm/v/jatabase.svg)

**Status**: Development
This is advisable when you need a local simple database without any security -- is a JSON file.

## Installing
```console
$ npm install jatabase --save
```

![](https://nodei.co/npm/jatabase.png?downloads=true&downloadRank=true&stars=true)

## Usage
All the persistence methods use promises, so they have an async way of using and a sync way.

Expand Down Expand Up @@ -210,4 +212,7 @@ productsModel.has(5);

// Using another fields
productsModel.has({name: 'Pear TV'});
```
```

# License
[MIT License](https://github.com/gabrieljmj/jatabase/blob/dev/LICENSE.md) 2015 © Gabriel Jacinto.
10 changes: 5 additions & 5 deletions src/jsondb.js → src/_json.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,21 @@

var fs = require('fs');

var JsonDB = function (file) {
var _Json = function (file) {
validateFile(file);

this.file = file;
};

JsonDB.prototype.update = function (data) {
return fs.writeFile(this.file, JSON.stringify(data, null, ' '), 'utf8', function (err) {
_Json.prototype.update = function (data) {
return fs.writeFile(this.file, JSON.stringify(data), 'utf8', function (err) {
if (err != null) {
throw Error(err);
}
});
};

JsonDB.prototype.updateKey = function (key, value) {
_Json.prototype.updateKey = function (key, value) {
let data = require(this.file);
data[key] = value;

Expand All @@ -45,4 +45,4 @@ let validateFile = function (file) {
});
};

module.exports = JsonDB;
module.exports = _Json;
78 changes: 78 additions & 0 deletions src/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Jatabase
*
* @author Gabriel Jacinto <gamjj74@hotmail.com>
* @license MIT License
* @package jatabase
*/

'use strict';

var _json = require('./_json'),
fs = require('fs');

let Context = function (file) {
validateFile(file);

this.file = file;
this._json = new _json(file);
};

/**
* Set the last insert ID of a collection
*
* @param {String} from
* @param {Integer} id
*/
Context.prototype.setLastInsertId = function (from, id) {
let contextFromCollection = getContextFromCollection(this, from, true);
contextFromCollection['last_insert_id'] = id;

this._json.updateKey(from, contextFromCollection);
};

/**
* Return the last ID of a collection
*
* @param {String} from
*
* @return {Integer}
*/
Context.prototype.lastInsertId = function (from) {
let contextFromCollection = getContextFromCollection(this, from, true);

return contextFromCollection.last_insert_id;
};

let getContextFromCollection = function (Context, from, create) {
let context = require(Context.file);

if (typeof context[from] == 'undefined') {
if (!create) {
throw Error('Context for ' + from + ' not found.');
}

context[from] = {last_insert_id: null};
}

return context[from];
};

/**
* Verify if the file exists and if is a JSON
*
* @param {String} file
*/
let validateFile = function (file) {
if (fileParts[fileParts.length - 1].toLowerCase() != 'json') {
throw Error('File must have .json extension.');
}

fs.stat(file, function(err, stat) {
if (err != null && err.code == 'ENOENT') {
throw Error('File does not exists: ' + file);
}
});
};

module.exports = Context;
32 changes: 27 additions & 5 deletions src/jatabase.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@

'use strict';

var model = require('./model');
var model = require('./model'),
fs = require('fs'),
path = require('path'),
Context = require('./context');

var jatabase = function (file) {
let jatabase = function (file) {
this.file = file;
};

Expand All @@ -23,15 +26,34 @@ var jatabase = function (file) {
* @return {Model}
*/
jatabase.prototype.createModel = function (collection, fields) {
var newModel = function (db, collection) {
let newModel = function (db, collection, _fields, context) {
this.file = db;
this.collection = collection;
this.fields = fields;
this.fields = _fields;
this.context = context;
};

newModel.prototype = new model;

return new newModel(this.file, collection);
return new newModel(this.file, collection, fields, createContext(this.file));
};

let createContext = function (file) {
let dir = path.dirname(file),
fileName = path.basename(file, '.json'),
contextFile = dir + '/.' + fileName + '.context.json';

fs.stat(contextFile, function(err, stat) {
if (err != null && err.code == 'ENOENT') {
fs.writeFile(contextFile, JSON.stringify({users: []}), function (err) {
if (err !== null) {
console.error(err);
}
});
}
});

return new Context(contextFile);
};

module.exports = jatabase;
11 changes: 6 additions & 5 deletions src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
'use strict';

var fs = require('fs'),
JsonDB = require('./jsondb'),
_json = require('./_json'),
utils = require('./utils');

var ModelValidator = function (model) {
Expand Down Expand Up @@ -38,10 +38,11 @@ var operation = function (operation) {
* @param {String} db
* @param {String} collection
*/
function Model (db, collection) {
function Model (db, collection, fields, context) {
this.file = db;
this.collection = collection;
this.fields;
this.fields = fields;
this.context = context;
};

/**
Expand Down Expand Up @@ -366,12 +367,12 @@ Model.prototype._validateFile = function () {
};

Model.prototype._saveModifications = function (data) {
let json = new JsonDB(this.file);
let json = new _json(this.file);
json.update(data);
};

Model.prototype._saveModificationOnKey = function (key, data) {
let json = new JsonDB(this.file);
let json = new _json(this.file);
json.updateKey(key, data);
};

Expand Down
12 changes: 11 additions & 1 deletion src/operations/add.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,17 @@ module.exports = function (Model) {
if (Model._validateFields(fields)) {
let db = require(Model.file),
collection = db[Model.collection],
id = collection.length ? collection[collection.length - 1].id + 1 : 1;
context = Model.context,
id;

if (context.lastInsertId(Model.collection) == null) {
id = collection.length ? collection[collection.length - 1].id + 1 : 1;
} else {
id = collection.length ? context.lastInsertId(Model.collection) + 1 : 1;
}

context.setLastInsertId(Model.collection, id);

collection.push(utils.object.merge({id: id}, fields));
Model._saveModificationOnKey(Model.collection, collection);
}
Expand Down

0 comments on commit 2d22512

Please sign in to comment.