Add Attachments.createWriteForExisting
This function lets us choose where to write attachment to instead of picking random name.
This commit is contained in:
parent
efd673083d
commit
5a6668e677
2 changed files with 58 additions and 1 deletions
|
@ -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);
|
||||
|
|
|
@ -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(() => {
|
||||
|
|
Loading…
Reference in a new issue