Skip to content

Commit 5747752

Browse files
committed
add is url an image check when submitting url
1 parent 4a1e6e1 commit 5747752

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/App.js

+14-2
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,24 @@ const App = () => {
4747
setInput(e.target.value);
4848
};
4949

50-
const onImageSubmit = (e) => {
50+
const onImageSubmit = async (e) => {
5151
e.preventDefault();
5252
const sanitizedUrl = DOMPurify.sanitize(input).trim();
53-
setImageUrl(sanitizedUrl);
53+
(await isImageUrl(sanitizedUrl)) && setImageUrl(sanitizedUrl);
5454
};
5555

56+
function isImageUrl(url) {
57+
return new Promise((resolve) => {
58+
const img = new Image();
59+
img.onload = () => resolve(true);
60+
img.onerror = () => {
61+
alert('Url is not an image');
62+
resolve(false);
63+
};
64+
img.src = url;
65+
});
66+
}
67+
5668
const onRouteChange = useCallback((newRoute) => {
5769
if (newRoute === 'signout') {
5870
setIsSignedIn(false);

src/App.test.js

+9
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,15 @@ describe('App component', () => {
7979
});
8080

8181
test('shows FindFace component after submitting an image URL', async () => {
82+
global.Image = class {
83+
constructor() {
84+
setTimeout(() => {
85+
if (this.onload) this.onload();
86+
}, 0);
87+
}
88+
set src(_) {}
89+
};
90+
8291
renderApp();
8392

8493
fireEvent.click(screen.getByText(/home/i));

0 commit comments

Comments
 (0)