refactored storage, style tweaks

This commit is contained in:
Danny Coates
2020-07-25 11:22:57 -07:00
parent 8fb770a4ea
commit 55df061567
8 changed files with 42 additions and 30 deletions

View File

@@ -7,9 +7,7 @@ module.exports = async function(req, res) {
const id = req.params.id;
try {
const meta = req.meta;
if (meta.dead || meta.flagged) {
return res.sendStatus(404);
}
const contentLength = await storage.length(id);
const fileStream = await storage.get(id);
let cancelled = false;
@@ -18,6 +16,10 @@ module.exports = async function(req, res) {
fileStream.destroy();
});
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Length': contentLength
});
fileStream.pipe(res).on('finish', async () => {
if (cancelled) {
return;

View File

@@ -32,27 +32,31 @@ class DB {
return Math.ceil(result) * 1000;
}
async getPrefixedId(id) {
async getPrefixedInfo(id) {
const [prefix, dead, flagged] = await this.redis.hmgetAsync(
id,
'prefix',
'dead',
'flagged'
);
if (dead || flagged) {
throw new Error('id not available');
}
return `${prefix}-${id}`;
return {
filePath: `${prefix}-${id}`,
flagged,
dead
};
}
async length(id) {
const filePath = await this.getPrefixedId(id);
const { filePath } = await this.getPrefixedInfo(id);
return this.storage.length(filePath);
}
async get(id) {
const filePath = await this.getPrefixedId(id);
return this.storage.getStream(filePath);
const info = await this.getPrefixedInfo(id);
if (info.dead || info.flagged) {
throw new Error(info.flagged ? 'flagged' : 'dead');
}
return this.storage.getStream(info.filePath);
}
async set(id, file, meta, expireSeconds = config.default_expire_seconds) {
@@ -75,18 +79,19 @@ class DB {
this.redis.hincrby(id, key, increment);
}
kill(id) {
async kill(id) {
const { filePath } = await this.getPrefixedInfo(id);
this.storage.del(filePath);
this.redis.hset(id, 'dead', 1);
}
async flag(id, key) {
// this.redis.persist(id);
await this.kill(id);
this.redis.hmset(id, { flagged: 1, key });
this.redis.sadd('flagged', id);
}
async del(id) {
const filePath = await this.getPrefixedId(id);
const { filePath } = await this.getPrefixedInfo(id);
this.storage.del(filePath);
this.redis.del(id);
}