Last active
June 11, 2020 21:33
-
-
Save jrichardsz/499dc07e0da3f504d4a6e94aafd5a756 to your computer and use it in GitHub Desktop.
javascript http request snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://stackoverflow.com/a/30008115/3957754 | |
function makeRequest (method, url, done) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open(method, url); | |
xhr.onload = function () { | |
done(null, xhr.response); | |
}; | |
xhr.onerror = function () { | |
done(xhr.response); | |
}; | |
xhr.send(); | |
} | |
// And we'd call it as such: | |
makeRequest('GET', 'http://example.com', function (err, datums) { | |
if (err) { throw err; } | |
console.log(datums); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Config from '@/config' | |
import axios from 'axios' | |
// eslint-disable-next-line | |
const boxcast = window.boxcast | |
if (!boxcast) { | |
alert('BoxCast JavaScript library not found. Application will not function.') | |
} | |
if (!Config || !Config.accountId || !Config.channelId) { | |
alert('BoxCast application portal not configured. Please ensure you have added your config.js') | |
} | |
const API_ROOT = 'https://api.boxcast.com' | |
function parseJson (r) { | |
return r.json() | |
} | |
function objToQueryParameters( obj ) { | |
let str = '?' + Object.keys(obj).reduce(function(a, k){ | |
a.push(k + '=' + encodeURIComponent(obj[k])); | |
return a; | |
}, []).join('&'); | |
return str; | |
} | |
function makeRequest (method, url, done) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open(method, url); | |
xhr.onload = function () { | |
// Get the raw header string | |
var headers = xhr.getAllResponseHeaders(); | |
var arr = headers.trim().split(/[\r\n]+/); | |
var headerMap = {}; | |
arr.forEach(function (line) { | |
var parts = line.split(': '); | |
var header = parts.shift(); | |
var value = parts.join(': '); | |
headerMap[header] = value; | |
}); | |
done(null, xhr.response, headerMap); | |
}; | |
xhr.onerror = function () { | |
done(xhr.response); | |
}; | |
xhr.send(); | |
} | |
function makeRequest2 (method, url) { | |
return new Promise(function (resolve, reject) { | |
var xhr = new XMLHttpRequest(); | |
xhr.open(method, url); | |
xhr.onload = function () { | |
if (this.status >= 200 && this.status < 300) { | |
// Get the raw header string | |
var headers = xhr.getAllResponseHeaders(); | |
var arr = headers.trim().split(/[\r\n]+/); | |
var headerMap = {}; | |
arr.forEach(function (line) { | |
var parts = line.split(': '); | |
var header = parts.shift(); | |
var value = parts.join(': '); | |
headerMap[header] = value; | |
}); | |
resolve({ | |
status: this.status, | |
body : xhr.response, | |
headers:headerMap | |
}); | |
} else { | |
reject({ | |
status: this.status, | |
err: xhr.statusText | |
}); | |
} | |
}; | |
xhr.onerror = function () { | |
reject({ | |
status: this.status, | |
statusText: xhr.statusText | |
}); | |
}; | |
xhr.send(); | |
}); | |
} | |
class Cache { | |
_data = {} | |
set (k, v) { | |
this._data[k] = v | |
} | |
get (k) { | |
return this._data[k] | |
} | |
} | |
let cache = new Cache() | |
// Access BoxCast API with proper caching and memoization | |
export default { | |
getAccountChannelId: function () { | |
return Config.channelId | |
}, | |
getAccount: function () { | |
let k = `account:${Config.accountId}` | |
if (cache.get(k)) { return Promise.resolve(cache.get(k)) } | |
return boxcast.utils.fetch(`${API_ROOT}/accounts`) | |
.then(parseJson) | |
.then((a) => { | |
cache.set(k, a) | |
return a | |
}) | |
}, | |
getChannels: function () { | |
let k = `channels:${Config.accountId}` | |
if (cache.get(k)) { return Promise.resolve(cache.get(k)) } | |
return boxcast.utils.fetch(`${API_ROOT}/accounts/${Config.accountId}/channels`) | |
.then(parseJson) | |
.then((channels) => { | |
if (Config.channelFilter) { | |
return channels.filter(Config.channelFilter) | |
} else { | |
return channels | |
} | |
}) | |
.then((channels) => { | |
cache.set(k, channels) | |
return channels | |
}) | |
}, | |
getChannelById: function (channelId) { | |
let k = `channel:${channelId}` | |
if (cache.get(k)) { return Promise.resolve(cache.get(k)) } | |
return boxcast.utils.fetch(`${API_ROOT}/channels/${channelId}`) | |
.then(parseJson) | |
.then((a) => { | |
cache.set(k, a) | |
return a | |
}) | |
}, | |
getChannelBroadcasts1: function (channelId, args) { | |
// No caching here, keep it fresh, but do handle pagination | |
let pagination = {} | |
let qs = args ? `?${boxcast.utils.Util.qsFromObj(args)}` : '' | |
return boxcast.utils.fetch(`${API_ROOT}/channels/${channelId}/broadcasts${qs}`) | |
.then((r) => { | |
pagination = JSON.parse(r.headers.get('X-Pagination')) | |
return r | |
}) | |
.then(parseJson) | |
.then((broadcasts) => { | |
return { broadcasts, pagination } | |
}) | |
}, | |
getChannelBroadcasts2: function (channelId, args, done) { | |
// No caching here, keep it fresh, but do handle pagination | |
let qs = args ? objToQueryParameters(args) : '' | |
let pagination = {"total":6} | |
var xhr = new XMLHttpRequest(); | |
xhr.open("GET", `${API_ROOT}/channels/${channelId}/broadcasts${qs}`); | |
xhr.onload = function () { | |
// Get the raw header string | |
var headers = xhr.getAllResponseHeaders(); | |
var arr = headers.trim().split(/[\r\n]+/); | |
var headerMap = {}; | |
arr.forEach(function (line) { | |
var parts = line.split(': '); | |
var header = parts.shift(); | |
var value = parts.join(': '); | |
headerMap[header] = value; | |
}); | |
console.log(headerMap); | |
done(null, { "broadcasts":JSON.parse(xhr.response), "pagination":pagination }); | |
}; | |
xhr.onerror = function () { | |
done(xhr.response,null); | |
}; | |
xhr.send(); | |
}, | |
getChannelBroadcasts3: function (channelId, args, done) { | |
// No caching here, keep it fresh, but do handle pagination | |
let qs = args ? objToQueryParameters(args) : '' | |
makeRequest("GET", `${API_ROOT}/channels/${channelId}/broadcasts${qs}`, function(err, response, headers){ | |
let pagination = JSON.parse(headers['x-pagination']); | |
done(null, { "broadcasts":JSON.parse(response), "pagination":pagination }); | |
}) | |
}, | |
getChannelBroadcasts: function (channelId, args) { | |
// No caching here, keep it fresh, but do handle pagination | |
let qs = args ? objToQueryParameters(args) : '' | |
// makeRequest2("GET", `${API_ROOT}/channels/${channelId}/broadcasts${qs}`, function(err, response, headers){ | |
// let pagination = JSON.parse(headers['x-pagination']); | |
// done(null, { "broadcasts":JSON.parse(response), "pagination":pagination }); | |
// }) | |
// | |
return makeRequest2('GET', `${API_ROOT}/channels/${channelId}/broadcasts${qs}`) | |
.then((response) => { | |
console.log(">>>>>>>>>>>>>>>>"); | |
console.log(response); | |
let pagination = JSON.parse(response.headers['x-pagination']); | |
let broadcasts = JSON.parse(response.body); | |
// return { "broadcasts":broadcasts, "pagination":pagination }; | |
return { broadcasts, pagination }; | |
}) | |
}, | |
getChannelHighlights: function (channelId, args) { | |
// No caching here, keep it fresh, but do handle pagination | |
let pagination = {} | |
let qs = args ? `?${boxcast.utils.Util.qsFromObj(args)}` : '' | |
return boxcast.utils.fetch(`${API_ROOT}/channels/${channelId}/highlights${qs}`) | |
.then((r) => { | |
pagination = JSON.parse(r.headers.get('X-Pagination')) | |
return r | |
}) | |
.then(parseJson) | |
.then((highlights) => { | |
return { highlights, pagination } | |
}) | |
}, | |
utils: { | |
// Parse start/stop to determine current/future/recently-ended/past | |
timeframe: (broadcast) => boxcast.utils.broadcast.timeframe(broadcast), | |
// h:mm:ss formatted duration | |
formatDuration: (broadcast) => boxcast.utils.broadcast.duration(broadcast), | |
// Pretty string, e.g. 10 minutes ago | |
formatRelative: (dateString, prefix = '', suffix = '') => { | |
let str = boxcast.utils.Clock.formatRelative(new Date(dateString)) | |
if (str.indexOf('/') > -1) { | |
return str | |
} else { | |
return `${prefix} ${str} ${suffix}`.trim() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment