Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add durations to search results #51

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ declare namespace search {
title: string;
description: string;
thumbnails: YouTubeSearchResultThumbnails;
duration: string;
}

export interface YouTubeSearchPageResults {
Expand Down
26 changes: 22 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var querystring = require('querystring')
var axios = require('axios')
var duration = require('duration-iso-8601').convertYouTubeDuration

var allowedProperties = [
'fields',
Expand Down Expand Up @@ -34,7 +35,7 @@ var allowedProperties = [
'key'
]

module.exports = function search (term, opts, cb) {
module.exports = function search(term, opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
Expand All @@ -46,7 +47,7 @@ module.exports = function search (term, opts, cb) {
return new Promise(function (resolve, reject) {
search(term, opts, function (err, results, pageInfo) {
if (err) return reject(err)
resolve({results: results, pageInfo: pageInfo})
resolve({ results: results, pageInfo: pageInfo })
})
})
}
Expand All @@ -60,7 +61,8 @@ module.exports = function search (term, opts, cb) {
Object.keys(opts).map(function (k) {
if (allowedProperties.indexOf(k) > -1) params[k] = opts[k]
})

if (!params.key)
return cb("No key")
axios.get('https://www.googleapis.com/youtube/v3/search?' + querystring.stringify(params))
.then(function (response) {
var result = response.data
Expand Down Expand Up @@ -103,7 +105,23 @@ module.exports = function search (term, opts, cb) {
}
})

return cb(null, findings, pageInfo)
axios.get('https://www.googleapis.com/youtube/v3/videos?' + querystring.stringify({
key: params.key,
id: findings.map(f => f.id).join(','),
part: 'contentDetails'
}))
.then(function (response) {
var findings2 = findings.map(function(item) {
var detailsItem = response.data.items.find(i => i.id === item.id)
item.duration = duration(detailsItem.contentDetails.duration)
return item
})
return cb(null, findings2, pageInfo)
})
.catch(function (err) {
return cb(err)
})

})
.catch(function (err) {
return cb(err)
Expand Down
Loading