-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.js
105 lines (93 loc) · 2.37 KB
/
db.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* @param ssid
* @constructor
*/
function DB(ssid) {
this.spreadsheet = SpreadsheetApp.openById(ssid).getSheets()[0];
this.headers = null;
this.data = null;
}
/**
* @returns {DB}
*/
DB.prototype.select = function () {
const data = this.spreadsheet.getDataRange().getValues();
this.headers = data.shift();
this.headers.unshift('row');
this.data = data.map(function (row, i) {
row.unshift(i + 2);
return row;
});
return this;
};
/**
* @see https://developers.google.com/apps-script/reference/spreadsheet/sheet#getdatarange
* @param conditions Object
* @returns {DB}
*/
DB.prototype.findByCondition = function (conditions) {
this.select();
this.data = this.data.reduce((function (filtered, row) {
var columns = Object.keys(conditions);
for (var i = 0; i < columns.length; i++) {
var column = columns[i];
var columnIndex = this.headers.indexOf(column);
if (columnIndex === -1) {
return filtered;
}
if ((row[columnIndex]).toString() !== (conditions[column]).toString()) {
return filtered;
}
}
filtered.push(row);
return filtered;
}).bind(this), []);
return this;
};
/**
* @returns {null|Array}
*/
DB.prototype.orderBy = function (column, direction) {
const columnIndex = this.headers.indexOf(column);
if (direction === undefined) {
direction = 'ASC';
}
this.data = this.data.sort(function(a, b){
var condition = direction === 'ASC' ? a[columnIndex] > b[columnIndex] : a[columnIndex] < b[columnIndex];
return a[columnIndex] === b[columnIndex] ? 0 : +(condition) || -1;
});
return this;
};
/**
* @returns {Array}
*/
DB.prototype.all = function () {
return this.data || [];
};
/**
* @returns {null|Array}
*/
DB.prototype.one = function () {
if (this.data === null || this.data.length < 1) {
return [];
}
return this.data.shift();
};
/**
* @see https://developers.google.com/apps-script/reference/spreadsheet/sheet#appendrowrowcontents
* @param data {Array}
*/
DB.prototype.insert = function (data) {
this.spreadsheet.appendRow(data);
return this;
};
/**
* @see https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangerow-column-numrows
* @param row {Number}
* @param data {Array}
* @returns {DB}
*/
DB.prototype.update = function (row, data) {
this.spreadsheet.getRange(row, 1, 1, data.length).setValues([data]);
return this;
};