-
Notifications
You must be signed in to change notification settings - Fork 0
/
track.ts
49 lines (44 loc) · 1.25 KB
/
track.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import axios from 'axios';
import Ajv from 'ajv';
import {throwError, RuntimeCache} from '../utils';
import {RecentTracks, recentTracksSchema} from '../schema/track';
export type Track = {
artist: string;
title: string;
};
export const index = async (): Promise<Track> => {
const track = await getLastFmTrack();
return track;
};
export const cache = new RuntimeCache();
async function getLastFmTrack() {
return await cache.get<Track>({
key: 'lastfm',
fallback: {
artist: 'unknown',
title: 'unknown',
},
callback: async () => {
const url = process.env.LASTFM_API_URL || '';
const response = await axios.get(url);
if (!isRecentTracks(response.data)) {
throwError({
errorCode: 'INVALID_SCHEMA',
errorType: 'invalid schema',
errorMessage: 'getLastFmTrack: Invalid response',
})();
}
const track = response.data.recenttracks.track[0];
const artist = track.artist['#text'];
const title = track.name;
return {artist, title};
},
ttl: 300,
});
}
const ajv = new Ajv();
const isRecentTracks = (data: unknown): data is RecentTracks => {
const schema = ajv.compile(recentTracksSchema);
const isValid = schema(data);
return isValid;
};