@aaronlcj/use-last-fm
Version:
Get data from last.fm as a React hook.
98 lines (78 loc) • 2.42 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var useSWR = _interopDefault(require('swr'));
function parseSong(body, imageSize) {
var _a, _b, _c;
if (!body) {
return {
status: 'connecting',
song: null
};
}
var lastSong = (_a = body.recenttracks.track) === null || _a === void 0 ? void 0 : _a[0];
if (!lastSong || !((_b = lastSong['@attr']) === null || _b === void 0 ? void 0 : _b.nowplaying)) {
return {
status: 'idle',
song: null
};
}
var image = lastSong.image.find(function (i) {
return i.size === imageSize;
});
return {
status: 'playing',
song: {
name: lastSong.name,
artist: lastSong.artist['#text'],
art: (_c = image === null || image === void 0 ? void 0 : image['#text']) !== null && _c !== void 0 ? _c : lastSong.image[0]['#text'],
url: lastSong.url,
album: lastSong.album['#text']
}
};
}
/**
* Use Last.fm
* @param method The search type and params used to construct the request endpoint
* @param token Your API token
* @param interval Optional, this is the internal between each request
* @param imageSize The size of the image
*/
var useLastFM = /*#__PURE__*/function () {
function useLastFM(token) {
this.token = token;
}
var _proto = useLastFM.prototype;
_proto.get = function get(method, interval, imageSize) {
if (interval === void 0) {
interval = 15 * 1000;
}
if (imageSize === void 0) {
imageSize = 'extralarge';
}
var endpoint = "//ws.audioscrobbler.com/2.0/?method=" + method.query.type + "." + method.query.node + "&" + method.query.type + "=" + method.param + "&api_key=" + this.token + "&format=json&limit=1";
var _useSWR = useSWR(endpoint, {
refreshInterval: interval
}),
_useSWR$data = _useSWR.data,
track = _useSWR$data === void 0 ? null : _useSWR$data,
error = _useSWR.error;
if (error) {
return {
status: 'error',
song: null
};
}
try {
return parseSong(track, imageSize);
} catch (e) {
return {
status: 'error',
song: null
};
}
};
return useLastFM;
}();
exports.default = useLastFM;
//# sourceMappingURL=use-last-fm.cjs.development.js.map