Browse Source

Use the modern class syntax on the server

dev_h
lovasoa 4 years ago
parent
commit
de9f9725e9
No account linked to committer's email address
1 changed files with 192 additions and 199 deletions
  1. 192
    199
      server/boardData.js

+ 192
- 199
server/boardData.js View File

@@ -32,231 +32,224 @@ var fs = require("./fs_promises.js"),
32 32
 
33 33
 /**
34 34
  * Represents a board.
35
- * @class
36
- * @constructor
37
- * @param {string} name
35
+ * @typedef {{[object_id:string]: any}} BoardElem
38 36
  */
39
-var BoardData = function (name) {
40
-  this.name = name;
41
-  /** @type {{[name: string]: {[object_id:string]: any}}} */
42
-  this.board = {};
43
-  this.file = path.join(
44
-    config.HISTORY_DIR,
45
-    "board-" + encodeURIComponent(name) + ".json"
46
-  );
47
-  this.lastSaveDate = Date.now();
48
-  this.users = new Set();
49
-};
37
+class BoardData {
38
+  /**
39
+   * @param {string} name
40
+   */
41
+  constructor(name) {
42
+    this.name = name;
43
+    /** @type {{[name: string]: BoardElem}} */
44
+    this.board = {};
45
+    this.file = path.join(
46
+      config.HISTORY_DIR,
47
+      "board-" + encodeURIComponent(name) + ".json"
48
+    );
49
+    this.lastSaveDate = Date.now();
50
+    this.users = new Set();
51
+  }
50 52
 
51
-/** Adds data to the board */
52
-BoardData.prototype.set = function (id, data) {
53
-  //KISS
54
-  data.time = Date.now();
55
-  this.validate(data);
56
-  this.board[id] = data;
57
-  this.delaySave();
58
-};
53
+  /** Adds data to the board
54
+   * @param {string} id
55
+   * @param {BoardElem} data
56
+   */
57
+  set(id, data) {
58
+    //KISS
59
+    data.time = Date.now();
60
+    this.validate(data);
61
+    this.board[id] = data;
62
+    this.delaySave();
63
+  }
59 64
 
60
-/** Adds a child to an element that is already in the board
61
- * @param {string} id - Identifier of the parent element.
62
- * @param {object} child - Object containing the the values to update.
63
- * @param {boolean} [create=true] - Whether to create an empty parent if it doesn't exist
64
- * @returns {boolean} - True if the child was added, else false
65
- */
66
-BoardData.prototype.addChild = function (parentId, child) {
67
-  var obj = this.board[parentId];
68
-  if (typeof obj !== "object") return false;
69
-  if (Array.isArray(obj._children)) obj._children.push(child);
70
-  else obj._children = [child];
65
+  /** Adds a child to an element that is already in the board
66
+   * @param {string} parentId - Identifier of the parent element.
67
+   * @param {BoardElem} child - Object containing the the values to update.
68
+   * @returns {boolean} - True if the child was added, else false
69
+   */
70
+  addChild(parentId, child) {
71
+    var obj = this.board[parentId];
72
+    if (typeof obj !== "object") return false;
73
+    if (Array.isArray(obj._children)) obj._children.push(child);
74
+    else obj._children = [child];
71 75
 
72
-  this.validate(obj);
73
-  this.delaySave();
74
-  return true;
75
-};
76
+    this.validate(obj);
77
+    this.delaySave();
78
+    return true;
79
+  }
76 80
 
77
-/** Update the data in the board
78
- * @param {string} id - Identifier of the data to update.
79
- * @param {object} data - Object containing the values to update.
80
- * @param {boolean} create - True if the object should be created if it's not currently in the DB.
81
- */
82
-BoardData.prototype.update = function (id, data, create) {
83
-  delete data.type;
84
-  delete data.tool;
81
+  /** Update the data in the board
82
+   * @param {string} id - Identifier of the data to update.
83
+   * @param {BoardElem} data - Object containing the values to update.
84
+   * @param {boolean} create - True if the object should be created if it's not currently in the DB.
85
+   */
86
+  update(id, data, create) {
87
+    delete data.type;
88
+    delete data.tool;
85 89
 
86
-  var obj = this.board[id];
87
-  if (typeof obj === "object") {
88
-    for (var i in data) {
89
-      obj[i] = data[i];
90
+    var obj = this.board[id];
91
+    if (typeof obj === "object") {
92
+      for (var i in data) {
93
+        obj[i] = data[i];
94
+      }
95
+    } else if (create || obj !== undefined) {
96
+      this.board[id] = data;
90 97
     }
91
-  } else if (create || obj !== undefined) {
92
-    this.board[id] = data;
98
+    this.delaySave();
93 99
   }
94
-  this.delaySave();
95
-};
96
-
97
-/** Removes data from the board
98
- * @param {string} id - Identifier of the data to delete.
99
- */
100
-BoardData.prototype.delete = function (id) {
101
-  //KISS
102
-  delete this.board[id];
103
-  this.delaySave();
104
-};
105 100
 
106
-/** Reads data from the board
107
- * @param {string} id - Identifier of the element to get.
108
- * @returns {object} The element with the given id, or undefined if no element has this id
109
- */
110
-BoardData.prototype.get = function (id, children) {
111
-  return this.board[id];
112
-};
101
+  /** Removes data from the board
102
+   * @param {string} id - Identifier of the data to delete.
103
+   */
104
+  delete(id) {
105
+    //KISS
106
+    delete this.board[id];
107
+    this.delaySave();
108
+  }
113 109
 
114
-/** Reads data from the board
115
- * @param {string} [id] - Identifier of the first element to get.
116
- * @param {BoardData~processData} callback - Function to be called with each piece of data read
117
- */
118
-BoardData.prototype.getAll = function (id) {
119
-  var results = [];
120
-  for (var i in this.board) {
121
-    if (!id || i > id) {
122
-      results.push(this.board[i]);
123
-    }
110
+  /** Reads data from the board
111
+   * @param {string} id - Identifier of the element to get.
112
+   * @returns {BoardElem} The element with the given id, or undefined if no element has this id
113
+   */
114
+  get(id) {
115
+    return this.board[id];
124 116
   }
125
-  return results;
126
-};
127 117
 
128
-/**
129
- * This callback is displayed as part of the BoardData class.
130
- * Describes a function that processes data that comes from the board
131
- * @callback BoardData~processData
132
- * @param {object} data
133
- */
118
+  /** Reads data from the board
119
+   * @param {string} [id] - Identifier of the first element to get.
120
+   * @returns {BoardElem[]}
121
+   */
122
+  getAll(id) {
123
+    return Object.entries(this.board)
124
+      .filter(([i]) => !id || i > id)
125
+      .map(([_, elem]) => elem);
126
+  }
134 127
 
135
-/** Delays the triggering of auto-save by SAVE_INTERVAL seconds
136
- */
137
-BoardData.prototype.delaySave = function (file) {
138
-  if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
139
-  this.saveTimeoutId = setTimeout(this.save.bind(this), config.SAVE_INTERVAL);
140
-  if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY)
141
-    setTimeout(this.save.bind(this), 0);
142
-};
128
+  /** Delays the triggering of auto-save by SAVE_INTERVAL seconds
129
+   */
130
+  delaySave() {
131
+    if (this.saveTimeoutId !== undefined) clearTimeout(this.saveTimeoutId);
132
+    this.saveTimeoutId = setTimeout(this.save.bind(this), config.SAVE_INTERVAL);
133
+    if (Date.now() - this.lastSaveDate > config.MAX_SAVE_DELAY)
134
+      setTimeout(this.save.bind(this), 0);
135
+  }
143 136
 
144
-/** Saves the data in the board to a file.
145
- * @param {string} [file=this.file] - Path to the file where the board data will be saved.
146
- */
147
-BoardData.prototype.save = async function (file) {
148
-  this.lastSaveDate = Date.now();
149
-  this.clean();
150
-  if (!file) file = this.file;
151
-  var tmp_file = backupFileName(file);
152
-  var board_txt = JSON.stringify(this.board);
153
-  if (board_txt === "{}") {
154
-    // empty board
155
-    try {
156
-      await fs.promises.unlink(file);
157
-      log("removed empty board", { name: this.name });
158
-    } catch (err) {
159
-      if (err.code !== "ENOENT") {
160
-        // If the file already wasn't saved, this is not an error
161
-        log("board deletion error", { err: err.toString() });
137
+  /** Saves the data in the board to a file.
138
+   * @param {string} [file=this.file] - Path to the file where the board data will be saved.
139
+   */
140
+  async save(file) {
141
+    this.lastSaveDate = Date.now();
142
+    this.clean();
143
+    if (!file) file = this.file;
144
+    var tmp_file = backupFileName(file);
145
+    var board_txt = JSON.stringify(this.board);
146
+    if (board_txt === "{}") {
147
+      // empty board
148
+      try {
149
+        await fs.promises.unlink(file);
150
+        log("removed empty board", { name: this.name });
151
+      } catch (err) {
152
+        if (err.code !== "ENOENT") {
153
+          // If the file already wasn't saved, this is not an error
154
+          log("board deletion error", { err: err.toString() });
155
+        }
156
+      }
157
+    } else {
158
+      try {
159
+        await fs.promises.writeFile(tmp_file, board_txt);
160
+        await fs.promises.rename(tmp_file, file);
161
+        log("saved board", {
162
+          name: this.name,
163
+          size: board_txt.length,
164
+          delay_ms: Date.now() - this.lastSaveDate,
165
+        });
166
+      } catch (err) {
167
+        log("board saving error", {
168
+          err: err.toString(),
169
+          tmp_file: tmp_file,
170
+        });
171
+        return;
162 172
       }
163
-    }
164
-  } else {
165
-    try {
166
-      await fs.promises.writeFile(tmp_file, board_txt);
167
-      await fs.promises.rename(tmp_file, file);
168
-      log("saved board", {
169
-        name: this.name,
170
-        size: board_txt.length,
171
-        delay_ms: Date.now() - this.lastSaveDate,
172
-      });
173
-    } catch (err) {
174
-      log("board saving error", {
175
-        err: err.toString(),
176
-        tmp_file: tmp_file,
177
-      });
178
-      return;
179 173
     }
180 174
   }
181
-};
182 175
 
183
-/** Remove old elements from the board */
184
-BoardData.prototype.clean = function cleanBoard() {
185
-  var board = this.board;
186
-  var ids = Object.keys(board);
187
-  if (ids.length > config.MAX_ITEM_COUNT) {
188
-    var toDestroy = ids
189
-      .sort(function (x, y) {
190
-        return (board[x].time | 0) - (board[y].time | 0);
191
-      })
192
-      .slice(0, -config.MAX_ITEM_COUNT);
193
-    for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
194
-    log("cleaned board", { removed: toDestroy.length, board: this.name });
176
+  /** Remove old elements from the board */
177
+  clean() {
178
+    var board = this.board;
179
+    var ids = Object.keys(board);
180
+    if (ids.length > config.MAX_ITEM_COUNT) {
181
+      var toDestroy = ids
182
+        .sort(function (x, y) {
183
+          return (board[x].time | 0) - (board[y].time | 0);
184
+        })
185
+        .slice(0, -config.MAX_ITEM_COUNT);
186
+      for (var i = 0; i < toDestroy.length; i++) delete board[toDestroy[i]];
187
+      log("cleaned board", { removed: toDestroy.length, board: this.name });
188
+    }
195 189
   }
196
-};
197 190
 
198
-/** Reformats an item if necessary in order to make it follow the boards' policy
199
- * @param {object} item The object to edit
200
- * @param {object} parent The parent of the object to edit
201
- */
202
-BoardData.prototype.validate = function validate(item, parent) {
203
-  if (item.hasOwnProperty("size")) {
204
-    item.size = parseInt(item.size) || 1;
205
-    item.size = Math.min(Math.max(item.size, 1), 50);
206
-  }
207
-  if (item.hasOwnProperty("x") || item.hasOwnProperty("y")) {
208
-    item.x = parseFloat(item.x) || 0;
209
-    item.x = Math.min(Math.max(item.x, 0), config.MAX_BOARD_SIZE);
210
-    item.x = Math.round(10 * item.x) / 10;
211
-    item.y = parseFloat(item.y) || 0;
212
-    item.y = Math.min(Math.max(item.y, 0), config.MAX_BOARD_SIZE);
213
-    item.y = Math.round(10 * item.y) / 10;
214
-  }
215
-  if (item.hasOwnProperty("opacity")) {
216
-    item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
217
-    if (item.opacity === 1) delete item.opacity;
218
-  }
219
-  if (item.hasOwnProperty("_children")) {
220
-    if (!Array.isArray(item._children)) item._children = [];
221
-    if (item._children.length > config.MAX_CHILDREN)
222
-      item._children.length = config.MAX_CHILDREN;
223
-    for (var i = 0; i < item._children.length; i++) {
224
-      this.validate(item._children[i]);
191
+  /** Reformats an item if necessary in order to make it follow the boards' policy
192
+   * @param {object} item The object to edit
193
+   */
194
+  validate(item) {
195
+    if (item.hasOwnProperty("size")) {
196
+      item.size = parseInt(item.size) || 1;
197
+      item.size = Math.min(Math.max(item.size, 1), 50);
198
+    }
199
+    if (item.hasOwnProperty("x") || item.hasOwnProperty("y")) {
200
+      item.x = parseFloat(item.x) || 0;
201
+      item.x = Math.min(Math.max(item.x, 0), config.MAX_BOARD_SIZE);
202
+      item.x = Math.round(10 * item.x) / 10;
203
+      item.y = parseFloat(item.y) || 0;
204
+      item.y = Math.min(Math.max(item.y, 0), config.MAX_BOARD_SIZE);
205
+      item.y = Math.round(10 * item.y) / 10;
206
+    }
207
+    if (item.hasOwnProperty("opacity")) {
208
+      item.opacity = Math.min(Math.max(item.opacity, 0.1), 1) || 1;
209
+      if (item.opacity === 1) delete item.opacity;
210
+    }
211
+    if (item.hasOwnProperty("_children")) {
212
+      if (!Array.isArray(item._children)) item._children = [];
213
+      if (item._children.length > config.MAX_CHILDREN)
214
+        item._children.length = config.MAX_CHILDREN;
215
+      for (var i = 0; i < item._children.length; i++) {
216
+        this.validate(item._children[i]);
217
+      }
225 218
     }
226 219
   }
227
-};
228 220
 
229
-/** Load the data in the board from a file.
230
- * @param {string} name - name of the board
231
- */
232
-BoardData.load = async function loadBoard(name) {
233
-  var boardData = new BoardData(name),
234
-    data;
235
-  try {
236
-    data = await fs.promises.readFile(boardData.file);
237
-    boardData.board = JSON.parse(data);
238
-    for (id in boardData.board) boardData.validate(boardData.board[id]);
239
-    log("disk load", { board: boardData.name });
240
-  } catch (e) {
241
-    log("empty board creation", {
242
-      board: boardData.name,
243
-      // If the file doesn't exist, this is not an error
244
-      error: e.code !== "ENOENT" && e.toString(),
245
-    });
246
-    boardData.board = {};
247
-    if (data) {
248
-      // There was an error loading the board, but some data was still read
249
-      var backup = backupFileName(boardData.file);
250
-      log("Writing the corrupted file to " + backup);
251
-      try {
252
-        await fs.promises.writeFile(backup, data);
253
-      } catch (err) {
254
-        log("Error writing " + backup + ": " + err);
221
+  /** Load the data in the board from a file.
222
+   * @param {string} name - name of the board
223
+   */
224
+  static async load(name) {
225
+    var boardData = new BoardData(name),
226
+      data;
227
+    try {
228
+      data = await fs.promises.readFile(boardData.file);
229
+      boardData.board = JSON.parse(data);
230
+      for (id in boardData.board) boardData.validate(boardData.board[id]);
231
+      log("disk load", { board: boardData.name });
232
+    } catch (e) {
233
+      log("empty board creation", {
234
+        board: boardData.name,
235
+        // If the file doesn't exist, this is not an error
236
+        error: e.code !== "ENOENT" && e.toString(),
237
+      });
238
+      boardData.board = {};
239
+      if (data) {
240
+        // There was an error loading the board, but some data was still read
241
+        var backup = backupFileName(boardData.file);
242
+        log("Writing the corrupted file to " + backup);
243
+        try {
244
+          await fs.promises.writeFile(backup, data);
245
+        } catch (err) {
246
+          log("Error writing " + backup + ": " + err);
247
+        }
255 248
       }
256 249
     }
250
+    return boardData;
257 251
   }
258
-  return boardData;
259
-};
252
+}
260 253
 
261 254
 /**
262 255
  * Given a board file name, return a name to use for temporary data saving.

Loading…
Cancel
Save