Refactoring
This commit is contained in:
35
lib/db.js
35
lib/db.js
@@ -4,6 +4,9 @@ const { existsInProc } = require('./procUtils')
|
||||
|
||||
const db = require('better-sqlite3')('downloads.db')
|
||||
|
||||
/**
|
||||
* Inits the repository, the tables.
|
||||
*/
|
||||
async function init() {
|
||||
try {
|
||||
db.exec(`CREATE TABLE downloads (
|
||||
@@ -21,10 +24,23 @@ async function init() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an instance of the db.
|
||||
* @returns {BetterSqlite3.Database} Current database instance
|
||||
*/
|
||||
async function get_db() {
|
||||
return db
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert an new download to the database
|
||||
* @param {string} url the video url
|
||||
* @param {string} title the title fetched by the info process
|
||||
* @param {string} thumbnail the thumbnail url fetched by the info process
|
||||
* @param {string} size optional - the download size
|
||||
* @param {number} PID the pid of the downloader
|
||||
* @returns {Promise<string>} the download UUID
|
||||
*/
|
||||
async function insertDownload(url, title, thumbnail, size, PID) {
|
||||
const uid = uuid.v1()
|
||||
try {
|
||||
@@ -42,28 +58,43 @@ async function insertDownload(url, title, thumbnail, size, PID) {
|
||||
return uid
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve all downloads from the database
|
||||
* @returns {ArrayLike} a collection of results
|
||||
*/
|
||||
async function retrieveAll() {
|
||||
return db
|
||||
.prepare('SELECT * FROM downloads')
|
||||
.all()
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a download by its uuid
|
||||
* @param {string} uid the to-be-deleted download uuid
|
||||
*/
|
||||
async function deleteDownloadById(uid) {
|
||||
db.prepare(`DELETE FROM downloads WHERE uid=${uid}`).run()
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a download by its pid
|
||||
* @param {string} pid the to-be-deleted download pid
|
||||
*/
|
||||
async function deleteDownloadByPID(PID) {
|
||||
db.prepare(`DELETE FROM downloads WHERE process_pid=${PID}`).run()
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the downloads that aren't active anymore
|
||||
* @returns {Promise<ArrayLike>}
|
||||
*/
|
||||
async function pruneDownloads() {
|
||||
const all = await retrieveAll()
|
||||
return all.map(job => {
|
||||
if (existsInProc(job.process_pid)) {
|
||||
return job
|
||||
} else {
|
||||
deleteDownloadByPID(job.process_pid)
|
||||
}
|
||||
deleteDownloadByPID(job.process_pid)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user