From fab42bf12e8c07ae6082e50a6b87da52ac5e6c2d Mon Sep 17 00:00:00 2001 From: Adam Dobrawy Date: Tue, 5 Oct 2021 05:22:11 +0200 Subject: [PATCH] refactor: Remove duplicate code for save content in store (#778) --- lib/stores/filesystem.js | 78 ++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 47 deletions(-) diff --git a/lib/stores/filesystem.js b/lib/stores/filesystem.js index 9c6a9a03..576da202 100644 --- a/lib/stores/filesystem.js +++ b/lib/stores/filesystem.js @@ -106,6 +106,35 @@ class FilesystemStore { await fs.writeFile(metadataPath, JSON.stringify(json, null, 2)); } + async putContent(objectPath, content) { + return new Promise((resolve, reject) => { + const writeStream = createWriteStream(objectPath); + const md5Context = crypto.createHash('md5'); + + if (Buffer.isBuffer(content)) { + writeStream.end(content); + md5Context.update(content); + resolve([content.length, md5Context.digest('hex')]); + } else { + let totalLength = 0; + pipeline( + content, + new Transform({ + transform(chunk, encoding, callback) { + md5Context.update(chunk, encoding); + totalLength += chunk.length; + callback(null, chunk); + }, + }), + writeStream, + (err) => + err + ? reject(err) + : resolve([totalLength, md5Context.digest('hex')]), + ); + } + }); + } // store implementation reset() { @@ -291,34 +320,7 @@ class FilesystemStore { ); await ensureDir(path.dirname(objectPath)); - - const [size, md5] = await new Promise((resolve, reject) => { - const writeStream = createWriteStream(objectPath); - const md5Context = crypto.createHash('md5'); - - if (Buffer.isBuffer(object.content)) { - writeStream.end(object.content); - md5Context.update(object.content); - resolve([object.content.length, md5Context.digest('hex')]); - } else { - let totalLength = 0; - pipeline( - object.content, - new Transform({ - transform(chunk, encoding, callback) { - md5Context.update(chunk, encoding); - totalLength += chunk.length; - callback(null, chunk); - }, - }), - writeStream, - (err) => - err - ? reject(err) - : resolve([totalLength, md5Context.digest('hex')]), - ); - } - }); + const [size, md5] = await this.putContent(objectPath, object.content); await this.putMetadata(object.bucket, object.key, object.metadata, md5); return { size, md5 }; } @@ -407,25 +409,7 @@ class FilesystemStore { await ensureDir(path.dirname(partPath)); - const [size, md5] = await new Promise((resolve, reject) => { - const writeStream = createWriteStream(partPath); - const md5Context = crypto.createHash('md5'); - let totalLength = 0; - - pipeline( - content, - new Transform({ - transform(chunk, encoding, callback) { - md5Context.update(chunk, encoding); - totalLength += chunk.length; - callback(null, chunk); - }, - }), - writeStream, - (err) => - err ? reject(err) : resolve([totalLength, md5Context.digest('hex')]), - ); - }); + const [size, md5] = await this.putContent(partPath, content); await fs.writeFile(`${partPath}.md5`, md5); return { size, md5 }; }