-
Notifications
You must be signed in to change notification settings - Fork 0
/
urls.js
66 lines (56 loc) · 1.6 KB
/
urls.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
const fetch = require("node-fetch");
const fs = require("fs");
const writeToFile = (filename, obj) => {
fs.writeFile(filename, JSON.stringify(obj), function (err) {
if (err) {
return console.log(err);
}
});
};
const updateFile = (fileName, arr) => {
if (arr != getFileData(fileName)) writeToFile(fileName, arr);
};
const getFileData = fileName => {
let array, file;
try {
file = fs.readFileSync(fileName);
array = JSON.parse(file.toString());
} catch (error) {
// console.log(error);
console.log("creating file");
writeToFile(fileName, []);
array = [];
}
return array;
};
// let getUrls = () => {
// };
let removeSlug = (fileName, slug) => {
let array = getFileData(fileName);
let index = array.reduce((a, b, i) => (b.slug == slug ? i : a), -1);
index != -1 ? array.splice(index, 1) : {};
updateFile(fileName, array);
};
let getUrl = (fileName, slug) => {
let array = getFileData(fileName);
return array.reduce((a, b) => {
if (b.slug == slug) {
return b.url;
} else return a;
}, undefined);
};
let incrementCount = (fileName, slug) => {
let array = getFileData(fileName);
let index = array.reduce((a, b, i) => (b.slug == slug ? i : a), -1);
if (array[index].count > 0) array[index].count++;
else array[index].count = 1;
updateFile(fileName, array);
};
let createUrl = (fileName, slug, url) => {
let array = getFileData(fileName);
const newUrl = { slug, url, count: 0 };
array.push(newUrl);
updateFile(fileName, array);
return array;
};
module.exports = { writeToFile, getFileData, removeSlug, getUrl, incrementCount, createUrl };