-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
118 lines (110 loc) · 3.4 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
106
107
108
109
110
111
112
113
114
115
116
117
118
const sqlite3 = require('sqlite3').verbose();
const tables = {
videos: `CREATE TABLE videos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
youtubeId TEXT,
title TEXT NOT NULL,
description TEXT,
uploadDate INTEGER,
user_id INTEGER)`,
users: `CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
)`,
sessions: `CREATE TABLE sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
active BOOLEAN NOT NULL DEFAULT 1
)`
};
const initData = {
videos: {
sql: 'INSERT INTO videos (id, user_id, youtubeId, title, description, uploadDate) VALUES (?, ?, ?, ?, ?, ?)',
data: [{
id: 1,
user_id: 1,
youtubeId: 'dQw4w9WgXcQ',
title: 'First video!!',
description: 'abcd!! this is the first video in the platform!! gonna be rich',
uploadDate: 1,
}, {
id: 2,
user_id: 2,
youtubeId: 'dQw4w9WgXcQ',
title: 'funny video please watch!',
description: 'haha funny :))))) please rate and subscribe',
uploadDate: 1
}, {
id: 3,
user_id: 1,
youtubeId: 'CnUJUMpq48E',
title: 'DJ IBUSAL - PILALLA',
description: 'kaik on pilalla',
uploadDate: 1,
}, {
id: 4,
user_id: 2,
youtubeId: 'LDU_Txk06tM',
title: 'crab rave',
description: 'haha',
uploadDate: 1,
}, {
id: 5,
user_id: 1,
youtubeId: 'CnUJUMpq48E',
title: 'please delete me',
description: 'delete',
uploadDate: 1609185734197,
}]
},
users: {
sql: 'INSERT INTO users (id, username, password) VALUES (?, ?, ?)',
data: [{
id: 1,
username: 'admin',
password: 'admin',
}, {
id: 2,
username: 'user123',
password: 'PaSSworDD!!',
}],
},
sessions: {
sql: 'INSERT INTO sessions (id, user_id) VALUES (?, ?)',
data: [{
id: 1,
user_id: 1,
}]
}
}
const db = new sqlite3.Database('db.dat', err => {
if (err) {
console.log(err);
throw err;
} else {
console.log('Connected to database');
// Create tables
Object.keys(tables).forEach(table => {
let tableSql = tables[table];
let exists = false;
db.run(tableSql, err => {
if (!err) {
// Table didn't exist before
console.log(`Created database table ${table}`);
if (initData[table]) {
console.log(`Populating table ${table} with initial data (${initData[table]['data'].length} rows)`);
initData[table]['data'].forEach(row => {
let rowData = Object.keys(row).map(key => row[key]);
db.run(initData[table]['sql'], rowData, (err) => {
if (err)
console.log(err);
});
});
}
}
});
});
}
})
module.exports = db;