Add Attachments.createWriteForExisting

This function lets us choose where to write attachment to instead of picking
random name.
This commit is contained in:
Daniel Gasienica 2018-04-03 21:08:43 -04:00
parent efd673083d
commit 5a6668e677
2 changed files with 58 additions and 1 deletions

View file

@ -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);

View file

@ -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(() => {