return new Promise((resolve, reject) => {
   debug(`Refreshing database`);
   db.loadDatabase({}, err => {
     if (err) {
       debug(`Error: tokens store could not be loaded: ${ util.inspect(err) }`);
       return reject(err);
     }
   
     tokens = db.getCollection('tokens');
     if (tokens.count() === 0) {
       debug(`the token store was empty`);
       tokens = db.addCollection('tokens');
       resolve();
     } else {
       debug(`${ tokens.count() } token(s) found in the store`);
       if (isReadOnlyTokenStore) {
         return resolve();
       } else {
         debug(`Clearing previous contents of the tokens store`);
         tokens.clear();
         db.saveDatabase(err => {
           if (err) {
             debug(`Error: Could not reinitialize database on file: ${ util.inspect(err) }`);
             return reject(err);
           }
           return resolve();
         });
       }
     }
   });
 });
Ejemplo n.º 2
0
exports.setupBeforeSecurity = function (mstream, program) {
  shareDB = new loki(path.join(program.storage.dbDirectory, dbName));
  shareDB.loadDatabase({}, err => {
    shareCollection = shareDB.getCollection('playlists');
    if (shareCollection === null) {
      shareCollection = shareDB.addCollection("playlists");
    }
  });

  mstream.post('/shared/get-token-and-playlist', (req, res) => {
    if (!req.body.tokenid) {
      res.status(500).json({ error: 'Please Supply Token' });
      return;
    }

    const playlistItem = shareCollection.findOne({ 'playlist_id': req.body.tokenid });
    if(!playlistItem) {
      return res.status(404).json({ error: 'Playlist Not Found' })
    }

    jwt.verify(playlistItem.token, program.secret, (err, decoded) => {
      if (err) {
        return res.redirect('/access-denied');
      }

      res.json({
        token: playlistItem.token,
        playlist: decoded.allowedFiles
      });
    });
  });
}
// database load handler
function loadHandler () {
  // load persisted database
  db.loadDatabase({}, function () {
    // initialize collection if not already existing
    if (!db.getCollection('messages')) {
      db.addCollection('messages', {unique: ['id']})
    }
  })
}
Ejemplo n.º 4
0
		fs.exists(DB_FILE, function (exists) {
          if (exists) {
          	db.loadDatabase(function () {
          		var c = db.getCollection('contacts')
				res.json(c.data);
          	});          	
          }
          else{          	          	
			res.json('No contacts');
          }
      });		
Ejemplo n.º 5
0
app.get('/', function (req, res) {
	dbr.loadDatabase({}, function() {
		user = dbr.getCollection('users')
		var foo = JSON.stringify(user.data, ['name', 'meta']);
    var username = user.get(1).name;
		res.send("Hello world " + foo);
		console.log(user.data);
		console.log(foo);
		console.log(username);
	});
});
Ejemplo n.º 6
0
 return new Promise((fulfill, reject) => {
   db.loadDatabase({}, () => {
     const coll = db.getCollection('quizItems');
     const doc = coll.get(_.sample(coll.idIndex));
     const question = {
       q: doc.q,
       a: doc.a,
       id: doc.$loki
     };
     fulfill(question);
   });
 });
Ejemplo n.º 7
0
/**
 * get data from a collection
 * @param collectionName
 * @param query
 * @param onGet
 * @private
 */
function _getData(collectionName,query,onGet){
    db.loadDatabase(
        {},
        function onLoad(){
            var collection = db.getCollection(collectionName);
            if(!collection){
                onGet(null,{});
            }else{
                var data = collection.find(query);
                onGet(null,data);
            }

        }
    );
}
Ejemplo n.º 8
0
 return new Promise((fullfill, reject) => {
     db.loadDatabase({}, () => {
         appareilDb = db.getCollection(COLLECTION_NAME);
         if (!appareilDb) {
             console.log("Creation collection : ", COLLECTION_NAME);
             appareilDb = db.addCollection(COLLECTION_NAME);
             db.saveDatabase();
             fullfill(appareilDb);
         }else {
             fullfill(appareilDb);
         }
     },(error) => {
         reject(error);
     });
 });
