UNPKG

@aaronlcj/use-last-fm

Version:

Get data from last.fm as a React hook.

92 lines (75 loc) 2.19 kB
import useSWR from '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; }(); export default useLastFM; //# sourceMappingURL=use-last-fm.esm.js.map