All files pocketdb.js

100% Statements 26/26
100% Branches 12/12
100% Functions 7/7
100% Lines 26/26
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 68 69 70 71 72 73 74 75 76 772x 2x   2x 2x       4x 4x     4x 2x         28x 1x       27x         28x 2x     26x   26x   1x     26x   26x       81x       27x     27x 1x       26x       1x       26x               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
    if (!this.db[collectionName]) {
      return Promise.reject(`A collection "${collectionName}" does not exist.`);
    }
 
    const collectionPath = this.getCollectionPath(collectionName);
 
    if (fs.existsSync(collectionPath)) {
      // Remove the db file, then unload it from the db
      fs.unlinkSync(collectionPath);
    }
 
    delete this.db[collectionName];
 
    return Promise.resolve();
  }
 
  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
};