UNPKG

2.25 kBJavaScriptView Raw
1/**
2 * Is.js
3 *
4 * Object type checks.
5 */
6
7const NAME = Symbol.toStringTag;
8
9/**
10 * Check if `obj` is a URLSearchParams object
11 * ref: https://github.com/node-fetch/node-fetch/issues/296#issuecomment-307598143
12 * @param {*} object - Object to check for
13 * @return {boolean}
14 */
15export const isURLSearchParameters = object => {
16 return (
17 typeof object === 'object' &&
18 typeof object.append === 'function' &&
19 typeof object.delete === 'function' &&
20 typeof object.get === 'function' &&
21 typeof object.getAll === 'function' &&
22 typeof object.has === 'function' &&
23 typeof object.set === 'function' &&
24 typeof object.sort === 'function' &&
25 object[NAME] === 'URLSearchParams'
26 );
27};
28
29/**
30 * Check if `object` is a W3C `Blob` object (which `File` inherits from)
31 * @param {*} object - Object to check for
32 * @return {boolean}
33 */
34export const isBlob = object => {
35 return (
36 object &&
37 typeof object === 'object' &&
38 typeof object.arrayBuffer === 'function' &&
39 typeof object.type === 'string' &&
40 typeof object.stream === 'function' &&
41 typeof object.constructor === 'function' &&
42 /^(Blob|File)$/.test(object[NAME])
43 );
44};
45
46/**
47 * Check if `obj` is an instance of AbortSignal.
48 * @param {*} object - Object to check for
49 * @return {boolean}
50 */
51export const isAbortSignal = object => {
52 return (
53 typeof object === 'object' && (
54 object[NAME] === 'AbortSignal' ||
55 object[NAME] === 'EventTarget'
56 )
57 );
58};
59
60/**
61 * isDomainOrSubdomain reports whether sub is a subdomain (or exact match) of
62 * the parent domain.
63 *
64 * Both domains must already be in canonical form.
65 * @param {string|URL} original
66 * @param {string|URL} destination
67 */
68export const isDomainOrSubdomain = (destination, original) => {
69 const orig = new URL(original).hostname;
70 const dest = new URL(destination).hostname;
71
72 return orig === dest || orig.endsWith(`.${dest}`);
73};
74
75/**
76 * isSameProtocol reports whether the two provided URLs use the same protocol.
77 *
78 * Both domains must already be in canonical form.
79 * @param {string|URL} original
80 * @param {string|URL} destination
81 */
82export const isSameProtocol = (destination, original) => {
83 const orig = new URL(original).protocol;
84 const dest = new URL(destination).protocol;
85
86 return orig === dest;
87};