/**
Checks if a resource has been blocked by client.
@memberof module:Viki
**/
class BlockedResourceChecker {
/**
@constructor
@param {String} resource - URI of resource to check
@throws {Error} - error when resource URI is invalid format or fetch() API not supported
**/
constructor(resource) {
if (resource.match(/^https?:\/\/(.*)$/)) {
this.resource = resource;
} else {
throw new Error('BlockedResourceChecker: Please pass in valid URI for resource param');
}
if (!(fetch && Request)) {
throw new Error('BlockedResourceChecker: fetch and Request not supported on this browser');
}
}
/**
Attempts to fetch resource.
@returns {Promise} promise that will return a result object with `blocked` and `resource` values
**/
test() {
const request = new Request(this.resource, {
mode: 'no-cors',
});
return fetch(request).then(() => {
return Promise.resolve({
blocked: false,
resource: this.resource });
}).catch((e) => {
this.blocked = true;
return Promise.resolve({
error: e,
blocked: true,
resource: this.resource });
});
}
}
module.exports = BlockedResourceChecker;