All files pocketdb.js

95.45% Statements 21/22
90% Branches 9/10
100% Functions 7/7
95.45% Lines 21/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 682x 2x   2x 2x       4x 4x     4x 2x         29x 1x       28x         27x       27x       57x       28x     28x 1x       27x       1x       27x               2x      
const fs = require('fs');
const path = require('path');
 
const _getCollectionData = Symbol('getCollectionData');
const _defaultCollectionData = Symbol('defaultCollectionData');
 
class PocketDB {
  constructor(pathToDB) {
    this.dbPath = pathToDB;
    this.db = {};
 
    // If the db path doesn't exist, then create it
    if (!fs.existsSync(this.dbPath)) {
      fs.mkdirSync(this.dbPath);
    }
  }
 
  loadCollection(collection) {
    if (!collection || typeof collection !== 'object') {
      throw new TypeError('Trying to load an invalid collection.');
    }
 
    // Otherwise set it to the collection arg
    this.db[collection.name] = collection;
  }
 
  removeCollection(collectionName) {
    // Reject if you try and remove a non-existing collection
    Iif (!this.db[collectionName]) {
      throw new Error(`A collection "${collectionName}" does not exist.`);
    }
 
    delete this.db[collectionName];
  }
 
  getCollectionPath(collectionName) {
    return path.join(this.dbPath, `${collectionName}.db`);
  }
 
  getCollectionData(collectionName) {
    const collectionPath = this.getCollectionPath(collectionName);
 
    // If the collection db file exists, then return that
    if (fs.existsSync(collectionPath)) {
      return this[_getCollectionData](collectionName);
    }
 
    // Otherwise return the default data
    return this[_defaultCollectionData](collectionName);
  }
 
  [_getCollectionData](collectionName) {
    return JSON.parse(fs.readFileSync(this.getCollectionPath(collectionName)), 'utf8');
  }
 
  [_defaultCollectionData](collectionName) {
    return {
      name: collectionName,
      nextID: 1,
      items: []
    };
  }
}
 
module.exports = {
  PocketDB
};