-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebtask_drawing.js
More file actions
59 lines (53 loc) · 1.39 KB
/
Copy pathwebtask_drawing.js
File metadata and controls
59 lines (53 loc) · 1.39 KB
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
module.exports = async function(context, cb) {
try {
const drawingObject = await getDrawing(context.storage);
// if GET, return object
if (!context.body) {
cb(null, drawingObject);
return;
}
// POST to update object
const color = context.body.color;
const columnIndex = context.body.columnIndex;
const rowIndex = context.body.rowIndex;
if (typeof color !== 'undefined') {
drawingObject.drawing[rowIndex][columnIndex] = color;
await setDrawing(context.storage, drawingObject);
}
cb(null, drawingObject);
} catch (e) {
cb(e);
}
};
async function getDrawing(storage) {
return new Promise(resolve => {
storage.get(function(error, data) {
if (data && data.drawing) {
resolve(data);
} else {
const emptyDrawing = { drawing: createInitialDrawing() };
resolve(emptyDrawing);
}
});
});
}
async function setDrawing(storage, drawing) {
return new Promise((resolve, reject) => {
storage.set(drawing, { force: 1 }, function(error) {
if (error) reject();
resolve();
});
});
}
function createInitialDrawing() {
const WIDTH = 60;
const HEIGHT = 30;
const INITIAL_DATA = [];
for (var row = 0; row < HEIGHT; row++) {
INITIAL_DATA[row] = [];
for (var column = 0; column < WIDTH; column++) {
INITIAL_DATA[row].push('#fff');
}
}
return INITIAL_DATA;
}