Skip to content

Commit 968adfc

Browse files
committed
chore(project): adjust peerDeps
1 parent 6c99f45 commit 968adfc

File tree

3 files changed

+114
-81
lines changed

3 files changed

+114
-81
lines changed

README.md

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111

1212
---
1313

14-
| Statements | Branches | Functions | Lines |
15-
| --------------------------------------------------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------- |
14+
| Statements | Branches | Functions | Lines |
15+
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
1616
| ![Statements](https://img.shields.io/badge/statements-87.96%25-yellow.svg?style=flat&logo=jest) | ![Branches](https://img.shields.io/badge/branches-72.97%25-red.svg?style=flat&logo=jest) | ![Functions](https://img.shields.io/badge/functions-81.81%25-yellow.svg?style=flat&logo=jest) | ![Lines](https://img.shields.io/badge/lines-88.65%25-yellow.svg?style=flat&logo=jest) |
1717

1818
## Table of Contents
@@ -51,15 +51,8 @@ import React from 'react';
5151
import useDownloader from 'react-use-downloader';
5252

5353
export default function App() {
54-
const {
55-
size,
56-
elapsed,
57-
percentage,
58-
download,
59-
cancel,
60-
error,
61-
isInProgress,
62-
} = useDownloader();
54+
const { size, elapsed, percentage, download, cancel, error, isInProgress } =
55+
useDownloader();
6356

6457
const fileUrl =
6558
'https://upload.wikimedia.org/wikipedia/commons/4/4d/%D0%93%D0%BE%D0%B2%D0%B5%D1%80%D0%BB%D0%B0_%D1%96_%D0%9F%D0%B5%D1%82%D1%80%D0%BE%D1%81_%D0%B2_%D0%BF%D1%80%D0%BE%D0%BC%D1%96%D0%BD%D1%8F%D1%85_%D0%B2%D1%80%D0%B0%D0%BD%D1%96%D1%88%D0%BD%D1%8C%D0%BE%D0%B3%D0%BE_%D1%81%D0%BE%D0%BD%D1%86%D1%8F.jpg';
@@ -101,15 +94,22 @@ export default function App() {
10194
| isInProgress | boolean denoting download status | n/a |
10295

10396
```jsx
104-
const {
105-
size,
106-
elapsed,
107-
percentage,
108-
download,
109-
cancel,
110-
error,
111-
isInProgress,
112-
} = useDownloader();
97+
const { size, elapsed, percentage, download, cancel, error, isInProgress } =
98+
useDownloader();
99+
```
100+
101+
`useDownloader(options?: UseDownloaderOptions)` also accepts fetch's RequestInit options:
102+
103+
- Ex.:
104+
105+
```jsx
106+
const { download } = useDownloader({
107+
mode: 'no-cors',
108+
credentials: 'include',
109+
headers: {
110+
Authorization: 'Bearer TOKEN',
111+
},
112+
});
113113
```
114114

115115
---

src/index.ts

Lines changed: 71 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
import { useCallback, useMemo, useRef, useState } from 'react';
2-
import { DownloadFunction, IResolverProps, IUseDownloader, IWindowDownloaderEmbedded, TError } from './types';
2+
import {
3+
DownloadFunction,
4+
IResolverProps,
5+
IUseDownloader,
6+
IWindowDownloaderEmbedded,
7+
TError,
8+
UseDownloaderOptions,
9+
} from './types';
310

411
export const resolver =
512
({
@@ -8,66 +15,66 @@ export const resolver =
815
setPercentageCallback,
916
setErrorCallback,
1017
}: IResolverProps) =>
11-
(response: Response): Response => {
12-
if (!response.ok) {
13-
throw Error(`${response.status} ${response.type} ${response.statusText}`);
14-
}
18+
(response: Response): Response => {
19+
if (!response.ok) {
20+
throw Error(`${response.status} ${response.type} ${response.statusText}`);
21+
}
1522

16-
if (!response.body) {
17-
throw Error('ReadableStream not yet supported in this browser.');
18-
}
23+
if (!response.body) {
24+
throw Error('ReadableStream not yet supported in this browser.');
25+
}
1926

20-
const responseBody = response.body;
27+
const responseBody = response.body;
2128

22-
const contentEncoding = response.headers.get('content-encoding');
23-
const contentLength = response.headers.get(
24-
contentEncoding ? 'x-file-size' : 'content-length'
25-
);
29+
const contentEncoding = response.headers.get('content-encoding');
30+
const contentLength = response.headers.get(
31+
contentEncoding ? 'x-file-size' : 'content-length'
32+
);
2633

27-
const total = parseInt(contentLength || '0', 10);
34+
const total = parseInt(contentLength || '0', 10);
2835

29-
setSize(() => total);
36+
setSize(() => total);
3037

31-
let loaded = 0;
38+
let loaded = 0;
3239

33-
const stream = new ReadableStream<Uint8Array>({
34-
start(controller) {
35-
setControllerCallback(controller);
40+
const stream = new ReadableStream<Uint8Array>({
41+
start(controller) {
42+
setControllerCallback(controller);
3643

37-
const reader = responseBody.getReader();
44+
const reader = responseBody.getReader();
3845

39-
async function read(): Promise<void> {
40-
return reader
41-
.read()
42-
.then(({ done, value }) => {
43-
if (done) {
44-
return controller.close();
45-
}
46+
async function read(): Promise<void> {
47+
return reader
48+
.read()
49+
.then(({ done, value }) => {
50+
if (done) {
51+
return controller.close();
52+
}
4653

47-
loaded += value?.byteLength || 0;
54+
loaded += value?.byteLength || 0;
4855

49-
if (value) {
50-
controller.enqueue(value);
51-
}
56+
if (value) {
57+
controller.enqueue(value);
58+
}
5259

53-
setPercentageCallback({ loaded, total });
60+
setPercentageCallback({ loaded, total });
5461

55-
return read();
56-
})
57-
.catch((error: Error) => {
58-
setErrorCallback(error);
59-
reader.cancel('Cancelled');
62+
return read();
63+
})
64+
.catch((error: Error) => {
65+
setErrorCallback(error);
66+
reader.cancel('Cancelled');
6067

61-
return controller.error(error);
62-
});
63-
}
68+
return controller.error(error);
69+
});
70+
}
6471

65-
return read();
66-
},
67-
});
72+
return read();
73+
},
74+
});
6875

69-
return new Response(stream);
70-
};
76+
return new Response(stream);
77+
};
7178

7279
export const jsDownload = (
7380
data: Blob,
@@ -79,8 +86,13 @@ export const jsDownload = (
7986
type: mime || 'application/octet-stream',
8087
});
8188

82-
if (typeof (window as unknown as IWindowDownloaderEmbedded).navigator.msSaveBlob !== 'undefined') {
83-
return (window as unknown as IWindowDownloaderEmbedded).navigator.msSaveBlob(blob, filename);
89+
if (
90+
typeof (window as unknown as IWindowDownloaderEmbedded).navigator
91+
.msSaveBlob !== 'undefined'
92+
) {
93+
return (
94+
window as unknown as IWindowDownloaderEmbedded
95+
).navigator.msSaveBlob(blob, filename);
8496
}
8597

8698
const blobURL =
@@ -105,7 +117,9 @@ export const jsDownload = (
105117
}, 200);
106118
};
107119

108-
export default function useDownloader(): IUseDownloader {
120+
export default function useDownloader(
121+
options: UseDownloaderOptions = {}
122+
): IUseDownloader {
109123
const debugMode = process.env.REACT_APP_DEBUG_MODE;
110124

111125
const [elapsed, setElapsed] = useState(0);
@@ -139,9 +153,12 @@ export default function useDownloader(): IUseDownloader {
139153
});
140154
}, []);
141155

142-
const setControllerCallback = useCallback((controller: ReadableStreamController<Uint8Array> | null) => {
143-
controllerRef.current = controller;
144-
}, []);
156+
const setControllerCallback = useCallback(
157+
(controller: ReadableStreamController<Uint8Array> | null) => {
158+
controllerRef.current = controller;
159+
},
160+
[]
161+
);
145162

146163
const closeControllerCallback = useCallback(() => {
147164
if (controllerRef.current) {
@@ -183,8 +200,9 @@ export default function useDownloader(): IUseDownloader {
183200
}, timeout);
184201

185202
return fetch(downloadUrl, {
203+
...options,
186204
method: 'GET',
187-
signal: fetchController.signal
205+
signal: fetchController.signal,
188206
})
189207
.then(resolverWithProgress)
190208
.then((data) => {
@@ -221,6 +239,7 @@ export default function useDownloader(): IUseDownloader {
221239
setControllerCallback,
222240
setPercentageCallback,
223241
setErrorCallback,
242+
options,
224243
]
225244
);
226245

src/types.ts

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,21 @@
1-
import { SetStateAction } from "react";
1+
import { SetStateAction } from 'react';
22

33
export type TError = {
44
errorMessage: string;
5-
} | null
5+
} | null;
66

77
export type DownloadFunction = (
88
/** Download url
99
* @example https://upload.wikimedia.org/wikipedia/commons/4/4d/%D0%93%D0%BE%D0%B2%D0%B5%D1%80%D0%BB%D0%B0_%D1%96_%D0%9F%D0%B5%D1%82%D1%80%D0%BE%D1%81_%D0%B2_%D0%BF%D1%80%D0%BE%D0%BC%D1%96%D0%BD%D1%8F%D1%85_%D0%B2%D1%80%D0%B0%D0%BD%D1%96%D1%88%D0%BD%D1%8C%D0%BE%D0%B3%D0%BE_%D1%81%D0%BE%D0%BD%D1%86%D1%8F.jpg
10-
*/
10+
*/
1111
downloadUrl: string,
1212
/** File name
1313
* @example carpathia.jpeg
14-
*/
14+
*/
1515
filename: string,
1616
/** Optional timeout to download items */
17-
timeout?: number) => Promise<void | null>;
17+
timeout?: number
18+
) => Promise<void | null>;
1819

1920
export interface IUseDownloader {
2021
/** Size in bytes */
@@ -28,7 +29,7 @@ export interface IUseDownloader {
2829
* @example await download('https://example.com/file.zip', 'file.zip')
2930
* @example await download('https://example.com/file.zip', 'file.zip', 500) timeouts after 500ms
3031
* */
31-
download: DownloadFunction
32+
download: DownloadFunction;
3233
/** Cancel function handler */
3334
cancel: () => void;
3435
/** Error object from the request */
@@ -39,8 +40,16 @@ export interface IUseDownloader {
3940

4041
export interface IResolverProps {
4142
setSize: (value: SetStateAction<number>) => void;
42-
setControllerCallback: (controller: ReadableStreamController<Uint8Array>) => void
43-
setPercentageCallback: ({ loaded, total }: { loaded: number; total: number; }) => void;
43+
setControllerCallback: (
44+
controller: ReadableStreamController<Uint8Array>
45+
) => void;
46+
setPercentageCallback: ({
47+
loaded,
48+
total,
49+
}: {
50+
loaded: number;
51+
total: number;
52+
}) => void;
4453
setErrorCallback: (err: Error) => void;
4554
}
4655

@@ -49,5 +58,10 @@ interface CustomNavigator extends Navigator {
4958
}
5059

5160
export interface IWindowDownloaderEmbedded extends Window {
52-
navigator: CustomNavigator
61+
navigator: CustomNavigator;
5362
}
63+
64+
/** useDownloader options for fetch call
65+
* See fetch RequestInit for more details
66+
*/
67+
export type UseDownloaderOptions = RequestInit;

0 commit comments

Comments
 (0)