-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
283 lines (245 loc) · 7.06 KB
/
index.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import { v4 as uuidv4 } from "uuid";
/*
A card in the database looks like:
{
id: string;
name: string;
description: string;
status: 'TODO' | 'IN_PROGRESS' | 'DONE';
created: Date; // UNIX timestamp
lastUpdated: Date; // UNIX timestamp
}
*/
/**
* @enum {'TODO'|'IN_PROGRESS'|'DONE'}
*/
const CARD_STATUS = {
TODO: "TODO",
IN_PROGRESS: "IN_PROGRESS",
DONE: "DONE",
};
/**
* @typedef Card
* @type {object}
* @property {string=} name
* @property {string=} description
* @property {CARD_STATUS=} status
* @property {Date=} created
* @property {Date=} lastUpdated
*/
/**
* @returns {KanbanDB}
*/
function KanbanDB() {
// True is uuid has been loaded via import.
let ready = false;
// Unique ID for this particular instance
let dbInstanceId;
// All localStorage items will contain this prefix
let dataItemPrefix;
function createGUID() {
return uuidv4();
}
function verifyDbReady() {
if (!ready) throw new Error("Database not ready");
}
/**
*
* @param {string} strDbKey
* @returns {string} Key prefixed by unique database instance.
*/
function addPrefix(strDbKey) {
return `${dataItemPrefix}--${strDbKey}`;
}
/**
* Verify the data structure of the card is valid for usage in database.
* @param {Card} card
* @returns {boolean}
*/
function isCardValid(card) {
// Card must have a name
const isValid =
card.name &&
typeof card.name === "string" &&
card.name.length > 0 &&
// If description is provided, it must be a strength w/ a length of at least one
card.description
? typeof card.description === "string" && card.description.length > 0
: true &&
// If card status is provided, it must be one of the valid statuses
(card.status
? Object.keys(CARD_STATUS).indexOf(card.status) !== -1
: true);
return isValid;
}
/**
* @returns {Promise<Card>} A single card, if found.
*/
this.getCardById = (strId) => {
verifyDbReady();
return new Promise((resolve, reject) => {
setTimeout(() => {
const card = localStorage.getItem(addPrefix(strId));
if (!card) {
reject(new Error(`Card with ID ${strId} not found.`));
}
resolve(JSON.parse(card));
}, 100);
});
};
/**
* @param {string} id Card ID
* @param {Card} cardData Card data
* @returns {Promise<boolean>} true if succesful.
*/
this.updateCardById = (strId, cardData) => {
verifyDbReady();
return new Promise((resolve, reject) => {
setTimeout(() => {
// make sure card exists.
const card = localStorage.getItem(addPrefix(strId));
if (!card) {
reject(new Error(`Card with ID ${strId} not found.`));
}
const newCard = {
...JSON.parse(card),
...cardData,
lastUpdated: Date.now(),
};
if (isCardValid(newCard)) {
localStorage.setItem(addPrefix(strId), JSON.stringify(newCard));
resolve(true);
} else {
reject(new Error("New card data invalid."));
}
}, 100);
});
};
/**
* @param {string} id Card ID
* @returns {Promise<boolean>} true if succesful.
*/
this.deleteCardById = (strId) => {
verifyDbReady();
return new Promise((resolve, reject) => {
setTimeout(() => {
// make sure card exists.
const card = localStorage.getItem(addPrefix(strId));
if (!card) {
reject(new Error(`Card with ID ${strId} not found.`));
}
localStorage.removeItem(addPrefix(strId));
resolve(true);
}, 100);
});
};
/**
* @returns {Promise<Card[]>} An array of all cards in the database.
*/
this.getCards = () => {
verifyDbReady();
return new Promise((resolve, reject) => {
setTimeout(() => {
const results = [];
const keys = Object.keys(localStorage);
if (keys.length < 1) {
reject(new Error("No data found."));
}
const filtered = keys.filter(
(strKey) => strKey.indexOf(dataItemPrefix) > -1
);
filtered.forEach((key) => {
// we don't add prefix here because key is already fully qualified
const item = localStorage.getItem(key);
results.push(JSON.parse(item));
});
resolve(results);
}, 100);
});
};
/**
* @param {CARD_STATUS[]} arrStatusCodes An array of valid status codes.
* @returns {Promise<Card[]>} An array of all cards with specific status codes.
*/
this.getCardsByStatusCodes = (arrStatusCodes) => {
verifyDbReady();
return new Promise((resolve, reject) => {
let i;
for (i = 0; i < arrStatusCodes.length; i += 1) {
if (Object.keys(CARD_STATUS).indexOf(arrStatusCodes[i]) === -1) {
reject(new Error("Invalid status"));
}
}
setTimeout(() => {
const results = [];
this.getCards().then((arrCards) => {
arrCards.forEach((card) => {
if (arrStatusCodes.indexOf(card.status) !== -1) {
results.push(card);
}
});
resolve(results);
});
}, 100);
});
};
/**
* @param {Card} cardData Card data
* @returns {Promise<string>} A unique ID for the user to recall card again later.
*/
this.addCard = (cardData) => {
verifyDbReady();
return new Promise((resolve, reject) => {
setTimeout(() => {
// We set the unique ID.
const card = {};
card.id = createGUID();
card.name = cardData.name;
card.description = cardData.description;
card.status = cardData.status;
card.created = Date.now();
card.lastUpdated = Date.now();
if (!isCardValid(card)) {
reject(new Error("Invalid card data."));
}
const cardKey = addPrefix(card.id);
localStorage.setItem(cardKey, JSON.stringify(card));
resolve(String(card.id));
}, 100);
});
};
/**
* @param {string} previousInstanceId If you want to persist data across instantation, pass
* the instance ID from a previous instantiation. Otherwise, every time you instantiate, you
* will have a fresh database.
* @returns {Promise<KanbanDB>} A handle to the KanbanDB instance.
*/
this.connect = (previousInstanceId = null) =>
new Promise((resolve) => {
ready = true;
dbInstanceId = previousInstanceId || createGUID();
// wipe away any previous data unless it was requested
if (!previousInstanceId) {
localStorage.clear();
}
dataItemPrefix = `KanbanDB--${dbInstanceId}`;
resolve(this);
});
/**
* @returns {string} Current database instance ID, which can later
* be passed to .connect(instanceID) to keep your data alive in local
* storage.
*/
this.getInstanceId = () => dbInstanceId;
// It just nullifies instance.
this.disconnect = () =>
new Promise((resolve) => {
ready = false;
dbInstanceId = null;
dataItemPrefix = null;
resolve(true);
});
// Instance handle.
return this;
}
export default new KanbanDB();