Ejemplo n.º 9
0
		fs.exists(DB_FILE, function (exists) {
          if (exists && typeof req.params.contact_id !='undefined') {
          	db.loadDatabase(function () {
          		var c = db.getCollection('contacts')
	          	if(c.get(parseInt(req.params.contact_id)) == null){
					res.json('No contact found');
				}
				else{
					res.json(c.get(parseInt(req.params.contact_id)));
				}
          	});  
          }
          else{
          	res.json('No Db yet');
          }
      });
Ejemplo n.º 10
0
fs.exists( db.filename, function(exists){
  if(!exists){
    console.log('File does not exist, init\'ing collection');

    posts = db.addCollection('posts','Post');
    return;
  } else {
    console.log('loading from file')
    // load the database from file
    db.loadDatabase(function(data){
      console.log(data);
      console.log(db.collections);
      posts = db.getCollection('posts');
    });
    console.log(db.collections);
  }
});
Ejemplo n.º 11
0
		fs.exists(DB_FILE, function (exists) {
          if (exists) {
          		db.loadDatabase(function () {
          			var contacts = db.getCollection('contacts');
          			contacts.insert(cntName);
					db.saveToDisk();
				});
				res.json('Contact added');
          }
          else{
          		var db2 = new lokijs(DB_FILE);
 				var contacts = db2.addCollection('contacts')
          		contacts.insert(cntName);
          		db2.saveToDisk();          	          	
			res.json('Contact added!');
          }
      });		
Ejemplo n.º 12
0
function getDeveloperCollection(callback){
    // have the DB load from disk
    db.loadDatabase({}, function(){
        // grab the developer collection
        var developer = db.getCollection('account');
        // if its null this is a new run, create the collection
        if(developer === null){
            developer = db.addCollection('account');
        }

        try{
            callback(null, developer);
        } catch(e){
            console.error('Error encountered during database developer transaction! Swallowing to preserve file integrity.');
            console.error(e);
        }
    });
}
Ejemplo n.º 13
0
 process.nextTick(function asyncAtomicWrite(){
     try {
         db.loadDatabase(
             {},
             function onLoad() {
                 var collection = db.getCollection(collectionName);
                 if (!collection) {
                     collection = db.addCollection(collectionName);
                 }
                 collection.insert(object);
             }
         );
     }catch(error){
         db.addCollection(collectionName);
         db.save();
         _atomicWrite(collectionName,object,retry++);
     }
 });
Ejemplo n.º 14
0
function getFavoritesCollection(callback){
    utils.log(null, logger, 'retreiving favorites collection');
    // have the DB load from disk
    db.loadDatabase({}, function(){
        // grab the developer collection
        var favorites = db.getCollection('favorites');
        // if its null this is a new run, create the collection
        if(favorites === null){
            favorites = db.addCollection('favorites');
        }

        try{
            callback(null, favorites);
        } catch(e){
            console.error('Error encountered during database favorites transaction! Swallowing to preserve file integrity.');
            console.error(e);
        }
    });
}
Ejemplo n.º 15
0
function getMetadataCollection(callback){
    utils.log(null, logger, 'retreiving metadata collection');
    // have the DB load from disk
    db.loadDatabase({}, function(){
        // grab the developer collection
        var metadata = db.getCollection('metadata');
        // if its null this is a new run, create the collection
        if(metadata === null){
            metadata = db.addCollection('metadata');
        }

        try{
            callback(null, metadata);
        } catch(e){
            console.error('Error encountered during database metadata transaction! Swallowing to preserve file integrity.');
            console.error(e);
        }
    });
}
Ejemplo n.º 16
0
		fs.exists(DB_FILE, function (exists) {
          if (exists && typeof req.params.contact_id !='undefined') {
          	db.loadDatabase(function () {
          		var c = db.getCollection('contacts')
	          	if(c.get(parseInt(req.params.contact_id)) == null){
					res.json('No contact found');
				}
				else{
					var cntUpd = c.get(parseInt(req.params.contact_id));					
					cntUpd.contact = req.body.contact;
					db.saveToDisk();  
					res.json('Contact updated');
				}
          	});  
          }
          else{
          	res.json('No Db yet');
          }
      })
