在 Firebase Cloud Function 中发出 Youtube Data API 请求

Posted

技术标签:

【中文标题】在 Firebase Cloud Function 中发出 Youtube Data API 请求【英文标题】:Make a Youtube Data API request in Firebase Cloud Function 【发布时间】:2018-07-28 03:43:27 【问题描述】:

我的 Firebase Cloud Function 中有以下代码,它应该进行 youtube.search.list API 调用。

const admin = require('firebase-admin');
const functions = require('firebase-functions');
const google = require('googleapis');
const util = require('util')
const API_KEY = '<API_KEY>';

admin.initializeApp(functions.config().firebase);
const db = admin.firestore();

exports.minutely_job =
  functions.pubsub.topic('minutely-tick').onPublish((event) => 
    var urlshortener = google.urlshortener('v1');
    var youtube = google.youtube(version: 'v3', auth: API_KEY);
    var request = youtube.search.list(
        part: 'snippet',
        type: 'video',
        q: 'Helge Schneider',
        maxResults: 10
    , (err,response) => 
        var docRef = db.collection('collection').doc('document');
        console.log(util.inspect(response, showHidden: true, depth: null));
        return 0;
    );
return 0;
  );

此代码不会引发错误。日志语句

console.log(util.inspect(response, showHidden: true, depth: null));

显示响应对象,它不包含任何预期的视频 sn-ps。

info    
minutely_job
  status: 200,
  statusText: 'OK',
  headers: 
    expires: 'Sat, 17 Feb 2018 09:57:02 GMT',
     date: 'Sat, 17 Feb 2018 09:57:02 GMT',
     'cache-control': 'private, max-age=120, must-revalidate, no-transform',
     etag: '"_gJQceDMxJ8gP-8T2HLXUoURK8c/NXy4AB-_wkPIjb5PPZ6-2KGo-xg"',
     vary: 'Origin, X-Origin',
     'content-type': 'application/json; charset=UTF-8',
     'x-content-type-options': 'nosniff',
     'x-frame-options': 'SAMEORIGIN',
     'x-xss-protection': '1; mode=block',
     'content-length': '10092',
     server: 'GSE',
     'alt-svc': 'hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"',
     connection: 'close' ,
  config: 
    adapter: [Function: httpAdapter],
     transformRequest:  '0': [Function: transformRequest] ,
     transformResponse:  '0': [Function: transformResponse] ,
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers: 
       Accept: 'application/json, text/plain, */*',
        'User-Agent': 'google-api-nodejs-client/1.2.1' ,
     method: 'get',
     url: 'https://www.googleapis.com/youtube/v3/search',
     paramsSerializer: [Function],
     data: undefined,
     params: 
       part: 'snippet',
        type: 'video',
        q: 'Helge Schneider',
        maxResults: 10,
        key: '***********************'  ,
  request: 
   ClientRequest 
     domain: null,
     _events: 
       socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] ,
     _eventsCount: 6,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: true,
     upgrading: false,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _removedHeader: ,
     _contentLength: 0,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket: 
      TLSSocket 
        _tlsOptions: 
          pipe: null,
           secureContext: SecureContext  context: SecureContext , singleUse: true ,
           isServer: false,
           requestCert: true,
           rejectUnauthorized: true,
           session: undefined,
           NPNProtocols: undefined,
           ALPNProtocols: undefined,
           requestOCSP: undefined ,
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: 
          close: 
            [ [Function],
               [Function: g] listener: [Function] ,
              [Function: onClose],
              [Function: socketCloseListener] ],
           end:  [Function: g] listener: [Function: onend] ,
           finish: [Function: onSocketFinish],
           _socketEnd: [Function: onSocketEnd],
           secure: [Function],
           free: [Function: onFree],
           agentRemove: [Function: onRemove],
           drain: [Function: ondrain],
           error: [Function: socketErrorListener] ,
        _eventsCount: 9,
        connecting: false,
        _hadError: false,
        _handle: null,
        _parent: null,
        _host: 'www.googleapis.com',
        _readableState: 
         ReadableState 
           objectMode: false,
           highWaterMark: 16384,
           buffer: BufferList  head: null, tail: null, length: 0 ,
           length: 0,
           pipes: null,
           pipesCount: 0,
           flowing: true,
           ended: false,
           endEmitted: false,
           reading: true,
           sync: false,
           needReadable: true,
           emittedReadable: false,
           readableListening: false,
           resumeScheduled: false,
           defaultEncoding: 'utf8',
           ranOut: false,
           awaitDrain: 0,
           readingMore: false,
           decoder: null,
           encoding: null ,
        readable: false,
        domain: null,
        _maxListeners: undefined,
        _writableState: 
         WritableState 
           objectMode: false,
           highWaterMark: 16384,
           needDrain: false,
           ending: true,
           ended: true,
           finished: true,
           decodeStrings: false,
           defaultEncoding: 'utf8',
           length: 0,
           writing: false,
           corked: 0,
           sync: false,
           bufferProcessing: false,
           onwrite: [Function],
           writecb: null,
           writelen: 0,
           bufferedRequest: null,

不幸的是,Log-Statement 在这里被截断了。但我没有从 response.items 中得到任何信息,所以我认为响应中不包含任何视频。

【问题讨论】:

嗨。你得到什么了吗?我也面临这种问题 嗨,我最终使用了“request”模块而不是“googleapis”模块。我会回答的。 【参考方案1】:

您可以使用“请求”模块代替“googleapis”模块。

const request = require('request');
const API_KEY = '************';


var url = "https://www.googleapis.com/youtube/v3/search?part=snippet&safeSearch=strict&maxResults=5&videoSyndicated=true&videoEmbeddable=true&q=Helge&type=video&key=" + API_KEY;
request(url, function (error, response, body) 
    if (!error && response.statusCode == 200) 
        obj = JSON.parse(body);
        var items = obj.items;
    );

【讨论】:

我在 spark 模式下尝试,但它不起作用。说需要计费。有没有办法解决这个问题 您无法通过 spark 计划访问云功能中的 Youtube Data API。您需要其他定价计划之一。 不,您可以使用 Google 的所有 API,而无需切换到付费计划。那个时候有效,对我来说问题是别的。

以上是关于在 Firebase Cloud Function 中发出 Youtube Data API 请求的主要内容,如果未能解决你的问题,请参考以下文章

在 TypeScript 中为 Firebase Cloud Function 配置 mailgun

在 Firebase Cloud Function 中发出 Youtube Data API 请求

从请求中获取用户信息到 Firebase 中的 Cloud Function

Firebase:Firestore 未在 Cloud Function 的计划函数中更新数据

Firebase Cloud Function在特定时间后自动删除数据[重复]

Firebase Cloud Function 在 .get() 完成之前结束