From 5a6668e6778da7923bd7427567023b1d8b6f9373 Mon Sep 17 00:00:00 2001 From: Daniel Gasienica Date: Tue, 3 Apr 2018 21:08:43 -0400 Subject: [PATCH] Add `Attachments.createWriteForExisting` This function lets us choose where to write attachment to instead of picking random name. --- app/attachments.js | 26 +++++++++++++++++++++++++- test/app/attachments_test.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/app/attachments.js b/app/attachments.js index cec884c68..4382ca6fd 100644 --- a/app/attachments.js +++ b/app/attachments.js @@ -56,9 +56,33 @@ exports.createWriterForNew = (root) => { throw new TypeError('"arrayBuffer" must be an array buffer'); } - const buffer = Buffer.from(arrayBuffer); const name = exports.createName(); const relativePath = exports.getRelativePath(name); + return exports.createWriterForExisting(root)({ + data: arrayBuffer, + path: relativePath, + }); + }; +}; + +// createWriter :: AttachmentsPath -> +// { data: ArrayBuffer, path: RelativePath } -> +// IO (Promise RelativePath) +exports.createWriterForExisting = (root) => { + if (!isString(root)) { + throw new TypeError('"root" must be a path'); + } + + return async ({ data: arrayBuffer, path: relativePath } = {}) => { + if (!isString(relativePath)) { + throw new TypeError('"relativePath" must be a path'); + } + + if (!isArrayBuffer(arrayBuffer)) { + throw new TypeError('"arrayBuffer" must be an array buffer'); + } + + const buffer = Buffer.from(arrayBuffer); const absolutePath = path.join(root, relativePath); await fse.ensureFile(absolutePath); await fse.writeFile(absolutePath, buffer); diff --git a/test/app/attachments_test.js b/test/app/attachments_test.js index 1f1e8cc11..ce337356a 100644 --- a/test/app/attachments_test.js +++ b/test/app/attachments_test.js @@ -40,6 +40,39 @@ describe('Attachments', () => { }); }); + describe('createWriterForExisting', () => { + let tempRootDirectory = null; + before(() => { + tempRootDirectory = tmp.dirSync().name; + }); + + after(async () => { + await fse.remove(tempRootDirectory); + }); + + it('should write file to disk on given path and return path', async () => { + const input = stringToArrayBuffer('test string'); + const tempDirectory = path.join( + tempRootDirectory, + 'Attachments_createWriterForExisting' + ); + + const relativePath = Attachments.getRelativePath(Attachments.createName()); + const attachment = { + path: relativePath, + data: input, + }; + const outputPath = + await Attachments.createWriterForExisting(tempDirectory)(attachment); + const output = await fse.readFile(path.join(tempDirectory, outputPath)); + + assert.equal(outputPath, relativePath); + + const inputBuffer = Buffer.from(input); + assert.deepEqual(inputBuffer, output); + }); + }); + describe('createReader', () => { let tempRootDirectory = null; before(() => {