Completed
Push — master ( c17b81...3a1758 )
by Dimas
19:57 queued 11s
created

libs/js/user.ts   A

Complexity

Total Complexity 14
Complexity/F 4.67

Size

Lines of Code 81
Function Count 3

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 50
dl 0
loc 81
rs 10
c 0
b 0
f 0
wmc 14
mnd 11
bc 11
fnc 3
bpm 3.6666
cpm 4.6666
noi 0
1
/**
2
 * User framework
3
 */
4
class user {
5
  //constructor() { if (!this.all()) { this.fetch(null); } }
6
  key = location.host + "/userdata";
7
8
  /**
9
   * Get all userdata
10
   */
11
  all(): undefined | object | any {
12
    var data = storage().get(this.key);
13
    if (!data || data == "") {
14
      return undefined;
15
    }
16
    return data;
17
  }
18
  /**
19
   * get userdata
20
   */
21
  get(key: string) {
22
    try {
23
      var data = this.all();
24
      if (data !== undefined) {
25
        if (data.hasOwnProperty(key)) {
26
          return data[key];
27
        }
28
      }
29
      console.log("user::get", data);
30
    } catch (error) {
31
      console.error("user::get", error);
32
      return undefined;
33
    }
34
  }
35
  /**
36
   * fetch userdata
37
   */
38
  fetch(callback: Function | null) {
39
    const ini = this;
40
    return $.ajax({
41
      url: "/user",
42
      method: "POST",
43
      silent: true,
44
      indicator: false,
45
      data: {
46
        check: true,
47
        user: true,
48
      },
49
      success: function (res: Object) {
50
        if (typeof res != "object") {
51
          return;
52
        }
53
        if (res) {
54
          if (res.hasOwnProperty("id")) {
55
            (<any>res).user_id = (<any>res).id;
56
            (<any>res)._ = new Date();
57
          }
58
          if (res.hasOwnProperty("username")) {
59
            if (typeof callback == "function") {
60
              callback(res);
61
            }
62
          }
63
        }
64
        storage().set(ini.key, JSON.stringify(res));
65
        console.log("user::fetch", ini.all());
66
      },
67
    });
68
  }
69
}
70
71
if (!(typeof module !== "undefined" && module.exports)) {
72
  /**
73
   * @typedef {user} userc
74
   */
75
  const userc = new user();
76
  if (typeof window.user === "undefined") {
77
    window.user = userc;
78
  }
79
  jQuery.user = userc;
80
}
81