├── config.js ├── lib ├── logger │ ├── mode.js │ ├── index.js │ └── errors.js ├── storage │ ├── index.js │ └── filesystem.js ├── goblin.js ├── database.js └── ambush.js ├── .travis.yml ├── test ├── data │ ├── restore.goblin │ └── restore.json └── goblin.js ├── .npmignore ├── .gitignore ├── gulpfile.js ├── package.json ├── demo └── fear_the_goblin.js ├── index.js ├── README.md └── LICENSE /config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | logPrefix: '[GoblinDB]', 3 | fileName : 'goblin_db', 4 | pointerSymbol: '.', 5 | recordChanges: true, 6 | mode : 'production' 7 | }; -------------------------------------------------------------------------------- /lib/logger/mode.js: -------------------------------------------------------------------------------- 1 | // Logger mode 2 | 3 | module.exports = { 4 | 'production': 'prod', // Silence 5 | 'development': 'dev', // console.warn 6 | 'strict': 'strict' // throw errors 7 | }; -------------------------------------------------------------------------------- /lib/storage/index.js: -------------------------------------------------------------------------------- 1 | const fileSystem = require('./filesystem'); 2 | 3 | const Storage = { 4 | database: fileSystem, 5 | ambush: fileSystem 6 | }; 7 | 8 | 9 | module.exports = Storage; 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | 2 | language: node_js 3 | node_js: 4 | - "9.8.0" 5 | before_install: 6 | - "sudo apt-get -qq update" 7 | - "sudo apt-get install -qq libzmq3-dev" 8 | install: true 9 | script: 10 | - bash ./build.sh 11 | branches: 12 | only: 13 | - master 14 | - dev -------------------------------------------------------------------------------- /test/data/restore.goblin: -------------------------------------------------------------------------------- 1 | [{ 2 | "id": "testing-sum-fn", 3 | "category": ["test-fn","test-sum"], 4 | "description": "This is a function that gets an array of numbers and send the sum via callback", 5 | "action": "\"function (numbers, callback) {\\n callback(numbers.reduce((accumulated, curr) => accumulated + curr, 0));\\n }\"" 6 | }] 7 | -------------------------------------------------------------------------------- /test/data/restore.json: -------------------------------------------------------------------------------- 1 | { 2 | "data-test":"testing content", 3 | "more-data-test":[ 4 | 123, 5 | true, 6 | "hello" 7 | ], 8 | "more-data":{ 9 | "more":"details" 10 | }, 11 | "CSmLLJ99ltmY0WBOrEmBzWCPcLXJGxOb":{ 12 | "more":"data" 13 | }, 14 | "internal":{ 15 | "references":{ 16 | "in":{ 17 | "goblin":{ 18 | "are":"deep", 19 | "push":{ 20 | "lmbcycaMtgfQwZAgiBm9I9tDdRafJmBt":{ 21 | "deeper":"than expected" 22 | }, 23 | "PXHTj0KCk6N3TUrpMOIENoqolwRpdQli":{ 24 | "cooler":"than expected" 25 | } 26 | } 27 | } 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | # Notes 40 | IDEAS 41 | IGNORE 42 | 43 | # Testing results 44 | coverage 45 | 46 | # Ignore goblin files if any 47 | *.goblin 48 | goblin_db.json -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | 11 | # Directory for instrumented libs generated by jscoverage/JSCover 12 | lib-cov 13 | 14 | # Coverage directory used by tools like istanbul 15 | coverage 16 | 17 | # nyc test coverage 18 | .nyc_output 19 | 20 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 21 | .grunt 22 | 23 | # node-waf configuration 24 | .lock-wscript 25 | 26 | # Compiled binary addons (http://nodejs.org/api/addons.html) 27 | build/Release 28 | 29 | # Dependency directories 30 | node_modules 31 | jspm_packages 32 | 33 | # Optional npm cache directory 34 | .npm 35 | 36 | # Optional REPL history 37 | .node_repl_history 38 | 39 | # Notes 40 | IDEAS 41 | IGNORE 42 | 43 | # Testing results 44 | coverage 45 | 46 | goblin_db.goblin 47 | goblin_db.json 48 | 49 | # Demo files 50 | /demo/*.json 51 | *.goblin -------------------------------------------------------------------------------- /lib/goblin.js: -------------------------------------------------------------------------------- 1 | const EventEmitter = require('events'); 2 | const _ = require('lodash'); 3 | 4 | const configGoblin = require('../config'); 5 | const errors = require('./logger/errors'); 6 | 7 | const goblin = { 8 | config: configGoblin, 9 | db: {}, 10 | goblinDataEmitter: new EventEmitter(), 11 | ambush: [], 12 | ambushEmitter: new EventEmitter(), 13 | hooks: { 14 | add: addHook, 15 | remove: removeHook, 16 | repository: [] 17 | }, 18 | errorEmitter: new EventEmitter(), 19 | saveDataTask: undefined 20 | }; 21 | 22 | function addHook(event, callback){ 23 | if(event && typeof(event) === 'string' && callback && typeof(callback) === 'function') { 24 | goblin.hooks.repository.push({event, callback}); 25 | } else { 26 | throw configGoblin.logPrefix, errors.EVENT_RECORD; 27 | } 28 | } 29 | 30 | function removeHook(event, callback) { 31 | const searchObj = {event}; 32 | 33 | if (callback !== undefined) { 34 | searchObj.callback = callback; 35 | } 36 | 37 | _.remove(goblin.hooks.repository, searchObj); 38 | } 39 | 40 | module.exports = goblin; -------------------------------------------------------------------------------- /lib/logger/index.js: -------------------------------------------------------------------------------- 1 | const errors = require('./errors'); 2 | const mode = require('./mode'); 3 | const goblin = require('../goblin'); 4 | 5 | // Error Hooks Execution 6 | goblin.errorEmitter.on('error', function (exception, error) { 7 | goblin.hooks.repository.forEach(function (hook) { 8 | if (hook.event === 'error') { 9 | hook.callback({msg: exception.toString(), error: error}); 10 | } 11 | }); 12 | }); 13 | 14 | function goblinException(prefix, code, log) { 15 | this.prefix = prefix; 16 | this.log = log; 17 | 18 | this.toString = function() { 19 | return (this.prefix ? this.prefix + ': ' : '') + this.log; 20 | }; 21 | this.faqString = function() { 22 | return 'Check the F.A.Q. at https://github.com/GoblinDBRocks/GoblinDB/wiki/Errors#' + 23 | code.toLowerCase() + ' for more information. 👺'; 24 | }; 25 | } 26 | 27 | module.exports = function(code, error, type) { 28 | const currentMode = mode[goblin.config.mode]; 29 | 30 | const prefix = goblin.config.logPrefix; 31 | const log = errors[code] || code; 32 | const exception = new goblinException(prefix, code, log); 33 | 34 | // Always emit error event 35 | goblin.errorEmitter.emit('error', exception, error || {}); 36 | if (currentMode === mode.strict) { 37 | throw exception.toString(); 38 | } else if (currentMode === mode.development) { 39 | console[type || 'error'](exception.toString(), exception.faqString(), error ? error : '' ); 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var gulp = require('gulp'), 4 | eslint = require('gulp-eslint'), 5 | debug = require('gulp-debug'), 6 | mocha = require('gulp-mocha'), 7 | istanbul = require('gulp-istanbul'), 8 | jsdoc = require('gulp-jsdoc3'); 9 | 10 | gulp.task('jsdoc', function(cb) { 11 | var config = require('./docs/jsdoc.json'); 12 | gulp.src(['./docs/README.md', './**/*.js', '!./gulp-tasks/**', '!./docs/**', '!./dist/**', '!./node_modules/**', '!./test/**.js', '!gulpfile.js', '!./coverage'], {read: false}) 13 | .pipe(debug({title: 'JSDoc (Scope):'})) 14 | .pipe(jsdoc(config, cb)); 15 | }); 16 | 17 | gulp.task('test', function (cb) { 18 | gulp.src(['./src/*.js']) 19 | .pipe(istanbul()) 20 | .pipe(istanbul.hookRequire()) 21 | .on('finish', function () { 22 | gulp.src(['./test/*.js']) 23 | .pipe(mocha()) 24 | .pipe(istanbul.writeReports()) 25 | .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } })) 26 | .on('end', cb); 27 | }); 28 | }); 29 | 30 | gulp.task('lint', function() { 31 | var filesToLint = [ 32 | '**/*.{html,js}', 33 | '!tests/protractor.conf.js', 34 | '!dist/**/*', 35 | '!docs/**/*', 36 | '!node_modules/**/*', 37 | '!tmp/**/*', 38 | '!coverage/**/*' 39 | ]; 40 | 41 | return gulp.src(filesToLint) 42 | .pipe(debug({title: 'eslint (Scope):'})) 43 | .pipe(eslint()) 44 | .pipe(eslint({fix:true})) 45 | .pipe(eslint.format()) 46 | .pipe(gulp.dest('.')); 47 | }); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@goblindb/goblindb", 3 | "version": "0.1.2", 4 | "description": "GoblinDB | Fear the Goblin! | An amazing, simple and fun database for humans", 5 | "main": "./index.js", 6 | "scripts": { 7 | "test": "gulp test" 8 | }, 9 | "readme": "README.md", 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/GoblinDBRocks/GoblinDB.git" 13 | }, 14 | "keywords": [ 15 | "database", 16 | "json" 17 | ], 18 | "author": { 19 | "name": "Ulises Gascón", 20 | "url": "https://github.com/ulisesGascon" 21 | }, 22 | "contributors": [ 23 | { 24 | "name": "Carlos Hernandez", 25 | "url": "https://github.com/codingcarlos" 26 | }, 27 | { 28 | "name": "Jose Manuel Gallego Chamorro", 29 | "url": "https://github.com/Josheriff" 30 | }, 31 | { 32 | "name": "Sebastián Cabanas", 33 | "url": "https://github.com/Sediug" 34 | }, 35 | { 36 | "name": "Santiago Trigo Porres", 37 | "url": "https://github.com/trigoporres" 38 | }, 39 | { 40 | "name": "Andrés", 41 | "url": "https://github.com/drewler" 42 | }, 43 | { 44 | "name": "Álvaro", 45 | "url": "https://github.com/alvarogtx300" 46 | } 47 | ], 48 | "license": "GPL-3.0", 49 | "bugs": { 50 | "url": "https://github.com/GoblinDBRocks/GoblinDB/issues" 51 | }, 52 | "homepage": "https://github.com/GoblinDBRocks/GoblinDB#readme", 53 | "dependencies": { 54 | "fs-extra": "^5.0.0", 55 | "json-fn": "^1.1.1", 56 | "lodash": "4.17.20", 57 | "randomstring": "1.1.5" 58 | }, 59 | "devDependencies": { 60 | "chai": "3.5.0", 61 | "chai-fs": "1.0.0", 62 | "gulp": "^4.0.2", 63 | "gulp-debug": "3.0.0", 64 | "gulp-istanbul": "^1.1.3", 65 | "gulp-mocha": "^7.0.2", 66 | "gulp-util": "3.0.8", 67 | "mocha": "^6.2.1", 68 | "gulp-eslint": "^5.0.0", 69 | "gulp-jsdoc3": "^2.0.0", 70 | "mocha-sinon": "^1.2.0", 71 | "sinon": "^1.17.7" 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /lib/logger/errors.js: -------------------------------------------------------------------------------- 1 | // Error logger 2 | 3 | module.exports = { 4 | 'EVENT_RECORD': 'Event Error Record. Check your arguments.', 5 | 'DB_SAVE_INVALID_REFERENCE': 'Database saving error: Invalid reference point type provided to push. Only string allowed.', 6 | 'DB_SAVE_INVALID_DATA': 'Database saving error: no data provided or data is not an object/Array.', 7 | 'DB_SAVE_ARRAY': 'Database saving error: Setting all the db to an Array is forbiden. Database must be an object.', 8 | 'DB_CLEAN_FS': 'Database cleaning before saving error in file System.', 9 | 'DB_SAVE_FS': 'Database saving error in file System.', 10 | 'AMBUSH_NO_CALLBACK': 'Ambush execution warning: no CALLBACK provided or CALLBACK is not a function.', 11 | 'AMBUSH_INVALID_REFERENCE':'Ambush RUN error: no ambush function registered with that ID', 12 | 'AMBUSH_CLEAN_FS': 'Ambush cleaning before saving error in file System.', 13 | 'AMBUSH_SAVE_FS': 'Ambush saving error in file System.', 14 | 'AMBUSH_INVALID_DATA': 'Ambush saving error: no data provided or data is not an object/Array.', 15 | 'AMBUSH_INVALID_ID': 'Ambush saving error: no ID provided or ID is not a string.', 16 | 'AMBUSH_INVALID_CATEGORY': 'Ambush saving error: no CATEGORY provided or CATEGORY is not an Array.', 17 | 'AMBUSH_INVALID_ACTION': 'Ambush saving error: no ACTION provided or ACTION is not a function.', 18 | 'AMBUSH_UPDATE_INVALID_REFERENCE': 'Ambush saving error: the provided id does not belong to any stored ambush function', 19 | 'AMBUSH_PROVIDED_ID_ALREADY_EXIST': 'Ambush add / update error: the provided id belong to a stored ambush function', 20 | 'AMBUSH_ADD_ERROR': 'Ambush ADD error: This ambush function was registered before.', 21 | 'AMBUSH_NOT_STORED_ID': 'Ambush error: The provided ID doesn not belong to any stored ambush function.', 22 | 'DB_DELETE_INVALID_POINT': 'Database delete error: Invalid pointer, there is no data in that part of tree.', 23 | 'DB_DELETE_MISSING_POINT': 'Database delete error: Missing point that indicates where to delete. It\'s mandatory, if you want to delete from root use truncate() instead.', 24 | 'DB_UPDATE_POIN_NOT_EXIST': 'Database update error: You\'re trying to store data in a key that doesn\'t exist. Please use a valid pointer or the method set() which create the structure if not exist.' 25 | }; 26 | 27 | -------------------------------------------------------------------------------- /demo/fear_the_goblin.js: -------------------------------------------------------------------------------- 1 | const GDB = require('../index'); 2 | const https = require('https'); 3 | 4 | const demoConfig = { 5 | fileName: 'demo' 6 | }; 7 | 8 | const httpsOptions = { 9 | hostname: 'api.github.com', 10 | path: '/orgs/GoblinDBRocks/events', 11 | headers: { 'User-Agent': 'Mozilla/5.0' } 12 | }; 13 | 14 | const goblinDB = GDB(demoConfig, err => { 15 | goblinDB.set({}); 16 | 17 | console.info('Fear the Goblin!'); 18 | console.info('Current Internal configuration:', goblinDB.getConfig()); 19 | 20 | goblinDB.on('change', function(changes){ 21 | console.info('-- change detected!:', changes); 22 | console.info('===================='); 23 | }); 24 | 25 | const originalData = goblinDB.get(); 26 | console.info('originalData:', originalData); 27 | 28 | goblinDB.set({'data': 'world!', 'data2': 'Hiiiii'}, 'elemento.elemento.elemento'); 29 | goblinDB.update({'new data': 'hellooo....', 'new array': ['aaaa', true, 2], 'data': 'cambiado!'}); 30 | 31 | const currentData = goblinDB.get(); 32 | console.info('currentData:', currentData); 33 | 34 | console.info('*****************************'); 35 | console.info('Let\'s make something fun....'); 36 | https.get(httpsOptions, res => { 37 | let body = ''; 38 | 39 | res.on('data', chunk => { 40 | body += chunk; 41 | }); 42 | 43 | res.on('end', () => { 44 | goblinDB.off('change'); 45 | goblinDB.update({'gh-events': JSON.parse(body)}); 46 | console.info('*****************************'); 47 | console.info('*****************************'); 48 | console.info( 49 | 'Check the key gh-events in the following file', 50 | goblinDB.getConfig().files.db 51 | ); 52 | console.info('*****************************'); 53 | console.info('*****************************'); 54 | }); 55 | }).on('error', e => { 56 | console.info('Got an error: ', e); 57 | }); 58 | 59 | console.info('*****************************'); 60 | console.info('Let\'s have some fun with advance features!'); 61 | console.info('Fun with ambush functions!'); 62 | 63 | goblinDB.ambush.add({ 64 | id: 'testing-goblin', 65 | category: ['data', 'other-tag'], 66 | description: 'Optional details...', 67 | action: (argument, callback) => { 68 | console.info('This is from the Function storage in Goblin:'); 69 | console.info('Current Argument:', argument); 70 | callback('I can send data...'); 71 | } 72 | }); 73 | 74 | goblinDB.ambush.run('testing-goblin', 'I love Goblin', arg => { 75 | console.info('*****************************'); 76 | console.info('This is from the callback: Now Running the Callback...'); 77 | console.info('This is from the Function storage in Goblin:', arg); 78 | }); 79 | 80 | goblinDB.ambush.update('testing-goblin',{ 81 | category: ['new thing...'], 82 | action: (a, b, c) => { 83 | if (c) { 84 | console.info(`${ a } * ${ b } * ${ c } = `, a * b * c); 85 | } else { 86 | console.info(`${ a } * ${ b } = `, a * b); 87 | } 88 | }, 89 | }); 90 | 91 | console.info(goblinDB.ambush.list()); 92 | 93 | console.info('*****************************'); 94 | console.info('Check ambush that apply a math operation'); 95 | goblinDB.ambush.run('testing-goblin', 5, 2); 96 | goblinDB.ambush.details('testing-goblin').action(9, 2, 3); 97 | }); -------------------------------------------------------------------------------- /lib/storage/filesystem.js: -------------------------------------------------------------------------------- 1 | const JSONfn = require('json-fn'); 2 | const fse = require('fs-extra'); 3 | const fs = require('fs'); 4 | 5 | const writeQueue = {}; 6 | const fileSystem = { 7 | read: read, 8 | save: save 9 | }; 10 | 11 | /** 12 | * Reads from a JSON file (if the file / path doesn't exist then create that path) and 13 | * gets file content. 14 | * 15 | * @param {string} file File path 16 | * @param {object} defaults Default value if it has to create the file. 17 | * @param {function} cb Callback called when file readed. Takes two arguments, the first 18 | * one is the error (if any) and the second one is the file content. 19 | * @returns {void} Nothing. 20 | */ 21 | function read(file, defaults, cb) { 22 | try { 23 | ensure(file, defaults, function(err) { 24 | if (err) { 25 | return cb(err, null); 26 | } 27 | 28 | fse.readJson(file, (err, db) => { 29 | cb(err, db); 30 | }); 31 | }); 32 | } catch(e) { 33 | cb(e, null); 34 | } 35 | } 36 | 37 | /** 38 | * Save JSON content into a file (if the path doesn't exist then create that path). 39 | * 40 | * @param {string} file File path 41 | * @param {object} db Data to store into the file. 42 | * @param {function} cb Callback called when file readed. Takes one argument, the error 43 | * (if any). 44 | * @returns {void} Nothing. 45 | */ 46 | function save(file, db, cb) { 47 | // Race condition - https://github.com/nodejs/node-v0.x-archive/issues/3958 48 | // Save only last call. 49 | if (writeQueue[file]) { 50 | writeQueue[file].db = db; 51 | writeQueue[file].callbacks.push(cb); 52 | writeQueue[file].version.version++; 53 | return; 54 | } else { 55 | writeQueue[file] = { callbacks: [cb], db, version: 1}; 56 | } 57 | 58 | writeToFile(file); 59 | } 60 | 61 | /** 62 | * Save db data to a file from the write queue. 63 | * 64 | * @param {string} file File path. 65 | * @returns {void} Nothing 66 | */ 67 | function writeToFile(file) { 68 | if (!writeQueue[file]) { 69 | return; 70 | } 71 | 72 | // If not already saving then save, but using the object we make sure to take only 73 | // the last changes. 74 | // Truncate - https://stackoverflow.com/questions/35178903/overwrite-a-file-in-node-js 75 | fs.truncate(file, err => { 76 | const beforeSaveVersion = writeQueue[file].version; 77 | fse.outputJson(file, writeQueue[file].db, err => { 78 | // Something has been saved while the filesystem was writing to file then 79 | // save again 80 | if (beforeSaveVersion !== writeQueue[file].version) { 81 | writeToFile(file); 82 | } 83 | 84 | resolveAllWriteQueueCallbacks(file, err); 85 | delete writeQueue[file]; 86 | }); 87 | }); 88 | } 89 | /** 90 | * Internal. Check if the file exist and if don't then create the file with the same 91 | * content as default (or {} if default is falsy). 92 | * 93 | * @param {string} file File path . 94 | * @param {object} defaults Default value if it has to create the file. 95 | * @param {function} cb Callback called when the path existance was validated. Takes one 96 | * argument, the error (if any). 97 | * @returns {void} Nothing. 98 | */ 99 | function ensure(file, defaults, cb) { 100 | fse.pathExists(file, (err, exists) => { 101 | if (err) { 102 | return cb(err); 103 | } 104 | 105 | if (exists) { 106 | return cb(); 107 | } 108 | 109 | fse.outputJson(file, defaults || {}, cb); 110 | }); 111 | } 112 | 113 | /** 114 | * Internal. Call to every callback of a the write queue for a file. 115 | * 116 | * @param {string} file File path . 117 | * @param {string} error Error message or null. 118 | * @returns {void} Nothing. 119 | */ 120 | function resolveAllWriteQueueCallbacks(file, error) { 121 | writeQueue[file].callbacks.forEach(cb => cb(error)); 122 | } 123 | 124 | module.exports = fileSystem; 125 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const _ = require('lodash'); 2 | 3 | const goblin = require('./lib/goblin'); 4 | const modes = require('./lib/logger/mode'); 5 | const Ambush = require('./lib/ambush'); 6 | const Database = require('./lib/database'); 7 | 8 | /** 9 | * Initialize Goblin DB with the data (if any) stored in the files 10 | * 11 | * @param {object} config Optional. Overwrite initial configuration. 12 | * Ex. {@link @see './config.js'} 13 | * @param {function} cb Optional callback called when the database has finished restoring 14 | * data from files and it's ready to work. This callback takes only 15 | * one parameter which is the error message (if any) that happen in 16 | * the db initialization. 17 | * @returns {object} Goblin instance. 18 | */ 19 | function GoblinExports(config, cb) { 20 | if (!cb) { 21 | cb = function() {}; 22 | } 23 | 24 | // Set configuration 25 | goblin.config = initialConfiguration(goblin.config, config); 26 | 27 | // Initialize current database 28 | Database.init(function(dbError) { 29 | if (dbError) { 30 | return cb(dbError); 31 | } 32 | 33 | // Initialize current Ambush Database 34 | Ambush.init(function(ambError) { 35 | cb(ambError); 36 | }); 37 | }); 38 | 39 | return { 40 | ambush: { 41 | add: Ambush.add, 42 | remove: Ambush.remove, 43 | update: Ambush.update, 44 | details: Ambush.details, 45 | list: Ambush.list, 46 | run: Ambush.run 47 | }, 48 | on: goblin.hooks.add, 49 | off: goblin.hooks.remove, 50 | getConfig: function() { 51 | return Object.assign({}, goblin.config); 52 | }, 53 | updateConfig: function(newConfig) { 54 | goblin.config = updateConfiguration(goblin.config, newConfig); 55 | }, 56 | stopStorage: function() { 57 | goblin.config.recordChanges = false; 58 | }, 59 | startStorage: function() { 60 | goblin.config.recordChanges = true; 61 | }, 62 | get: Database.get, 63 | push: Database.push, 64 | set: Database.set, 65 | update: Database.update, 66 | delete: Database.delete, 67 | truncate: Database.truncate 68 | }; 69 | } 70 | 71 | function isNotEmptyString(element) { 72 | return element && typeof(element) === 'string'; 73 | } 74 | 75 | function isBoolean(element) { 76 | return typeof(element) === 'boolean'; 77 | } 78 | 79 | function isValidMode(mode) { 80 | return modes[mode] !== undefined; 81 | } 82 | 83 | function initialConfiguration(defaultConfiguration, externalConfiguration) { 84 | const updated = updateConfiguration(defaultConfiguration, externalConfiguration); 85 | 86 | if (!updated.files) { 87 | updated.files = { 88 | ambush: updated.fileName + '.goblin', 89 | db: updated.fileName + '.json' 90 | }; 91 | } 92 | 93 | return updated; 94 | } 95 | 96 | function updateConfiguration(currentConfiguration, newConfiguration) { 97 | if ( 98 | typeof(newConfiguration) !== 'object' || 99 | newConfiguration === null || 100 | Object.keys(newConfiguration).length === 0 101 | ) { 102 | return currentConfiguration; 103 | } 104 | 105 | const updatedConfig = Object.assign({}, currentConfiguration); 106 | 107 | if (isNotEmptyString(newConfiguration.fileName)) { 108 | updatedConfig.fileName = newConfiguration.fileName; 109 | updatedConfig.files = { 110 | ambush: newConfiguration.fileName + '.goblin', 111 | db: newConfiguration.fileName + '.json' 112 | }; 113 | } 114 | 115 | if (isNotEmptyString(newConfiguration.pointerSymbol)) { 116 | updatedConfig.pointerSymbol = newConfiguration.pointerSymbol; 117 | } 118 | 119 | if (isBoolean(newConfiguration.recordChanges)) { 120 | updatedConfig.recordChanges = newConfiguration.recordChanges; 121 | } 122 | 123 | if (isValidMode(newConfiguration.mode)) { 124 | updatedConfig.mode = newConfiguration.mode; 125 | } 126 | // console.log(updateConfiguration, newConfiguration); 127 | if (isNotEmptyString(newConfiguration.logPrefix)) { 128 | updatedConfig.logPrefix = '[' + newConfiguration.logPrefix + ']' 129 | } 130 | 131 | return updatedConfig; 132 | } 133 | 134 | module.exports = GoblinExports; 135 | -------------------------------------------------------------------------------- /lib/database.js: -------------------------------------------------------------------------------- 1 | const _ = require('lodash'); 2 | const randomstring = require('randomstring'); 3 | 4 | const goblin = require('./goblin'); 5 | const Storage = require('./storage').database; 6 | const logger = require('./logger'); 7 | 8 | // Goblin Internal Events + Hooks Execution 9 | goblin.goblinDataEmitter.on('change', function(details) { 10 | if (goblin.config.recordChanges) { 11 | Storage.save(goblin.config.files.db, goblin.db, function(err) { 12 | err && logger('DB_SAVE_FS', err); 13 | }); 14 | } 15 | 16 | // Hooks management 17 | goblin.hooks.repository.forEach(function(hook) { 18 | if (hook.event === details.type || hook.event === 'change') { 19 | hook.callback({'value': details.value, 'oldValue': details.oldValue}); 20 | } 21 | }); 22 | }); 23 | 24 | /** 25 | * Initialize database. 26 | * 27 | * @param {function} cb Callback function called when the database is initialized, 28 | * meaning the functions have been restored from file. The function 29 | * gets a parameter which is an error message if any. 30 | * @returns {void} 31 | */ 32 | function init(cb) { 33 | Storage.read(goblin.config.files.db, {}, function(err, db) { 34 | if (err) { 35 | return cb(err); 36 | } 37 | 38 | goblin.db = db; 39 | cb(); 40 | }) 41 | } 42 | 43 | /** 44 | * Gets the data from a point in the nested tree. If you don't set a point then all db 45 | * will be returned. 46 | * 47 | * @param {string} point The place where the data is stored. If there is no such place 48 | * in the nested tree then it'll return undefined. 49 | * @returns {any} The stored data. 50 | */ 51 | function get(point) { 52 | if (point && typeof(point) === 'string') { 53 | const tree = point.split(goblin.config.pointerSymbol); 54 | let parent = goblin.db; 55 | 56 | for (let i = 0; i < tree.length; i++) { 57 | if(i !== tree.length-1) { 58 | if(parent[tree[i]] === undefined) { 59 | // If there is no child here, won't be deeper. Return undefined 60 | return undefined; 61 | } 62 | parent = parent[tree[i]]; 63 | } else { 64 | return parent[tree[i]]; 65 | } 66 | } 67 | } else { 68 | return goblin.db; 69 | } 70 | } 71 | 72 | /** 73 | * Push data to a point in the database nested tree. If you don't set a point where to 74 | * store the data then it'll be stored in higher level, in that case the data can not 75 | * be an array. The first element of the DB has to be always an object. 76 | * 77 | * @param {object | array} data The data to store in the database. 78 | * @param {string} point The place to store the data. 79 | * @returns {void} 80 | */ 81 | function push(data, point) { 82 | if (!point) { 83 | point = ''; 84 | } else if (typeof(point) === 'string') { 85 | point = point + '.'; 86 | } else { 87 | logger('DB_SAVE_INVALID_REFERENCE'); 88 | } 89 | 90 | const newKey = point + randomstring.generate(); 91 | set(data, newKey, true); 92 | goblin.goblinDataEmitter.emit('change', { 93 | type: 'push', 94 | value: data, 95 | key: newKey 96 | }); 97 | } 98 | 99 | /** 100 | * Set data to a point in the database nested tree. If you don't set a point where to 101 | * store the data then it'll be stored in higher level, in that case the data can not 102 | * be an array. The first element of the DB has to be always an object. 103 | * 104 | * @param {object | array} data The data to store in the database. 105 | * @param {string} point The place to store the data. 106 | * @param {bool} silent Internal use. When this is true this method doesn't trigger 107 | * events. 108 | * @returns {void} 109 | */ 110 | 111 | function set(data, point, silent) { 112 | if (!data || typeof(data) !== 'object') { 113 | return logger('DB_SAVE_INVALID_DATA'); 114 | } 115 | 116 | data = makeInmutable(data); 117 | 118 | if (point && typeof(point) === 'string') { 119 | const tree = point.split(goblin.config.pointerSymbol); 120 | let parent = goblin.db; 121 | 122 | for (let i = 0; i < tree.length; i++) { 123 | if (i !== tree.length - 1) { 124 | if (parent[tree[i]] === undefined) { 125 | parent[tree[i]] = {}; 126 | } 127 | 128 | parent = parent[tree[i]]; 129 | } else { 130 | if (!silent) { 131 | goblin.goblinDataEmitter.emit('change', { 132 | type: 'set', 133 | value: data, 134 | oldValue: goblin.db[point], 135 | key: point 136 | }); 137 | } 138 | 139 | parent[tree[i]] = data; 140 | } 141 | } 142 | } else { 143 | if (Array.isArray(data)) { 144 | return logger('DB_SAVE_ARRAY'); 145 | } 146 | 147 | const oldValue = goblin.db; 148 | goblin.db = data; 149 | !silent && goblin.goblinDataEmitter.emit('change', { 150 | type: 'set', 151 | value: goblin.db, 152 | oldValue: oldValue 153 | }); 154 | } 155 | } 156 | 157 | 158 | /** 159 | * Update data to a point in the database nested tree. If you don't set a point where to 160 | * update the stored data then it'll replace all db, in that case the data can not 161 | * be an array. The first element of the DB has to be always an object. 162 | * 163 | * @param {any} data The data to store in the database. 164 | * @param {string} point The place to store the data. 165 | * @returns {void} 166 | */ 167 | function update(data, point) { 168 | if (!data || (!point && typeof(data) !== 'object')) { 169 | return logger('DB_SAVE_INVALID_DATA'); 170 | } 171 | 172 | data = makeInmutable(data); 173 | 174 | if (point && typeof(point) === 'string') { 175 | const tree = point.split('.'); 176 | let parent = goblin.db; 177 | 178 | for (let i = 0; i < tree.length; i++) { 179 | if (parent[tree[i]] === undefined) { 180 | return logger('DB_UPDATE_POIN_NOT_EXIST', 'Invalid point: ' + point); 181 | } 182 | 183 | if (i < tree.length - 1) { 184 | parent = parent[tree[i]]; 185 | } else { 186 | const oldValue = parent[tree[i]]; 187 | parent[tree[i]] = data; 188 | goblin.goblinDataEmitter.emit('change', { 189 | type: 'update', 190 | value: parent[tree[i]], 191 | oldValue: oldValue, 192 | key: point 193 | }); 194 | } 195 | } 196 | } else { 197 | if (Array.isArray(data)) { 198 | return logger('DB_SAVE_ARRAY'); 199 | } 200 | 201 | const oldValue = goblin.db; 202 | goblin.db = Object.assign({}, goblin.db, data); 203 | goblin.goblinDataEmitter.emit('change', { 204 | type: 'update', 205 | value: goblin.db, 206 | oldValue: oldValue 207 | }); 208 | } 209 | } 210 | 211 | /** 212 | * Deletes the content stored where point indicates. 213 | * 214 | * @param {string} point The place where the data is stored. 215 | * @returns {bool} Success 216 | */ 217 | function deleteFn(point) { 218 | if (point && typeof(point) === 'string') { 219 | const tree = point.split('.'); 220 | let source = goblin.db; 221 | 222 | return tree.every((node, i) => { 223 | if (source[node] === undefined) { 224 | logger('DB_DELETE_INVALID_POINT', node); 225 | return false; 226 | } 227 | 228 | if (i === tree.length - 1) { 229 | let oldValue = source[node]; 230 | 231 | if (Array.isArray(source)) { 232 | source.splice(node, 1); 233 | return true; 234 | } 235 | 236 | if (delete source[node]) { 237 | goblin.goblinDataEmitter.emit('change', { 238 | type: 'delete', 239 | value: undefined, 240 | oldValue: oldValue 241 | }); 242 | 243 | return true; 244 | } else { 245 | return false; 246 | } 247 | } 248 | 249 | source = source[node]; 250 | return true; 251 | }); 252 | } 253 | 254 | logger('DB_DELETE_MISSING_POINT'); 255 | return false; 256 | } 257 | 258 | /** 259 | * Truncate all db data and restore it to default (an empty object). 260 | * 261 | * @returns {void} Nothing 262 | */ 263 | function truncate() { 264 | const oldValue = Object.assign({}, goblin.db); 265 | goblin.db = {}; 266 | goblin.goblinDataEmitter.emit('change', { 267 | type: 'truncate', 268 | value: goblin.db, 269 | oldValue: oldValue 270 | }); 271 | } 272 | 273 | 274 | /** 275 | * Private. Check if an element is an object and creates a new memory ref for that object 276 | * to preserve inmutability. 277 | * 278 | * @param {any} element The element to test agains. 279 | * @return {any} A new memory ref in the case it's an object. 280 | */ 281 | function makeInmutable(element) { 282 | if (element && typeof(element) === 'object') { 283 | if (Array.isArray(element)) { 284 | return [...element]; 285 | } else { 286 | return Object.assign({}, element); 287 | } 288 | } 289 | 290 | return element; 291 | } 292 | 293 | module.exports = { 294 | init: init, 295 | get: get, 296 | push: push, 297 | set: set, 298 | update: update, 299 | delete: deleteFn, 300 | truncate: truncate 301 | }; 302 | -------------------------------------------------------------------------------- /lib/ambush.js: -------------------------------------------------------------------------------- 1 | const _ = require('lodash'); 2 | const JSONfn = require('json-fn'); 3 | 4 | const goblin = require('./goblin'); 5 | const Storage = require('./storage').ambush; 6 | const logger = require('./logger'); 7 | 8 | /** 9 | * Ambush function data object. 10 | * 11 | * @typedef {object} Ambush 12 | * @property {string} id Id of the ambush function. 13 | * @property {string} description Optional. Describe what the action does. 14 | * @property {array} category Optional. Category/ies to filter ambush functions later. 15 | * @property {function} action Action perform by this ambush function when calling method 16 | * run() {@see #run} 17 | */ 18 | 19 | // Goblin Internal Events + Hooks Execution 20 | goblin.ambushEmitter.on('change', function(details) { 21 | Storage.save(goblin.config.files.ambush, compileFn(goblin.ambush), function(err) { 22 | err && logger('AMBUSH_SAVE_FS', err); 23 | }); 24 | 25 | // Hooks management 26 | goblin.hooks.repository.forEach(function(hook) { 27 | if (hook.event === 'ambush-' + details.type || hook.event === 'ambush-change') { 28 | hook.callback({'value': details.value, 'oldValue': details.oldValue}); 29 | } 30 | }); 31 | }); 32 | 33 | 34 | /** 35 | * Initialize ambush functions database. Try to read from the configured file route, 36 | * if the file don't exist then try to create it with the default db. 37 | * 38 | * @param {function} cb Callback function called when the ambush db is initialized, 39 | * meaning the functions have been restored from file. The function 40 | * gets a parameter which is an error message if any. 41 | * @returns {void} 42 | */ 43 | function init(cb) { 44 | Storage.read(goblin.config.files.ambush, [], function(err, db) { 45 | if (err) { 46 | return cb(err); 47 | } 48 | 49 | goblin.ambush = restoreFn(db); 50 | cb(); 51 | 52 | }); 53 | } 54 | 55 | /** 56 | * Parse functions when loading file restoring then to js valid objects. 57 | * 58 | * @param {array} db Ambush functions db 59 | * @returns {arrat} Parsed db ready to use. 60 | */ 61 | function restoreFn(db) { 62 | return db.map(function(amb) { 63 | return Object.assign({}, amb, {action: JSONfn.parse(amb.action)}); 64 | }); 65 | } 66 | 67 | /** 68 | * Turn actions in every ambush function into valid json strings. 69 | * 70 | * @param {array} db Ambush functions db. 71 | * @returns {arrat} Compiled db ready to save. 72 | */ 73 | function compileFn(db) { 74 | return db.map(function(amb) { 75 | return Object.assign({}, amb, {action: JSONfn.stringify(amb.action)}); 76 | }); 77 | 78 | return result; 79 | } 80 | 81 | /** 82 | * Store a new ambush function. Validates id doesn't exist already, etc. 83 | * 84 | * @param {Ambush} object Ambush function data. 85 | * @returns {void} Nothing. 86 | */ 87 | function add(object) { 88 | if (!_isValidAmbush(object)) { 89 | return false; 90 | } 91 | 92 | object.description = _cleanDescription(object.description); 93 | 94 | if (!_belongToAStoredAmbush(object.id)) { 95 | const newObject = Object.assign({}, object); 96 | goblin.ambush.push(newObject); 97 | goblin.ambushEmitter.emit('change', { type: 'add', value: newObject }); 98 | } else { 99 | logger('AMBUSH_ADD_ERROR'); 100 | } 101 | } 102 | 103 | /** 104 | * Remove an ambush function from the database. 105 | * 106 | * @param {string} id Ambush function id. 107 | * @returns {void} Nothing. 108 | */ 109 | function remove(id) { 110 | if (!_isValidId(id)) { 111 | return false; 112 | } 113 | 114 | const oldValue = JSONfn.clone(goblin.ambush); 115 | 116 | _.remove(goblin.ambush, function(current) { 117 | return current.id === id; 118 | }); 119 | 120 | goblin.ambushEmitter.emit('change', { 121 | type: 'remove', 122 | oldValue: oldValue 123 | }); 124 | } 125 | 126 | /** 127 | * Updates an ambush function. 128 | * 129 | * @param {string} id Ambush function id. 130 | * @param {Ambush} object Ambush function data. 131 | * @returns {bool} If updated or not. 132 | */ 133 | function update(id, object) { 134 | // Validations 135 | if (!_isValidId(id)) { 136 | return false; 137 | } 138 | 139 | // Action 140 | const index = _getIndexOfId(id); 141 | 142 | if (index > -1) { 143 | if (_isValidAmbushOnUpdate(id, object)) { 144 | const current = goblin.ambush[index]; 145 | const newAmbush = Object.assign({}, current, object); 146 | newAmbush.description = _cleanDescription(newAmbush.description); 147 | 148 | // Set updated ambush 149 | goblin.ambush[index] = newAmbush; 150 | goblin.ambushEmitter.emit( 151 | 'change', 152 | { 153 | type: 'update', 154 | oldValue: JSONfn.clone(current), 155 | value: JSONfn.clone(goblin.ambush[index]) 156 | } 157 | ); 158 | } 159 | } else { 160 | logger('AMBUSH_UPDATE_INVALID_REFERENCE'); 161 | } 162 | 163 | return true; 164 | } 165 | 166 | /** 167 | * Gets an ambush function data. 168 | * 169 | * @param {string} id Ambush function id. 170 | * @returns {Ambush} Ambush function data. 171 | */ 172 | function details(id) { 173 | if (!_isValidId(id)) { 174 | return false; 175 | } 176 | 177 | const index = _getIndexOfId(id); 178 | 179 | if (index === -1) { 180 | return logger('AMBUSH_NOT_STORED_ID'); 181 | } 182 | 183 | return goblin.ambush[index]; 184 | } 185 | 186 | /** 187 | * List all ambush function ids that match the passed category. If actegory is a falsy 188 | * then all ambush functions will be listed. 189 | * 190 | * @param {string} category Ambush function category. 191 | * @returns {array} Ids of the ambush functions of that category. 192 | */ 193 | function list(category){ 194 | let list = []; 195 | 196 | if (category && typeof(category) === 'string') { 197 | list = _(goblin.ambush).filter(function(current) { 198 | return _.includes(current.category, category); 199 | }).map('id').value(); 200 | } else { 201 | list = _(goblin.ambush).map('id').value(); 202 | } 203 | 204 | return list; 205 | 206 | } 207 | 208 | /** 209 | * Run an ambush function action. 210 | * 211 | * @param {string} id Ambush function id. 212 | * @param {any} parameter First parameter for the ambush function action. 213 | * @param {function} callback Second parameter for the ambush function action. 214 | * @returns {array} Ids of the ambush functions of that category. 215 | */ 216 | function run(id, parameter, callback) { 217 | if (!_isValidId(id)) { 218 | return false; 219 | } 220 | 221 | if (callback && typeof(callback) !== 'function') { 222 | logger('AMBUSH_NO_CALLBACK'); 223 | } 224 | 225 | const index = _getIndexOfId(id); 226 | 227 | if (index > -1) { 228 | goblin.ambush[index].action(parameter, callback); 229 | } else { 230 | logger('AMBUSH_INVALID_REFERENCE'); 231 | } 232 | } 233 | 234 | // Internal Functions 235 | 236 | /** 237 | * Validate description returning the description only if valid and false otherwise. 238 | * 239 | * @param {string} id Ambush function id. 240 | * @returns {(string | bool)} The description string if valid or false. 241 | */ 242 | function _cleanDescription(description) { 243 | return (description && typeof(description) === 'string') ? description : false; 244 | } 245 | 246 | /** 247 | * Validates ambush function data object on create. 248 | * 249 | * @param {Ambush} object Ambush function data. 250 | * @returns {bool} If it's valid or not. 251 | */ 252 | function _isValidAmbush(object) { 253 | return _isValidObject(object) && 254 | _isValidId(object.id) && 255 | _isUniqueId(null, object.id) && 256 | _isValidCategory(object.category) && 257 | _isValidAction(object.action); 258 | } 259 | 260 | /** 261 | * Validates ambush function data object on update. 262 | * 263 | * @param {string} id Ambush function id. 264 | * @param {Ambush} object Ambush function data. 265 | * @returns {bool} If it's valid or not. 266 | */ 267 | function _isValidAmbushOnUpdate(id, object) { 268 | return _isValidObject(object) && 269 | _isValidNotRequired(object.id, _isValidId) && 270 | _isUniqueId(id, object.id) && 271 | _isValidNotRequired(object.category, _isValidCategory) && 272 | _isValidNotRequired(object.action, _isValidAction); 273 | } 274 | 275 | /** 276 | * Tells if the passed element is a valid object (not an array). 277 | * 278 | * @param {object} object The object to be validated. 279 | * @returns {bool} If it's valid or not. 280 | */ 281 | function _isValidObject(object) { 282 | if (!object || Array.isArray(object) || typeof(object) !== 'object') { 283 | logger('AMBUSH_INVALID_DATA'); 284 | return false; 285 | } 286 | 287 | return true; 288 | } 289 | 290 | /** 291 | * Validates passed if is a string and it's not empty. 292 | * 293 | * @param {string} id Ambush function id. 294 | * @returns {bool} If it's valid or not. 295 | */ 296 | function _isValidId(id) { 297 | if (!id || typeof(id) !== 'string') { 298 | logger('AMBUSH_INVALID_ID'); 299 | return false; 300 | } 301 | 302 | return true; 303 | } 304 | 305 | /** 306 | * Validates passed action checking if it's a function. 307 | * 308 | * @param {function} action Ambush function action. 309 | * @returns {bool} If it's valid or not. 310 | */ 311 | function _isValidAction(action) { 312 | if (!action || typeof(action) !== 'function') { 313 | logger('AMBUSH_INVALID_ACTION'); 314 | return false; 315 | } 316 | 317 | return true; 318 | } 319 | 320 | /** 321 | * Validates passed category. 322 | * 323 | * @param {array} category Ambush function categories. 324 | * @returns {bool} If it's valid or not. 325 | */ 326 | function _isValidCategory(category) { 327 | if (!category || !Array.isArray(category)) { 328 | logger('AMBUSH_INVALID_CATEGORY'); 329 | return false; 330 | } 331 | 332 | return true; 333 | } 334 | 335 | /** 336 | * Validates an id doesn't belong to an already stored ambush function. When updating 337 | * an ambush function id check if the new id it's already in use. 338 | * 339 | * @param {string} currentId Ambush function current id. 340 | * @param {string} newId Ambush function new id. 341 | * @returns {bool} If it already exist or not. 342 | */ 343 | function _isUniqueId(currentId, newId) { 344 | if ( 345 | newId !== undefined && 346 | currentId !== newId && 347 | _belongToAStoredAmbush(newId) 348 | ) { 349 | logger('AMBUSH_PROVIDED_ID_ALREADY_EXIST'); 350 | return false; 351 | } 352 | 353 | return true; 354 | } 355 | 356 | /** 357 | * Takes two arguments, one of then is the element that may or may not exist and the 358 | * other one is the validation function to apply over it when it exist. 359 | * 360 | * @param {any} element The element to be validated. 361 | * @param {function} validatorCallback The validator to apply over that element. 362 | * @returns {bool} True if there's no element or pass validation, false otherwise. 363 | */ 364 | function _isValidNotRequired(element, validatorCallback) { 365 | if (element !== undefined) { 366 | return validatorCallback(element); 367 | } 368 | 369 | return true; 370 | } 371 | 372 | /** 373 | * Gets the index of an stored ambush function given its id (or -1 if not exist). 374 | * 375 | * @param {string} id Ambush function id. 376 | * @returns {int} Index of the ambush function or -1. 377 | */ 378 | function _getIndexOfId(id) { 379 | return _.indexOf(goblin.ambush, _.find(goblin.ambush, {id})) 380 | } 381 | 382 | /** 383 | * Check if the passed id belongs to an stored ambush function. 384 | * 385 | * @param {string} id Ambush function id. 386 | * @returns {bool} If exist or not. 387 | */ 388 | function _belongToAStoredAmbush(id) { 389 | return _getIndexOfId(id) > -1 390 | } 391 | 392 | module.exports = { 393 | init: init, 394 | add: add, 395 | remove: remove, 396 | update: update, 397 | details: details, 398 | list: list, 399 | run: run 400 | }; 401 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![shieldsIO](https://img.shields.io/github/issues/GoblinDBRocks/GoblinDB.svg) 2 | ![shieldsIO](https://img.shields.io/github/release/GoblinDBRocks/GoblinDB.svg) 3 | ![shieldsIO](https://img.shields.io/github/license/GoblinDBRocks/GoblinDB.svg) 4 | ![shieldsIO](https://img.shields.io/david/GoblinDBRocks/GoblinDB.svg) 5 | [![Build Status](https://travis-ci.org/GoblinDBRocks/GoblinDB.svg?branch=master)](https://travis-ci.org/GoblinDBRocks/GoblinDB) 6 | 7 | # [GoblinDB](http://goblindb.osweekends.com/) 8 | 9 | ![goblin](https://raw.githubusercontent.com/GoblinDBRocks/Art/master/high_resolution/goblin_db_logo-01.png) 10 | 11 | ### Fear the Goblin! 12 | 13 | **An amazing, simple and fun database for humans** 14 | 15 | 16 | ### Goblin Philosophy 17 | 18 | - Coding is fun, so databases must be fun too. 19 | - Data is the king. 20 | - Data should be stored in the system as a file whenever a change happens. 21 | - Data storage in the system must be hackable. 22 | - The database can lead or connect your server components. 23 | - Events are great... because we are asynchronous. 24 | - We prefer facts over promises: facts are there, promises maybe yes or not. In fact, we're talking about callbacks. 25 | - Data is not the only stuff that can be store in a database. 26 | - We prefer ambush functions over lambda functions. As you know... we're talking about anonymous functions. 27 | 28 | ### [Documentation](http://goblindb.osweekends.com/) 29 | 30 | ```javascript 31 | const GDB = require("@goblindb/goblindb"); 32 | 33 | const goblinDB = GDB(function(dbError) { 34 | if (dbError) { 35 | throw dbError; 36 | } 37 | 38 | console.log("Fear the Goblin!") 39 | 40 | // Events supported 41 | goblinDB.on('change', function(changes){ 42 | console.log("-- change detected!:", changes) 43 | console.log("====================") 44 | }); 45 | 46 | // Read all Database... 47 | const originalData = goblinDB.get(); 48 | console.log("originalData:", originalData); 49 | 50 | // Store data... 51 | goblinDB.set({"data": "world!", "data2": "Hiiiii"}); 52 | 53 | // Update date... 54 | goblinDB.update({"new data": "hellooo....", "new array": ["aaaa", true, 2], "data": "cambiado!"}) 55 | 56 | // Read all Database... 57 | const currentData = goblinDB.get(); 58 | console.log("currentData:", currentData) 59 | }); 60 | ``` 61 | 62 | **[Check the official documentation in our website](http://goblindb.osweekends.com/)** 63 | 64 | 65 | ### Demo 66 | You can run a demo in 4 steps! 67 | 68 | 1. Clone this repository 69 | ```bash 70 | git clone https://github.com/GoblinDBRocks/GoblinDB 71 | ``` 72 | 73 | 2. Enter in the folder 74 | ```bash 75 | cd GoblinDB 76 | ``` 77 | 78 | 3. Install the dependencies 79 | ```bash 80 | npm install 81 | ``` 82 | 83 | 4. Run *fear_the_goblin.js* 84 | ```bash 85 | node demo/fear_the_goblin.js 86 | ``` 87 | 88 | ### Testing 89 | 90 | You can test your changes... 91 | 92 | ```bash 93 | npm test 94 | ``` 95 | 96 | ### Future Implementations 97 | 98 | - [ ] Support to chain methods. [Issue 50](https://github.com/GoblinDBRocks/GoblinDB/issues/50) 99 | - [ ] Add Pugins system. [Issue 12](https://github.com/GoblinDBRocks/GoblinDB/issues/12) 100 | - [ ] Plugin documentation example. [Issue 56](https://github.com/GoblinDBRocks/GoblinDB/issues/56) 101 | - [ ] Add basic query methods as a plugin. [Issue 54](https://github.com/GoblinDBRocks/GoblinDB/issues/54) 102 | - [ ] Add Avance query methods as a plugin. [Issue 55](https://github.com/GoblinDBRocks/GoblinDB/issues/55) 103 | - [ ] Add support to .once() method for events. [Issue 51](https://github.com/GoblinDBRocks/GoblinDB/issues/51) 104 | - [ ] Add support to UID in events. [Issue 53](https://github.com/GoblinDBRocks/GoblinDB/issues/53) 105 | - [ ] Add additional support to Backup Goblin with other databases like Firebase, Mongo... in real time as a plugin.[Issue 52](https://github.com/GoblinDBRocks/GoblinDB/issues/52) 106 | - [x] Support multidimensional navigation in the database (.ref() method). Using get instead of .ref but same functionality. [Issue 17](https://github.com/GoblinDBRocks/GoblinDB/issues/17) 107 | - [x] Additional events to support (config changes, etc...). 108 | - [x] Full documentation in JSDoc. 109 | - [x] Gulp Tasks Improvement. 110 | - [x] Test support for Events using Sinon. 111 | - [x] Test refactor in order to separate more the test cases. 112 | 113 | 114 | ### Plugins 115 | 116 | - __[GoblinSocket](https://github.com/CodingCarlos/GoblinSocket).__ *WebSocket interface for GoblinDB using SocketIO* 117 | 118 | 119 | ### Goblin Team 120 | Those are the amazing people which have contributed to this project: 121 | 122 | [Ulises Gascón](https://github.com/UlisesGascon) **Co-leader** 123 | 124 | [Sebastián Cabanas](https://github.com/Sediug) **Co-leader** 125 | 126 | [Carlos Hernandez](https://github.com/CodingCarlos) **Co-leader** 127 | 128 | [Leyla Vieira](https://github.com/LeylaVieira) **Contributor** (Web) 129 | 130 | [Santiago Trigo Porres](https://github.com/trigoporres) **Contributor** 131 | 132 | [Andrés](https://github.com/drewler) **Contributor** 133 | 134 | [Alvaro](https://github.com/alvarogtx300) **Contributor** 135 | 136 | [Jose](https://github.com/Josheriff) **Contributor** (Moral support :trollface:) 137 | 138 | 139 | 140 | 141 | ### Achievements 142 | 143 | #### v.0.1.0 The Kraken! 144 | :tada::tada: Finally, here we are! Releasing the version one, the first production quality version available ever. We're very proud to reach this step in the project life! :tada::tada: 145 | 146 | After almost one month working with the last version [v0.0.11 Meigas](https://github.com/GoblinDBRocks/GoblinDB#v0011-meigas) we're pretty sure the database is reliable to be used in a production environment. So here we are releasing the kraken! 147 | 148 | 149 | **Bug fixes:** 150 | 151 | - Improve and update the project demo. 152 | 153 | **Notices:** 154 | - Evangelization process is going on (Talks, documentation, workshops...) 155 | - We are looking for active evangelists, ping us ;-) 156 | 157 | 158 | 159 | #### v.0.0.11 Meigas! 160 | We've found bugs... bugs which didn't make sense, like meigas it looks like there is none but in the end there were some big bugs like db not storing data in the json and other similar "features" :trollface: 161 | 162 | Wellcome to the new members of the team :heart: Andrés @drewler (The Galician Tigger), Santiago @trigoporres (El potro de Vallecas) and Alvaro @alvarogtx300 (El ausente :trollface:) 163 | 164 | People which have contributed to this release: 165 | 166 | [Sebastián Cabanas](https://github.com/Sediug) **Co-leader** 167 | 168 | [Carlos Hernandez](https://github.com/CodingCarlos) **Co-leader** 169 | 170 | [Ulises Gascón](https://github.com/UlisesGascon) **Evangelist and Consultant** 171 | 172 | [Santiago Trigo Porres](https://github.com/trigoporres) **Contributor** :tada::tada: 173 | 174 | [Andrés](https://github.com/drewler) **Contributor** :tada::tada: 175 | 176 | [Alvaro](https://github.com/alvarogtx300) **Contributor** :tada::tada: 177 | 178 | 179 | 180 | **Main target:** 181 | 182 | - Version 1 candidate. 183 | - Remove eval. Improved how data gets saved and loaded. 184 | - Various code improvements. 185 | - Events improvements. 186 | - Add callback to goblin init method (now async loading json db files). 187 | - Allow using a custom pointer symbol (you can use '/' for example, instead of '.' (default)). Configurable in init method config. [Issue 36](https://github.com/GoblinDBRocks/GoblinDB/issues/36) [Pull Request 42](https://github.com/GoblinDBRocks/GoblinDB/pull/42) Thanks to [Santiago Trigo Porres](https://github.com/trigoporres) :100: 188 | - Add **delete** and **truncate** methods to database. [Issue 38](https://github.com/GoblinDBRocks/GoblinDB/issues/38) PR [Pull Request 34](https://github.com/GoblinDBRocks/GoblinDB/pull/34) 189 | - Add error events hook. Now you can listen to `goblinDBInstance.on('error', callback...)`. [Issue 37](https://github.com/GoblinDBRocks/GoblinDB/issues/37) [Pull Request 43](https://github.com/GoblinDBRocks/GoblinDB/pull/43) Thanks to [Alvaro](https://github.com/alvarogtx300) :100: 190 | - Add test cases for events. [Issue 8](https://github.com/GoblinDBRocks/GoblinDB/issues/8) [Pull Request 44](https://github.com/GoblinDBRocks/GoblinDB/pull/44) 191 | - Add errors FAQ and improve messages adding links to the docs (in dev mode only). [Issue 14](https://github.com/GoblinDBRocks/GoblinDB/issues/14) [Pull Request 46](https://github.com/GoblinDBRocks/GoblinDB/pull/46) Thanks to [Andrés](https://github.com/drewler) :100: 192 | - Add ambush functions events hooks. Now you can listen to **ambush-change**, **ambush-add**, **ambush-update** and **ambush-remove**. 193 | - Add support for detaching all events of the same type for all the callbacks associated. Ex. Detaching the listeners for 4 different callbacks on change event. 194 | 195 | **Bug fixes:** 196 | 197 | - Lots of bugs. I don't even now where to start haha. 198 | 199 | **Features:** 200 | 201 | - Add methods **delete** and **truncate** to the database. 202 | - Added a callback to Goblin **init** method which will be called when the db is ready to work (load data from file async). 203 | - Allow using a custom pointer symbol. Now you can use ***'/'*** (firebase friendly). 204 | - New code structure (feature only for developers), wich improve stability. 205 | - Test improvements (feature only for developers), wich improve stability. 206 | 207 | **Notices:** 208 | - Great job and support from [Alvaro](https://github.com/alvarogtx300), [Santiago Trigo Porres](https://github.com/trigoporres) and [Andrés](https://github.com/drewler) (now in GoblinDB team) :tada::tada: 209 | - This version is a good candidate for v0.1.0 210 | - Evangelization process is going on (Talks, documentation, workshops...) Last event was T3chfest 2018 and all osw events :+1: 211 | - We are looking for active evangelists, ping us ;-) 212 | 213 | 214 | #### v.0.0.10. New Drakkar! 215 | 216 | **Main target:** 217 | 218 | - Refactor the main structure to improve maintainability. 219 | - Improve all the test cases, to cover well all the code. 220 | 221 | **Bug fixes:** 222 | 223 | - Lot of bugs when adding or updating ambush functions. 224 | - Improved error messages and reasons (some of them was not consistent). 225 | 226 | **Features:** 227 | 228 | - Travis added to the project 229 | - Silence mode. 230 | - Production mode. 231 | - Development mode. 232 | - New code structure (feature only for developers), wich improve stability. 233 | 234 | **Notices:** 235 | - Great job and support from @Sediug (now in GoblinDB team) 236 | - Evangelization process has been started (Talks, documentation, workshops...) 237 | - We are looking for active evangelists, ping us ;-) 238 | 239 | #### v.0.0.8 240 | 241 | **Main target:** 242 | - Improve architecture & compatibility 243 | 244 | **Features:** 245 | - Native Events now supported. 246 | - No need to use Object.observe or proxy ECMA6 alternatives. 247 | 248 | #### v.0.0.7 249 | 250 | **Main target:** 251 | - Ambush support 252 | 253 | **Bugs Fixed:** 254 | - No need to require http module, in documentation examples 255 | 256 | **Features:** 257 | - Database testing improved 258 | - Added optional features like parameters and callbacks for Ambush (lambda) functions 259 | - Added automatic save for Ambush 260 | - Added .goblin extension in order to store ambush operations 261 | - Added Testing to support ambush features 262 | - Added goblin.ambush as container 263 | - Added goblin.ambush.add(), 264 | - Added goblin.ambush.remove(), 265 | - Added goblin.ambush.update(), 266 | - Added goblin.ambush.list(), 267 | - Added goblin.ambush.details(), 268 | - Added goblin.ambush.run() 269 | 270 | #### v.0.0.6 271 | 272 | - Readme improved 273 | 274 | #### v.0.0.5 275 | 276 | - [New Art](https://github.com/GoblinDBRocks/Art/) 277 | - [New Organization](https://github.com/GoblinDBRocks/) 278 | 279 | #### v.0.0.4 280 | 281 | **Features:** 282 | - Documentation improved 283 | 284 | **Bugs Fixed** 285 | - [Wrong route on npm install](https://github.com/GoblinDBRocks/GoblinDB/issues/3) 286 | - [Database storage location](https://github.com/GoblinDBRocks/GoblinDB/issues/4) 287 | 288 | 289 | #### v.0.0.3 290 | 291 | **Notes:** 292 | Just to solve issues with NPM. 293 | 294 | #### v.0.0.2 295 | 296 | **Main target:** 297 | - Develop the basics key functionalities (methods) 298 | - Key/Value operative database 299 | - Event support 300 | - Database recorded as file 301 | - Minimum config setup 302 | 303 | **Features:** 304 | - Added support to JSDoc 305 | - Added Gulp Tasks 306 | - Added Basic Testing with Mocha, Chai and Istanbul 307 | - Added .editorconfig 308 | - Added esLint support 309 | - Roadmap added 310 | - Added File structure 311 | - Added minimal validation 312 | - Added basic documentation 313 | - Added GoblinDB as Module 314 | - Added GoglinDB Helpers as an independente module 315 | - Added support to store the data on demand as JSON 316 | - Added full support to events 317 | - Added support to key changes in events 318 | - Added Method on 319 | - Added Method off 320 | - Added Method getConfig 321 | - Added Method setConfig 322 | - Added Method stopStorage 323 | - Added Method startStorage 324 | - Added Method get 325 | - Added Method push 326 | - Added Method set 327 | - Added Method update 328 | 329 | 330 | #### v.0.0.1 331 | 332 | **Features:** 333 | 334 | **Notes:** 335 | Just a "Hello world" 336 | 337 | ---------------------------------- 338 | 339 | Dev status: [![Build Status](https://travis-ci.org/GoblinDBRocks/GoblinDB.svg?branch=dev)](https://travis-ci.org/GoblinDBRocks/GoblinDB) 340 | 341 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /test/goblin.js: -------------------------------------------------------------------------------- 1 | const chai = require('chai'), 2 | expect = chai.expect, 3 | gutil = require('gulp-util'), 4 | fs = require('fs'); 5 | 6 | // Plugins 7 | require('mocha-sinon'); 8 | chai.use(require('chai-fs')); 9 | let dbReady = false, restoreReady = false; 10 | const testDB = {db: './test/testDB.json', ambush: './test/testDB.goblin'}; 11 | const restoreDB = {db: './test/data/restore.json', ambush: './test/data/restore.goblin'}; 12 | const GDB = require('../index'); 13 | 14 | const goblinDB = GDB({'fileName': './test/testDB', mode: 'strict'}, function(err) { 15 | err && console.error('ERROR INITIALIZING DB', err); 16 | dbReady = true; 17 | }); 18 | 19 | const errors = require('../lib/logger/errors.js'); 20 | 21 | // Mute feature for console.log 22 | // @see: http://stackoverflow.com/a/1215400 23 | const consoleLogger = function(){ 24 | let oldConsoleLog = null; 25 | const pub = {}; 26 | 27 | pub.enable = function enableLogger() { 28 | if (oldConsoleLog === null) { 29 | return; 30 | } 31 | 32 | console.log = oldConsoleLog; 33 | }; 34 | 35 | pub.disable = function disableLogger() { 36 | oldConsoleLog = console.log; 37 | console.log = function() {}; 38 | }; 39 | 40 | return pub; 41 | }(); 42 | 43 | function emptyAmbushFunctions() { 44 | const currentFunctions = goblinDB.ambush.list(); 45 | currentFunctions.forEach(function(element) { 46 | goblinDB.ambush.remove(element); 47 | }); 48 | } 49 | 50 | function cleanGoblin (callback) { 51 | goblinDB.set({}); 52 | 53 | callback(); 54 | } 55 | 56 | function cleanAmbush (callback) { 57 | const funcs = goblinDB.ambush.list(); 58 | 59 | for(let i = 0; i < funcs.length; i++) { 60 | goblinDB.ambush.remove(funcs[i]); 61 | } 62 | 63 | callback(); 64 | } 65 | 66 | function waitDbContent(time, callback) { 67 | setTimeout(function(){ 68 | callback(); 69 | }, time); 70 | } 71 | 72 | function cleanUp (file){ 73 | fs.exists(file, function(exists) { 74 | if (exists) { 75 | fs.unlinkSync(file); 76 | } else { 77 | gutil.colors.red(`${file} not found, so not deleting.`); 78 | } 79 | }); 80 | } 81 | 82 | function checkFileCreation(file, done) { 83 | const interval = setInterval(() => { 84 | if (dbReady) { 85 | fs.open(file, 'r', (err, fd) => { 86 | expect(err).to.equal(null); 87 | done(); 88 | }); 89 | 90 | clearInterval(interval); 91 | } 92 | }, 30); 93 | } 94 | 95 | /**/ 96 | describe('Database creation and restore:', function() { 97 | it('Database - File created successfully', function(done) { 98 | checkFileCreation(testDB.db, done); 99 | }); 100 | 101 | it('Ambush (Lambda) - File created successfully', function(done) { 102 | checkFileCreation(testDB.ambush, done); 103 | }); 104 | 105 | it('Database - Store an object in memory after read from file', function() { 106 | expect(typeof(goblinDB.get())).to.deep.equal('object'); 107 | }); 108 | 109 | it('Ambush (Lambda) - Store an array in memory after read from file', function() { 110 | expect(Array.isArray(goblinDB.ambush.list())).to.equal(true); 111 | }); 112 | }); 113 | 114 | describe('Ambush (Lambda) test', function() { 115 | let control; 116 | let simpleFunction = { 117 | id: 'testing-simple-function', 118 | category: ['test'], 119 | description: 'This is a simple function', 120 | action: function() { 121 | control = true; 122 | } 123 | }; 124 | 125 | let argumentFunction = { 126 | id: 'testing-argument-function', 127 | category: ['test', 'test-argument'], 128 | description: 'This is a function with arguments', 129 | action: function(argument) { 130 | control = argument; 131 | } 132 | }; 133 | 134 | let fullFunction = { 135 | id: 'testing-callback-function', 136 | category: ['test', 'test-callback'], 137 | description: 'This is a function with arguments and callback', 138 | action: function(argument, callback) { 139 | callback(argument); 140 | } 141 | }; 142 | 143 | describe('Events:', () => { 144 | afterEach(function(done) { 145 | cleanAmbush(done); 146 | }); 147 | 148 | it('on add', done => { 149 | goblinDB.on('ambush-add', result => { 150 | expect(result.value).to.deep.equal(simpleFunction); 151 | expect(result.oldValue).to.be.equal(); 152 | done(); 153 | goblinDB.off('ambush-add'); 154 | }); 155 | goblinDB.ambush.add(simpleFunction); 156 | }); 157 | 158 | it('on remove', done => { 159 | goblinDB.on('ambush-remove', result => { 160 | goblinDB.off('ambush-remove'); 161 | expect(result.value).to.be.equal(); 162 | expect(result.oldValue[0].id).to.be.equal(simpleFunction.id); 163 | done(); 164 | }); 165 | goblinDB.ambush.add(simpleFunction); 166 | goblinDB.ambush.remove(simpleFunction.id); 167 | }); 168 | 169 | it('on update', done => { 170 | goblinDB.on('ambush-update', result => { 171 | expect(result.value.category).to.deep.equal(['probando']); 172 | expect(result.oldValue.id).to.be.equal(simpleFunction.id); 173 | done(); 174 | goblinDB.off('ambush-update'); 175 | }); 176 | goblinDB.ambush.add(simpleFunction); 177 | goblinDB.ambush.update(simpleFunction.id, {category: ['probando']}); 178 | }); 179 | 180 | it('on change', done => { 181 | let changes = 0; 182 | const cleaner = object => { 183 | return { 184 | id: object.id, 185 | category: object.category, 186 | description: object.description 187 | }; 188 | }; 189 | 190 | goblinDB.on('ambush-change', result => { 191 | changes++; 192 | 193 | switch(changes) { 194 | case 1: 195 | expect(result.value).to.deep.equal(simpleFunction); 196 | expect(result.oldValue).to.be.equal(); 197 | return; 198 | case 2: 199 | expect(result.value).to.deep.equal(argumentFunction); 200 | expect(result.oldValue).to.be.equal(); 201 | return; 202 | case 3: 203 | expect(result.value).to.deep.equal(fullFunction); 204 | expect(result.oldValue).to.be.equal(); 205 | return; 206 | case 4: 207 | expect(result.value).to.be.equal(); 208 | expect(result.oldValue.map(cleaner)).to.deep.equal([ 209 | simpleFunction, 210 | argumentFunction, 211 | fullFunction 212 | ].map(cleaner)); 213 | return; 214 | case 5: 215 | expect(result.value.description).to.deep.equal('Changing description'); 216 | expect(result.oldValue.description).to.be.equal(fullFunction.description); 217 | } 218 | 219 | done(); 220 | goblinDB.off('ambush-change'); 221 | }); 222 | 223 | goblinDB.ambush.add(simpleFunction); 224 | goblinDB.ambush.add(argumentFunction); 225 | goblinDB.ambush.add(fullFunction); 226 | goblinDB.ambush.remove(simpleFunction.id); 227 | goblinDB.ambush.update(fullFunction.id, {description: 'Changing description'}); 228 | }); 229 | 230 | it('on error', done => { 231 | goblinDB.on('error', result => { 232 | expect(result.msg).to.be.equal('[GoblinDB]: Ambush saving error: no data provided or data is not an object/Array.'); 233 | done(); 234 | goblinDB.off('error'); 235 | }); 236 | 237 | try { 238 | goblinDB.ambush.add([]); 239 | } catch(e) { 240 | console.error(e); 241 | goblinDB.off('error'); 242 | } 243 | }); 244 | }); 245 | 246 | describe('Methods:', function() { 247 | 248 | describe('add(): As Expected', function() { 249 | it('Simple function. No Arguments and No Callback', function() { 250 | goblinDB.ambush.add(simpleFunction); 251 | expect(goblinDB.ambush.details('testing-simple-function')).to.be.deep.equal(simpleFunction); 252 | }); 253 | 254 | it('Function with Arguments. No Callback', function() { 255 | goblinDB.ambush.add(argumentFunction); 256 | expect(goblinDB.ambush.details('testing-argument-function')).to.be.deep.equal(argumentFunction); 257 | }); 258 | 259 | it('Function with Arguments and Callback', function() { 260 | goblinDB.ambush.add(fullFunction); 261 | expect(goblinDB.ambush.details('testing-callback-function')).to.be.deep.equal(fullFunction); 262 | }); 263 | }); 264 | 265 | describe('add(): Error Management', function() { 266 | it('No Arguments provided', function() { 267 | expect(function () { goblinDB.ambush.add(); }).to.throw(errors.AMBUSH_INVALID_DATA); 268 | }); 269 | 270 | it('Wrong Arguments provided: Array', function() { 271 | expect(function () { goblinDB.ambush.add([]); }).to.throw(errors.AMBUSH_INVALID_DATA); 272 | }); 273 | 274 | it('Wrong Arguments provided: No ID', function() { 275 | expect(function () { goblinDB.ambush.add({ 276 | category: [], 277 | action: function(){}, 278 | }); }).to.throw(errors.AMBUSH_INVALID_ID); 279 | }); 280 | 281 | it('Wrong Arguments provided: No right ID type of data', function() { 282 | expect(function () { goblinDB.ambush.add({ 283 | id: 1, 284 | category: [], 285 | action: function(){}, 286 | }); }).to.throw(errors.AMBUSH_INVALID_ID); 287 | }); 288 | 289 | it('Wrong Arguments provided: No CATEGORY', function() { 290 | expect(function () { goblinDB.ambush.add({ 291 | id: 'test', 292 | action: function(){}, 293 | }); }).to.throw(errors.AMBUSH_INVALID_CATEGORY); 294 | }); 295 | 296 | it('Wrong Arguments provided: No right CATEGORY type of data', function() { 297 | expect(function () { goblinDB.ambush.add({ 298 | id: 'test', 299 | category: '', 300 | action: function(){}, 301 | }); }).to.throw(errors.AMBUSH_INVALID_CATEGORY); 302 | }); 303 | 304 | it('Wrong Arguments provided: No ACTION', function() { 305 | expect(function () { goblinDB.ambush.add({ 306 | id: 'test', 307 | category: [], 308 | }); }).to.throw(errors.AMBUSH_INVALID_ACTION); 309 | }); 310 | 311 | it('Wrong Arguments provided: No right ACTION type of data', function() { 312 | expect(function () { goblinDB.ambush.add({ 313 | id: 'test', 314 | category: [], 315 | action: [], 316 | }); }).to.throw(errors.AMBUSH_INVALID_ACTION); 317 | }); 318 | 319 | it('Wrong ID: The id already exist in the database', function() { 320 | expect(function () { goblinDB.ambush.add({ 321 | id: 'testing-simple-function', 322 | category: ['test-category'], 323 | action: function() {}, 324 | });}).to.throw(errors.AMBUSH_PROVIDED_ID_ALREADY_EXIST); 325 | }); 326 | }); 327 | 328 | describe('remove(): As Expected', function() { 329 | it('Simple function. No Arguments and No Callback', function() { 330 | goblinDB.ambush.remove('testing-simple-function'); 331 | expect(goblinDB.ambush.list().length).to.be.equal(2); 332 | }); 333 | 334 | it('Function with Arguments. No Callback', function() { 335 | goblinDB.ambush.remove('testing-argument-function'); 336 | expect(goblinDB.ambush.list().length).to.be.equal(1); 337 | }); 338 | 339 | it('Function with Arguments and Callback', function() { 340 | goblinDB.ambush.remove('testing-callback-function'); 341 | expect(goblinDB.ambush.list().length).to.be.equal(0); 342 | }); 343 | }); 344 | 345 | describe('remove(): Error Management', function() { 346 | it('Wrong Arguments provided: No ID', function() { 347 | expect(function () { goblinDB.ambush.remove(); }).to.throw(errors.AMBUSH_INVALID_ID); 348 | }); 349 | it('Wrong Arguments provided: No right ID type of data', function() { 350 | expect(function () { goblinDB.ambush.remove({id: 1}); }).to.throw(errors.AMBUSH_INVALID_ID); 351 | }); 352 | }); 353 | 354 | describe('update(): As Expected', function() { 355 | it('Overwrite the function completely:', function(){ 356 | var origin = { 357 | id: 'testing-origin', 358 | category: ['test'], 359 | description: 'This is a simple function', 360 | action: function(){ 361 | control = true; 362 | } 363 | }; 364 | 365 | var after = { 366 | id: 'testing-after', 367 | category: ['test-modified'], 368 | description: 'This is a modified function', 369 | action: function(){ 370 | control = 'modified'; 371 | } 372 | }; 373 | 374 | goblinDB.ambush.add(origin); 375 | goblinDB.ambush.update('testing-origin', after); 376 | expect(goblinDB.ambush.details('testing-after')).to.be.deep.equal(after); 377 | goblinDB.ambush.remove('testing-after'); 378 | 379 | }); 380 | it('Overwrite the -ID- only:', function(){ 381 | const origin = { 382 | id: 'testing-origin', 383 | category: ['test'], 384 | description: 'This is a simple function', 385 | action: function(){ 386 | control = true; 387 | } 388 | }; 389 | 390 | goblinDB.ambush.add(origin); 391 | goblinDB.ambush.update('testing-origin', {id: 'testing-after'}); 392 | origin.id = 'testing-after'; 393 | expect(goblinDB.ambush.details('testing-after')).to.be.deep.equal(origin); 394 | goblinDB.ambush.remove('testing-after'); 395 | }); 396 | it('Overwrite the -ACTION- only:', function(){ 397 | const origin = { 398 | id: 'testing-origin', 399 | category: ['test'], 400 | description: 'This is a simple function', 401 | action: function(){ 402 | control = true; 403 | } 404 | }; 405 | const changeFactor = function(){ 406 | return 'Now... is different!'; 407 | }; 408 | 409 | goblinDB.ambush.add(origin); 410 | goblinDB.ambush.update('testing-origin', {action: changeFactor}); 411 | origin.action = changeFactor; 412 | expect(goblinDB.ambush.details('testing-origin')).to.be.deep.equal(origin); 413 | goblinDB.ambush.remove('testing-origin'); 414 | }); 415 | 416 | it('Overwrite the -CATEGORY- only:', function(){ 417 | const origin = { 418 | id: 'testing-origin', 419 | category: ['test'], 420 | description: 'This is a simple function', 421 | action: function(){ 422 | control = true; 423 | } 424 | }; 425 | const changeFactor = ['Hello-test']; 426 | 427 | goblinDB.ambush.add(origin); 428 | goblinDB.ambush.update('testing-origin', {category: changeFactor}); 429 | origin.category = changeFactor; 430 | expect(goblinDB.ambush.details('testing-origin')).to.be.deep.equal(origin); 431 | goblinDB.ambush.remove('testing-origin'); 432 | }); 433 | 434 | it('Overwrite the -DESCRIPTION- only:', function(){ 435 | const origin = { 436 | id: 'testing-origin', 437 | category: ['test'], 438 | description: 'This is a simple function', 439 | action: function(){ 440 | control = true; 441 | } 442 | }; 443 | const changeFactor = 'Hello-test'; 444 | 445 | goblinDB.ambush.add(origin); 446 | goblinDB.ambush.update('testing-origin', {description: changeFactor}); 447 | origin.description = changeFactor; 448 | expect(goblinDB.ambush.details('testing-origin')).to.be.deep.equal(origin); 449 | goblinDB.ambush.remove('testing-origin'); 450 | }); 451 | }); 452 | 453 | describe('update(): Error Management', function() { 454 | before(function() { 455 | // Add testing-callback-function and testing-simple-function ambush for testing purpose 456 | goblinDB.ambush.add(fullFunction); 457 | goblinDB.ambush.add(simpleFunction); 458 | }); 459 | after(function() { 460 | goblinDB.ambush.remove('testing-callback-function'); 461 | }); 462 | 463 | it('Wrong ID conflict Management', function (){ 464 | expect(function () { 465 | goblinDB.ambush.update('invented-id', { 466 | category: ['intented-data'] 467 | }); 468 | }).to.throw(errors.AMBUSH_UPDATE_INVALID_REFERENCE); 469 | }); 470 | 471 | it('Wrong ID shall not add functions', function (){ 472 | const currentList = goblinDB.ambush.list(); 473 | let actualList; 474 | 475 | consoleLogger.disable(); 476 | try { 477 | goblinDB.ambush.update('invented-id', {category: ['intented-data']}); 478 | } catch(e) { 479 | actualList = goblinDB.ambush.list(); 480 | } 481 | consoleLogger.enable(); 482 | 483 | expect(currentList).to.be.deep.equal(actualList); 484 | }); 485 | 486 | it('Wrong Arguments provided: No ID', function() { 487 | expect(function () { goblinDB.ambush.update(); }).to.throw(errors.AMBUSH_INVALID_ID); 488 | }); 489 | 490 | it('Wrong Arguments provided: No right ID type of data', function() { 491 | expect(function () { goblinDB.ambush.update(1); }).to.throw(errors.AMBUSH_INVALID_ID); 492 | }); 493 | 494 | it('No Arguments provided', function() { 495 | expect(function() { 496 | goblinDB.ambush.update('testing-callback-function'); 497 | }).to.throw(errors.AMBUSH_INVALID_DATA); 498 | }); 499 | 500 | it('Wrong Arguments provided: Array', function() { 501 | expect(function() { 502 | goblinDB.ambush.update('testing-callback-function', []); 503 | }).to.throw(errors.AMBUSH_INVALID_DATA); 504 | }); 505 | 506 | it('Wrong Arguments provided: No right ID type of data', function() { 507 | expect(function () { goblinDB.ambush.update('testing-callback-function',{ 508 | id: 1, 509 | category: [], 510 | action: function(){}, 511 | });}).to.throw(errors.AMBUSH_INVALID_ID); 512 | }); 513 | 514 | it('Wrong Arguments provided: No right CATEGORY type of data', function() { 515 | expect(function () { goblinDB.ambush.update('testing-callback-function',{ 516 | id: 'test', 517 | category: 1, 518 | action: function(){}, 519 | });}).to.throw(errors.AMBUSH_INVALID_CATEGORY); 520 | }); 521 | 522 | it('Wrong Arguments provided: No right ACTION type of data', function() { 523 | expect(function () { goblinDB.ambush.add({ 524 | id: 'test', 525 | category: [], 526 | action: [], 527 | });}).to.throw(errors.AMBUSH_INVALID_ACTION); 528 | }); 529 | 530 | it('Wrong ID: The id already exist in the database', function() { 531 | expect(function () { goblinDB.ambush.update('testing-simple-function', { 532 | id: 'testing-callback-function' 533 | });}).to.throw(errors.AMBUSH_PROVIDED_ID_ALREADY_EXIST); 534 | }); 535 | }); 536 | 537 | describe('list(): As Expected', function() { 538 | it('Brings all the functions', function() { 539 | cleanAmbush(function() { 540 | goblinDB.ambush.add(simpleFunction); 541 | goblinDB.ambush.add(fullFunction); 542 | }); 543 | expect(goblinDB.ambush.list().length).to.be.equal(2); 544 | }); 545 | it('Brings all the functions filtered by category', function() { 546 | expect(goblinDB.ambush.list('test').length).to.be.equal(2); 547 | expect(goblinDB.ambush.list('test-callback').length).to.be.equal(1); 548 | }); 549 | }); 550 | 551 | describe('list(): Error Management', function() { 552 | it('Deal with no real category', function(){ 553 | expect(goblinDB.ambush.list('test-invented').length).to.be.equal(0); 554 | }); 555 | it('Wrong Arguments provided: No right CATEGORY type of data', function(){ 556 | expect(goblinDB.ambush.list(123).length).to.be.equal(2); 557 | }); 558 | }); 559 | 560 | describe('details(): As Expected', function() { 561 | it('Brings all the details of an existing function', function() { 562 | expect(goblinDB.ambush.details('testing-simple-function')).to.be.deep.equal(simpleFunction); 563 | }); 564 | }); 565 | 566 | describe('details(): Error Management', function() { 567 | it('Wrong Arguments provided: No ID', function() { 568 | expect(function () { goblinDB.ambush.details(); }).to.throw(errors.AMBUSH_INVALID_ID); 569 | }); 570 | 571 | it('Wrong Arguments provided: No right ID type of data', function() { 572 | expect(function () { goblinDB.ambush.details(1); }).to.throw(errors.AMBUSH_INVALID_ID); 573 | }); 574 | 575 | it('Wrong ID: The requested id does not exist', function() { 576 | expect(function () { goblinDB.ambush.details('testing-invented') }).to.throw(errors.AMBUSH_NOT_STORED_ID); 577 | }); 578 | }); 579 | 580 | describe('run(): As Expected', function() { 581 | it('Simple function. No Arguments and No Callback', function() { 582 | control = false; 583 | goblinDB.ambush.run('testing-simple-function'); 584 | expect(control).to.be.equal(true); 585 | }); 586 | 587 | it('Function with Arguments. No Callback', function() { 588 | control = false; 589 | goblinDB.ambush.add(argumentFunction); 590 | goblinDB.ambush.run('testing-argument-function', true); 591 | expect(control).to.be.equal(true); 592 | }); 593 | 594 | it('Function with Arguments and Callback', function() { 595 | control = false; 596 | goblinDB.ambush.run('testing-callback-function', true, function(arg){ 597 | control = arg; 598 | }); 599 | expect(control).to.be.equal(true); 600 | }); 601 | }); 602 | 603 | describe('run(): Error Management', function() { 604 | it('Wrong ID conflict Management', function() { 605 | expect(function () { goblinDB.ambush.run('invented-id-function', false, console.log); }).to.throw(errors.AMBUSH_INVALID_REFERENCE); 606 | }); 607 | 608 | it('Shall not run a removed function', function() { 609 | control = false; 610 | goblinDB.ambush.run('testing-callback-function', true, function(arg){ 611 | control = arg; 612 | }); 613 | expect(control).to.be.equal(true); 614 | goblinDB.ambush.remove('testing-callback-function'); 615 | expect(function () { 616 | goblinDB.ambush.run('testing-callback-function', false, function(arg){ 617 | control = arg; 618 | }); 619 | }).to.throw(errors.AMBUSH_INVALID_REFERENCE); 620 | expect(control).to.be.equal(true); 621 | }); 622 | 623 | it('Wrong Arguments provided: No ID', function() { 624 | expect(function () { goblinDB.ambush.run(); }).to.throw(errors.AMBUSH_INVALID_ID); 625 | }); 626 | 627 | it('Wrong Arguments provided: No right ID type of data', function() { 628 | expect(function () { goblinDB.ambush.run(1); }).to.throw(errors.AMBUSH_INVALID_ID); 629 | }); 630 | 631 | it('Wrong Arguments provided: No right CALLBACK type of data', function() { 632 | expect(function () { goblinDB.ambush.run('test', 'test-argument', 'callback'); }).to.throw(errors.AMBUSH_NO_CALLBACK); 633 | }); 634 | }); 635 | }); 636 | }); 637 | /**/ 638 | 639 | describe('Database', function() { 640 | beforeEach(function(done) { 641 | cleanGoblin(done); 642 | }); 643 | beforeEach(function(done) { 644 | cleanAmbush(done); 645 | }); 646 | beforeEach(function() { 647 | this.sinon.stub(console, 'error'); 648 | }); 649 | 650 | describe('Enviroment:', function() { 651 | describe('JSON Database:', function() { 652 | it('File creation for data', function() { 653 | expect(testDB.db).to.be.a.file() 654 | }); 655 | 656 | it('File creation for Ambush (Lmabda)', function() { 657 | expect(testDB.ambush).to.be.a.file() 658 | }); 659 | }) 660 | 661 | describe('JSON Database:', function() { 662 | it('Content for data', function(done) { 663 | waitDbContent(10, function() { 664 | expect(testDB.db).with.content('{}\n'); 665 | done(); 666 | }) 667 | }); 668 | 669 | it('Content for Ambush (Lmabda)', function(done) { 670 | emptyAmbushFunctions(); 671 | waitDbContent(10, function() { 672 | expect(testDB.ambush).with.content('[]\n'); 673 | done(); 674 | }) 675 | }); 676 | }); 677 | }); 678 | 679 | describe('Events:', () => { 680 | it('on set', done => { 681 | const v = {are: 'deep'}; 682 | goblinDB.on('set', result => { 683 | expect(result.value).to.deep.equal(v); 684 | done(); 685 | goblinDB.off('set'); 686 | }); 687 | goblinDB.set(v); 688 | }); 689 | 690 | it('on push', done => { 691 | const v = {are: 'deep'}; 692 | goblinDB.on('push', result => { 693 | expect(result.value).to.deep.equal(v); 694 | done(); 695 | goblinDB.off('push'); 696 | }); 697 | goblinDB.push(v); 698 | }); 699 | 700 | it('on update', done => { 701 | const v = {are: 'deep'}; 702 | goblinDB.on('update', result => { 703 | expect(result.value).to.deep.equal('new-value'); 704 | expect(result.oldValue).to.deep.equal('deep'); 705 | done(); 706 | goblinDB.off('update'); 707 | }); 708 | goblinDB.set(v); 709 | goblinDB.update('new-value', 'are'); 710 | }); 711 | 712 | it('on truncate', done => { 713 | goblinDB.on('truncate', result => { 714 | expect(result.value).to.deep.equal({}); 715 | done(); 716 | goblinDB.off('truncate'); 717 | }); 718 | goblinDB.truncate(); 719 | }); 720 | 721 | it('on delete', done => { 722 | const v = {test: 1}; 723 | goblinDB.set(v, 'data'); 724 | goblinDB.on('delete', result => { 725 | expect(result.value).to.deep.equal(); 726 | expect(result.oldValue).to.deep.equal(v); 727 | done(); 728 | goblinDB.off('delete'); 729 | }); 730 | goblinDB.delete('data'); 731 | }); 732 | 733 | it('on change', done => { 734 | let changes = 0; 735 | 736 | goblinDB.on('change', result => { 737 | changes++; 738 | 739 | if (changes === 3) { 740 | expect(result.value).to.deep.equal({ prueba: 10 }); 741 | expect(result.oldValue).to.deep.equal(); 742 | done(); 743 | goblinDB.off('change'); 744 | } 745 | }); 746 | 747 | const v = {test: 1}; 748 | goblinDB.set(v, 'data'); 749 | goblinDB.delete('data'); 750 | goblinDB.push({prueba: 10}, 'deep.data'); 751 | }); 752 | }); 753 | 754 | describe('Methods:', function() { 755 | const demoContent = { 756 | 'data-test': 'testing content', 757 | 'more-data-test': [123, true, 'hello'], 758 | 'to': { 759 | 'delete': { 760 | 'nested': { 761 | 'here': 'finish' 762 | } 763 | } 764 | } 765 | }; 766 | 767 | beforeEach(function() { 768 | goblinDB.set(demoContent) 769 | }); 770 | 771 | it('Method get(): All Data', function() { 772 | expect(goblinDB.get()).to.deep.equal(demoContent); 773 | }); 774 | 775 | it('Method get(): Key Data', function() { 776 | expect(goblinDB.get('data-test')).to.deep.equal(demoContent['data-test']); 777 | }); 778 | 779 | it('Method set(): Replace All', function() { 780 | goblinDB.set({'hello': 'there', 'more-data': 'yeah!'}); 781 | expect(goblinDB.get()).to.deep.equal({'hello': 'there', 'more-data': 'yeah!'}); 782 | }); 783 | it('Method set(): Replace Key Content', function() { 784 | goblinDB.set({'more': 'details'}, 'more-data'); 785 | expect(goblinDB.get('more-data')).to.deep.equal({'more': 'details'}); 786 | }); 787 | it('Method push(): Creation', function() { 788 | goblinDB.push({'more':'data'}); 789 | expect(Object.keys(goblinDB.get()).length).to.be.equal(4); 790 | }); 791 | it('Method update(): Update object', function() { 792 | goblinDB.update({'more':'data'}, 'data-test'); 793 | goblinDB.update([1,2,3,4,5], 'more-data-test'); 794 | goblinDB.update('nothing', 'to'); 795 | expect(goblinDB.get()).to.deep.equal({ 796 | 'data-test': {'more':'data'}, 797 | 'more-data-test': [1,2,3,4,5], 798 | 'to': 'nothing' 799 | }); 800 | }); 801 | it('Method update(): Throw error when invalid pointer (invalid tree node route).', function() { 802 | expect(() => { 803 | goblinDB.update('nothing', 'this-should-not-exist'); 804 | }).to.throw(errors.DB_UPDATE_POIN_NOT_EXIST) 805 | }); 806 | it('Deep method set(): Create a deep object', function() { 807 | goblinDB.set({are: 'deep'}, 'internal.references.in.goblin'); 808 | expect(goblinDB.get('internal')).to.deep.equal({'references': {'in': {'goblin': {'are': 'deep'}}}}); // internal.references.in.goblin.are.deep 809 | }); 810 | it('Deep method get(): Get a deep node', function() { 811 | expect(goblinDB.get('to.delete.nested.here')).to.deep.equal('finish'); 812 | }); 813 | it('Deep method push(): Push two objects deep', function() { 814 | goblinDB.push({'deeper':'than expected'}, 'internal.references.in.goblin.push'); 815 | goblinDB.push({'cooler':'than expected'}, 'internal.references.in.goblin.push'); 816 | expect(Object.keys(goblinDB.get('internal.references.in.goblin.push')).length).to.be.equal(2); 817 | }); 818 | it('Method getConfig(): Content', function() { 819 | expect(goblinDB.getConfig()).to.deep.equal({ 820 | fileName: './test/testDB', 821 | files: { 822 | ambush: './test/testDB.goblin', 823 | db: './test/testDB.json' 824 | }, 825 | pointerSymbol: ".", 826 | logPrefix: '[GoblinDB]', 827 | recordChanges: true, 828 | mode: 'strict' 829 | }); 830 | }); 831 | it('Method updateConfig(): Changes', function() { 832 | goblinDB.updateConfig({logPrefix: 'GoblinRocks!'}); 833 | expect(goblinDB.getConfig()).to.deep.equal({ 834 | fileName: './test/testDB', 835 | files: { 836 | ambush: './test/testDB.goblin', 837 | db: './test/testDB.json' 838 | }, 839 | pointerSymbol: ".", 840 | logPrefix: '[GoblinRocks!]', 841 | recordChanges: true, 842 | mode: 'strict' 843 | }); 844 | }); 845 | 846 | it('Method stopStorage(): Changes', function() { 847 | goblinDB.stopStorage(); 848 | expect(goblinDB.getConfig().recordChanges).to.be.equal(false); 849 | }); 850 | 851 | it('Method startStorage(): Changes', function() { 852 | goblinDB.stopStorage(); 853 | goblinDB.startStorage(); 854 | expect(goblinDB.getConfig().recordChanges).to.be.equal(true); 855 | }); 856 | 857 | it('Deep method delete(): Delete a nested point', function() { 858 | expect(goblinDB.delete('to.delete.nested.here')).to.be.equal(true); 859 | expect(goblinDB.get('to.delete.nested')).to.deep.equal({}); 860 | }); 861 | 862 | it('Deep method delete(): Not delete when pointing to a invalid node', function() { 863 | expect(function () { 864 | deleted = goblinDB.delete('to.not.exist.nested.point'); 865 | }).to.throw(); 866 | }); 867 | 868 | it('Deep method delete(): Not point do nothing.', function() { 869 | let deleted = false; 870 | 871 | expect(function () { 872 | deleted = goblinDB.delete(); 873 | }).to.throw(); 874 | expect(deleted).to.be.equal(false); 875 | }); 876 | 877 | it('Deep method truncate(): Truncate all db.', function() { 878 | goblinDB.truncate(); 879 | expect(goblinDB.get()).to.deep.equal({}); 880 | }); 881 | }) 882 | 883 | describe('Mode:', function() { 884 | it('Stric mode: Expect to thow an error', function() { 885 | const strictGDB = GDB({'fileName': './test/testDB', mode: 'strict'}); 886 | expect(function () { strictGDB.ambush.update(); }).to.throw(); 887 | }); 888 | 889 | it('Development mode: Expect to get console error', function() { 890 | const devGDB = GDB({'fileName': './test/testDB', mode: 'development'}); 891 | devGDB.ambush.update(); 892 | expect( console.error.calledOnce ).to.be.true; 893 | }); 894 | 895 | it('Production mode: Expect nothing, neither to throw or call console error', function() { 896 | const prodGDB = GDB({'fileName': './test/testDB', mode: 'production'}); 897 | 898 | expect( function() { prodGDB.ambush.update() }).to.not.throw(); 899 | expect( console.error.calledOnce ).to.be.false; 900 | }); 901 | }); 902 | 903 | after(function() { 904 | cleanUp(testDB.db); 905 | cleanUp(testDB.ambush); 906 | }); 907 | }); 908 | 909 | 910 | describe('Restore from file', function() { 911 | const sumFnRestore = { 912 | id: 'testing-sum-fn', 913 | category: ['test-fn', 'test-sum'], 914 | description: 'This is a function that gets an array of numbers and send the sum via callback', 915 | action: function(numbers, callback) { 916 | callback(numbers.reduce((accumulated, curr) => accumulated + curr, 0)); 917 | } 918 | }; 919 | 920 | it('Database - Restored from file successfully', function(done) { 921 | const restoreDB = GDB( 922 | { 923 | fileName: './test/data/restore', 924 | mode: 'development' 925 | }, 926 | function(err) { 927 | err && console.error('ERROR INITIALIZING RESTORE DB', err); 928 | 929 | expect(restoreDB.get('internal.references.in.goblin.are')).to.equal('deep'); 930 | done(); 931 | } 932 | ); 933 | }); 934 | 935 | it('Ambush (Lambda) - Restored from file successfully', function(done) { 936 | const restoreDB = GDB( 937 | { 938 | fileName: './test/data/restore', 939 | mode: 'development' 940 | }, 941 | function(err) { 942 | err && console.error('ERROR INITIALIZING RESTORE DB', err); 943 | 944 | restoreDB.ambush.run(sumFnRestore.id, [90, 8, 5], function(result) { 945 | expect(result).to.equal(103); 946 | }); 947 | done(); 948 | } 949 | ); 950 | }); 951 | }); --------------------------------------------------------------------------------