Issues (791)

src/cli/users/manager.js (1 issue)

1
import fs from 'fs-extra'
2
import mkdirp from 'mkdirp'
3
import path from 'path'
4
5
import {
6
  config
7
  ,coreUtils
8
  ,User
9
} from '../../cli'
10
11
let singleton = Symbol()
12
let singletonEnforcer = Symbol()
13
14
class Manager {
15
16
  constructor(enforcer) {
17
18
    if(enforcer != singletonEnforcer) throw 'Cannot construct Json singleton'
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
19
20
    this._isEnable = config.users.enable
21
    this._file = path.join(config.root, 'users', 'bdd.json')
22
  }
23
24
  static get instance() {
25
    if(!this[singleton]) {
26
      this[singleton] = new Manager(singletonEnforcer)
27
    }
28
    return this[singleton]
29
  }
30
31
  read() {
32
    if (this._isEnable) {
33
      if (coreUtils.file.exist(this._file)) {
34
        return JSON.parse(fs.readFileSync(this._file, 'utf8'))
35
      }else {
36
        this._users = []
37
        var admin = User.operations.add(config.users.default)
38
        this.save()
39
        User.operations.activate(admin.user.id)
40
        return JSON.parse(fs.readFileSync(this._file, 'utf8'))
41
      }
42
    }
43
    return []
44
  }
45
46
  save() {
47
    if (this._isEnable) {
48
      mkdirp(path.dirname(this._file))
49
      fs.writeJsonSync(this._file, this._users, { space: 2, encoding: 'utf-8' })
50
    }
51
  }
52
53
  get() {
54
    if (this._users == null) {
55
      this._users = this.read()
56
    }
57
    return this._users
58
  }
59
60
  update(json) {
61
    if (this._isEnable) {
62
      this._users = json
63
      this.save()
64
      return true
65
    }
66
    return false
67
  }
68
}
69
70
export default Manager