Completed
Push — master ( 4e8cb2...696b71 )
by Wallace
01:27
created

database.js ➔ ???   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 3
c 3
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 3
cp 1
crap 3
rs 9.4285
1
/**
2
 * Database
3
 */
4
'use strict'
5
6 1
const fs = require('fs')
7 1
const _ = require('lodash')
8
9 1
const __ = {
10
  getDatabase: database => {
11 10
    if (!fs.existsSync(database) || !fs.readFileSync(database, 'utf8')) {
12 3
      return false
13
    }
14
15 7
    return JSON.parse(fs.readFileSync(database, 'utf8'))
16
  }
17
}
18
19 1
const Database = () => {
20 1
  const proto = {
21
    data: {},
22
    database: '',
23
24
    /**
25
     * Set file database.
26
     *
27
     * @param {string} pathname
28
     */
29
    setFile: function (pathname) {
30 6
      let regex = new RegExp(/\.json$/)
31
32 6
      if (!regex.test(pathname)) {
33 1
        throw new Error('The database file must be a json file')
34
      }
35
36 5
      this.database = pathname
37
38 5
      return this
39
    },
40
41
    /**
42
     * Add a key and value for database.
43
     *
44
     * @param {string} key
45
     * @param {string} value
46
     */
47
    add: function (key, value) {
48 5
      this.data = __.getDatabase(this.database) || this.data
49 5
      this.data[key] = value
50
51 5
      return this
52
    },
53
54
    /**
55
     * Add values to env vars from node.
56
     *
57
     * @param {object} data
58
     */
59
    addEnv: function (data) {
60 2
      if (typeof data !== 'object') {
61 1
        throw new Error('data must be an object')
62
      }
63
64 1
      _.map(data, (value, key) => {
65 1
        process.env[key] = value
66
      })
67
    },
68
69
    /**
70
     * Add multiples keys to database.
71
     *
72
     * @param {object} data
73
     */
74
    massive: function (data) {
75 2
      if (typeof data !== 'object') {
76 1
        throw new Error('data must be an object')
77
      }
78
79 2
      _.map(data, (value, key) => this.add(key, value))
80
81 1
      return this
82
    },
83
84
    /**
85
     * Return an key from database or all data.
86
     *
87
     * @param {string} item
88
     */
89
    get: function (item) {
90 5
      let db = __.getDatabase(this.database) || this.data
91
92 5
      if (item !== undefined && !(item in db)) {
93 1
        throw new Error(`${item} is undefined`)
94
      }
95
96 4
      return db[item] || db
97
    },
98
99
    /**
100
     * Store data to db.json.
101
     */
102
    store: function () {
103 2
      fs.writeFile(this.database, JSON.stringify(this.data), err => {
104 2
        if (err) {
105 1
          throw new Error(err)
106
        }
107
108 1
        return this
109
      })
110
    }
111
  }
112
113 1
  return Object.create(proto)
114
}
115
116
module.exports = Database()
117