-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebtask_drawing.js
60 lines (54 loc) · 1.43 KB
/
webtask_drawing.js
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
60
// Webtask to store and update a drawing
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 = 40;
const HEIGHT = 25;
const INITIAL_DATA = [];
for (var row = 0; row < HEIGHT; row++) {
INITIAL_DATA[row] = [];
for (var column = 0; column < WIDTH; column++) {
INITIAL_DATA[row].push("#ffffff");
}
}
return INITIAL_DATA;
}