-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdatabase.js
66 lines (56 loc) · 1.64 KB
/
database.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 fs = require('fs');
const path = require('path');
const logger = require("./utils/logger");
const config = require("./config");
let db = {}; //主数据库
let index = {}; //索引
fs.mkdirSync(path.dirname(config.unsubscribe_db_path), { recursive: true });
try {
db = JSON.parse(fs.readFileSync(config.unsubscribe_db_path));
} catch (e) {
logger.warn(`Cannot read database: ${e}`);
}
for (let url in db) {
for (let feed_url in db[url]) {
const feed = db[url][feed_url];
index[feed.url] = url; //构建索引
}
}
function write() {
return fs.writeFile(config.unsubscribe_db_path, JSON.stringify(db), (e) => {
if (e) logger.warn(`Cannot read database: ${e}`);
});
}
function putFeedToUrl(url, feed) {
if (typeof db[url] !== 'object') { //如果没有记录这个url
db[url] = {}; //就创建
}
db[url][feed.url] = feed; //在这个URL下加入feed
index[feed.url] = url; //并加索引
write();
}
function delUrlByFeedurl(feedurl) {
const url = index[feedurl] //索引里查url
if (url) { //如果存在
const feeds = db[url]; //就读取它的feed列表
if (typeof feeds === 'object') { //如果feed列表存在
for (let furl in feeds) {
delete index[furl]; //就逐个删除索引
}
}
delete db[url]; //最后删除数据库
}
write();
}
function delUrl(url) {
delete db[url]; //删除数据库
write();
}
function getAllUrl() {
let urls = [];
for (let url in db) {
urls.push(url);
}
return urls
}
module.exports = { putFeedToUrl, delUrlByFeedurl, delUrl, getAllUrl }