Moved contents of seasoned_api up to root folder

This commit is contained in:
2022-08-19 01:03:27 +02:00
parent 0efc109992
commit 56262a45c8
134 changed files with 885 additions and 32 deletions

48
src/tmdb/cache.js Normal file
View File

@@ -0,0 +1,48 @@
const assert = require("assert");
const establishedDatabase = require("../database/database");
class Cache {
constructor(database) {
this.database = database || establishedDatabase;
this.queries = {
read:
'SELECT value, time_to_live, created_at, DATETIME("now", "localtime") as now, ' +
'DATETIME(created_at, "+" || time_to_live || " seconds") as expires ' +
"FROM cache WHERE key = ? AND now < expires",
create:
"INSERT OR REPLACE INTO cache (key, value, time_to_live) VALUES (?, ?, ?)"
};
}
/**
* Retrieve an unexpired cache entry by key.
* @param {String} key of the cache entry
* @returns {Object}
*/
get(key) {
return Promise.resolve()
.then(() => this.database.get(this.queries.read, [key]))
.then(row => {
assert(row, "Could not find cache entry with that key.");
return JSON.parse(row.value);
});
}
/**
* Insert cache entry with key and value.
* @param {String} key of the cache entry
* @param {String} value of the cache entry
* @param {Number} timeToLive the number of seconds before entry expires
* @returns {Object}
*/
set(key, value, timeToLive = 10800) {
const json = JSON.stringify(value);
return Promise.resolve()
.then(() =>
this.database.run(this.queries.create, [key, json, timeToLive])
)
.then(() => value);
}
}
module.exports = Cache;