1- import { getConfig } from '../config' ;
2- import { Command } from '../types' ;
31import fetch from 'node-fetch' ;
42
3+ import { getConfig } from '../config' ;
4+ import type { Command } from '../types' ;
5+
6+ const isErrorResponse = ( response : YoutubeResponse ) : response is YoutubeResponseError =>
7+ 'error' in response ;
8+
59const youtube : Command = {
610 name : 'youtube' ,
711 description : 'Wyszukuje video z youtube' ,
@@ -12,39 +16,53 @@ const youtube: Command = {
1216 const result = await fetch (
1317 `https://www.googleapis.com/youtube/v3/search?part=id&type=video&key=${ YOUTUBE_API_KEY } &q=${ query } ` ,
1418 ) ;
15- const data = ( await result . json ( ) ) as YoutubeResponse ;
19+ const response = ( await result . json ( ) ) as YoutubeResponse ;
1620
17- if ( ! data . items . length ) {
21+ if ( isErrorResponse ( response ) ) {
22+ return msg . channel . send ( `Uh, integracja z API YT nie zadziałała 😭` ) ;
23+ }
24+
25+ if ( ! response . items . length ) {
1826 return msg . channel . send ( `Niestety nic nie znalazłam 😭` ) ;
1927 }
2028
21- const { videoId } = data . items [ 0 ] . id ;
29+ const [
30+ {
31+ id : { videoId } ,
32+ } ,
33+ ] = response . items ;
2234 return msg . channel . send ( `https://www.youtube.com/watch?v=${ videoId } ` ) ;
2335 } ,
2436} ;
2537
2638export default youtube ;
2739
28- interface YoutubeResponse {
29- kind : string ;
30- etag : string ;
31- nextPageToken : string ;
32- regionCode : string ;
33- pageInfo : PageInfo ;
34- items : YoutubeItem [ ] ;
40+ interface YoutubeResponseError {
41+ readonly error : unknown ;
42+ }
43+
44+ interface YoutubeResponseSuccess {
45+ readonly kind : string ;
46+ readonly etag : string ;
47+ readonly nextPageToken : string ;
48+ readonly regionCode : string ;
49+ readonly pageInfo : PageInfo ;
50+ readonly items : ReadonlyArray < YoutubeItem > ;
3551}
3652
3753interface PageInfo {
38- totalResults : number ;
39- resultsPerPage : number ;
54+ readonly totalResults : number ;
55+ readonly resultsPerPage : number ;
4056}
4157
4258interface YoutubeItem {
43- kind : string ;
44- etag : string ;
45- id : YoutubeItemId ;
59+ readonly kind : string ;
60+ readonly etag : string ;
61+ readonly id : YoutubeItemId ;
4662}
4763interface YoutubeItemId {
48- kind : string ;
49- videoId : string ;
64+ readonly kind : string ;
65+ readonly videoId : string ;
5066}
67+
68+ type YoutubeResponse = YoutubeResponseSuccess | YoutubeResponseError ;
0 commit comments