Skip to content

Commit

Permalink
fix(index): throw error if file param is not rtf
Browse files Browse the repository at this point in the history
  • Loading branch information
Frazer Smith committed Jun 9, 2021
1 parent 9660cce commit e3552bb
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
"typescript": "^4.1.3"
},
"dependencies": {
"file-type": "^16.5.0",
"semver": "^7.3.4",
"upath": "^2.0.1"
}
Expand Down
17 changes: 16 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const fileType = require("file-type");
const fs = require("fs");
const path = require("upath");
const semver = require("semver");
Expand Down Expand Up @@ -152,14 +153,28 @@ class UnRTF {
};

try {
// UnRTF still attempts to convert empty strings/files, so catch them here before
/**
* UnRTF will attempt to convert empty strings/files, and non-RTF files
* so catch them here
*/
if (
file === undefined ||
fs.existsSync(path.normalizeTrim(file)) === false
) {
throw new Error("File missing");
}

const results = await fileType.fromFile(path.normalizeTrim(file));
if (
results === undefined ||
results.mime === undefined ||
results.mime !== "application/rtf"
) {
throw new Error(
"File is not the correct media type, expected 'application/rtf'"
);
}

const { stderr } = await execFileAsync(
path.joinSafe(this.unrtfPath, "unrtf"),
["--version"]
Expand Down
15 changes: 15 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,21 @@ describe("Convert Function", () => {
expect(isHtml(res)).toEqual(false);
});

test("Should return an Error object if file passed not RTF format", async () => {
const unRtf = new UnRTF(testBinaryPath);
const options = {
noPictures: true,
};
const testTxtFile = `${testDirectory}test.txt`;

expect.assertions(1);
await unRtf.convert(testTxtFile, options).catch((err) => {
expect(err.message).toEqual(
"File is not the correct media type, expected 'application/rtf'"
);
});
});

test("Should return an Error object if invalid value types provided for an option are passed to function", async () => {
const unRtf = new UnRTF(testBinaryPath);
const options = {
Expand Down
1 change: 1 addition & 0 deletions test_files/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
I am a test file!

0 comments on commit e3552bb

Please sign in to comment.