Skip to content

Commit

Permalink
feat: refactor youtube fetchTitle for track model
Browse files Browse the repository at this point in the history
  • Loading branch information
Hugo Vieilledent committed Jul 13, 2018
1 parent da696c9 commit f0e46f1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 13 deletions.
19 changes: 6 additions & 13 deletions app/components/track-form/component.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import Ember from 'ember';
import config from 'radio4000/config/environment';
import youtubeUrlToId from 'radio4000/utils/youtube-url-to-id';
import {fetchTitle} from 'radio4000/utils/youtube-api';
import {task, timeout} from 'ember-concurrency';

const {Component, debug, get, set, observer} = Ember;
const {Component, get, set, observer} = Ember;

export default Component.extend({
tagName: 'form',
Expand Down Expand Up @@ -45,17 +45,10 @@ export default Component.extend({

fetchTitle: task(function * () {
yield timeout(250); // throttle
const track = get(this, 'track');
const ytid = track.get('ytid');
const url = `https://www.googleapis.com/youtube/v3/videos?id=${ytid}&key=${config.youtubeApiKey}&fields=items(id,snippet(title))&part=snippet`;
const response = yield fetch(url);
const data = yield response.json();
if (!data.items.length) {
debug('Could not find title for track');
return;
}
const title = data.items[0].snippet.title;
track.set('title', title);
const track = get(this, 'track')
const ytid = track.get('ytid')
let title = yield fetchTitle(ytid)
track.set('title', title)
}).restartable(),

submitTask: task(function * () {
Expand Down
36 changes: 36 additions & 0 deletions app/utils/youtube-api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import Ember from 'ember';
import config from 'radio4000/config/environment';
const {debug} = Ember;

const fetchYoutubeTrack = async (ytid, fields) => {
if (!ytid) {
throw Error('You need to provide a youtube video to fetchYoutubeTrack')
}
if (!fields) {
fields = `items(id,snippet,contentDetails,statistics)&part=snippet,contentDetails,statistics`;
}

let rootUrl = `https://www.googleapis.com/youtube/v3/videos?key=${config.youtubeApiKey}`
let url = rootUrl + `&id=${ytid}&fields=${fields}`
let response = await fetch(url);
let data = await response.json();
if (!data.items.length) {
debug('Could not find title for track');
return;
}
return data.items[0]
}

const fetchTitle = async function (ytid) {
let data = await fetchYoutubeTrack(ytid, 'items(id,snippet(title))&part=snippet');
return data.snippet.title
}


const fetchTrackAvailability = async function (ytid) {
// let data = await fetchYoutubeTrack(ytid, 'items(id,status)&part=status')
let data = await fetchYoutubeTrack(ytid, 'items(id,snippet(title))&part=snippet');
return Boolean(data.snippet.title)
}

export {fetchTitle, fetchTrackAvailability};

0 comments on commit f0e46f1

Please sign in to comment.