Ejemplo n.º 17
0
const loki = require('lokijs');
const config = require('./config');
const content = require('./content');
const db = new loki('loki.json');

console.time('t1');
db.loadDatabase({}, function () {
  var tests = db.getCollection('tests');
  console.log('count', tests.count());
  let i = 0;
  for (i = 0; i < config.total; i++) {
    if (i % 20 === 0) {
      console.log(i);
    }
    tests.insert({
      id: `test${i}`,
      name: `Name-${Math.random()}`,
      value: content
    });
  }

  db.saveDatabase((err) => {
    console.log(err);
    console.timeEnd('t1');
  });
});
var loki = require('lokijs');
var db = new loki('data/db.json');

db.loadDatabase({}, function() {
  var index_collection = db.getCollection("index");

  var datos = index_collection.find({});
  var n = datos.length;
  console.log("La base de datos tiene " + n + " registros en total.")
});
Ejemplo n.º 19
0
var env			= process.env;
var colors		= require('colors');
var clear		= require('clear');
var fs			= require('fs-extra');
var serve		= require('koa-static');
var routing		= require('koa-routing');
var body		= require('koa-better-body');
var request 	= require('koa-request');
var koa			= require('koa');
var loki		= require('lokijs')

var db = new loki('content.json');
db.loadDatabase({}, function () {
	if (db.getCollection('content') === null){
		var content = db.addCollection('content');
		db.saveDatabase();
		console.log('New Loki Database created!! /content.json'.bgYellow);
	}
});

var app = koa();
app.use(function* (next) {
	// console.log('Writing koa middleware yeh?');
	yield next;
});

app.use(serve('public'));

app.use(function* (next) {
	yield next;
	this.set('Access-Control-Allow-Origin', '*');
Ejemplo n.º 20
0
 return new Promise( (resolve, reject) => {
     this.db.loadDatabase({}, resolve); 
 });
Ejemplo n.º 21
0
var webdriverio = require('webdriverio');
var client = webdriverio.remote();

var shop, company, menu, shops;
console.log('initial lokijs Database success');
lokidb.loadDatabase({}, function () {
    shop = lokidb.getCollection('shop');
    company = lokidb.getCollection('company');
    menu = lokidb.getCollection('menu');

    if (shop === null) {
        shop = lokidb.addCollection('shop');
    }
    if (company === null) {
        company = lokidb.addCollection('company');
    }
    if (menu === null) {
        menu = lokidb.addCollection('menu');
    }

    console.log('load shop items', shop.idIndex.length);
    console.log('load company items', company.idIndex.length);
    console.log('load menu items', menu.idIndex.length);
    shops = shop.find();
    initWebDriver();
});

function initWebDriver() {
    client.init().url('https://www.google.com.tw/maps/', initialSeleniumOk);
}
Ejemplo n.º 22
0
//initialize lokijs db if db.json is empty
var dbFileStats = fs.statSync('db.json');
lokiInstance = new loki('db.json');

if(dbFileStats["size"] == 0){
    var users = lokiInstance.addCollection('users');
    for(var i = 0; i < 100000; i ++){
        var firstnamerand = Math.floor(Math.random() * 1000);
        var lastnamerand = Math.floor(Math.random() * 1000);
        var username = names.firstNames[firstnamerand] + " " + names.lastNames[lastnamerand];
        var age = Math.floor(Math.random() * (60 - 18) + 18);
        users.insert({name: username, age: age});
    }
    lokiInstance.save();
}else {
    lokiInstance.loadDatabase()
};;


var app = express();


// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.get('/', cors(), function(req, res){
    var collection = lokiInstance.getCollection('users');