2017-05-21 3 views
0

Sails.jsのNode.jsにYoutube Data APIを接続しようとしていますが、 "fs.readFile"機能に問題があります。Sails.js:コントローラからYouTubeサービスを呼び出す

サービスを起動すると、「未定義」が返されます。ここで

はYoutubeServiceのための私のコードです:

module.exports = { 

callYoutubeApi: function (req, res) { 
    // Load client secrets from a local file. 
    fs.readFile('api/services/client_secret.json', function processClientSecrets(err, content) { 
     if (err) { 
      sails.log('Error loading client secret file: ' + err); 
      return "error"; 
     } 
     // Authorize a client with the loaded credentials, then call the YouTube API. 
     sails.log('123'); 
     return YoutubeService.authorize(JSON.parse(content), YoutubeService.getChannel); 
    }); 
}, 

`/** 
* Create an OAuth2 client with the given credentials, and then execute the 
* given callback function. 
* 
* @param {Object} credentials The authorization client credentials. 
* @param {function} callback The callback to call with the authorized client. 
*/ 
authorize: function (credentials, callback) { 
    var clientSecret = credentials.installed.client_secret; 
    var clientId = credentials.installed.client_id; 
    var redirectUrl = credentials.installed.redirect_uris[0]; 
    var auth = new googleAuth(); 
    var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl); 

    // Check if we have previously stored a token. 
    fs.readFile(TOKEN_PATH, function (err, token) { 
     if (err) { 
      sails.log('tata'); 
      getNewToken(oauth2Client, callback); 
     } else { 
      sails.log('tonton'); 
      oauth2Client.credentials = JSON.parse(token); 
      callback(oauth2Client); 
     } 
    }); 
}, 

/** 
* Get and store new token after prompting for user authorization, and then 
* execute the given callback with the authorized OAuth2 client. 
* 
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for. 
* @param {getEventsCallback} callback The callback to call with the authorized 
*  client. 
*/ 
getNewToken: function (oauth2Client, callback) { 
    var authUrl = oauth2Client.generateAuthUrl({ 
     access_type: 'offline', 
     scope: SCOPES 
    }); 
    sails.log('Authorize this app by visiting this url: ', authUrl); 
    var rl = readline.createInterface({ 
     input: process.stdin, 
     output: process.stdout 
    }); 
    rl.question('Enter the code from that page here: ', function (code) { 
     rl.close(); 
     oauth2Client.getToken(code, function (err, token) { 
      if (err) { 
       sails.log('Error while trying to retrieve access token', err); 
       return; 
      } 
      sails.log('getNewToken'); 
      oauth2Client.credentials = token; 
      storeToken(token); 
      callback(oauth2Client); 
     }); 
    }); 
}, 

/** 
* Store token to disk be used in later program executions. 
* 
* @param {Object} token The token to store to disk. 
*/ 
storeToken: function (token) { 
    try { 
     fs.mkdirSync(TOKEN_DIR); 
    } catch (err) { 
     if (err.code != 'EEXIST') { 
      throw err; 
     } 
    } 
    fs.writeFile(TOKEN_PATH, JSON.stringify(token)); 
    sails.log('Token stored to ' + TOKEN_PATH); 
}, 

/** 
* Lists the names and IDs of up to 10 files. 
* 
* @param {google.auth.OAuth2} auth An authorized OAuth2 client. 
*/ 
getChannel: function (auth) { 
    var service = google.youtube('v3'); 
    service.channels.list({ 
     auth: auth, 
     part: 'snippet,contentDetails,statistics', 
     id: 'UCQznUf1SjfDqx65hX3zRDiA' 
    }, function (err, response) { 
     if (err) { 
      sails.log('The API returned an error: ' + err); 
      return; 
     } 
     var channels = response.items; 
     if (channels.length == 0) { 
      sails.log('No channel found.'); 
     } else { 
      sails.log(channels[0]); 
      return channels[0]; 
     } 
    }); 
} 
}` 

コントローラでコール:

channelData = YoutubeService.callYoutubeApi(); 
sails.log(channelData); 

エラー:

debug: undefined 
debug: 123 

私は、コールが動作し、それはないと思います"processClientSecrets"関数を読み取ることができません。

誰かが感謝の手助けをする考えがある場合は、

答えて

0

非同期サービス関数を作成しましたが、これを同期的に呼び出すことになりました。それが何を意味するのかわからない場合は、「Node.jsを使った非同期プログラミング」について教えるためにグーグルでやってください。

この場合は、あなたからあなたのヘルパーの関数のシグネチャを変更したいと思う:

callYoutubeApi: function (req, res) { 

へ:「コールバック」の

callYoutubeApi: function (cb) { 

cbスタンド、そしてそれはあなたが合格機能ですあなたの非同期コードが完了すると呼び出されます。現在、returnにリテラル値を指定して呼び出している場合は、cbへの呼び出しを返します。 Nodeの規約では、cbの最初の引数は、エラーが発生した可能性があります。nullまたはundefinedです。 2番目の引数は、非同期コードの結果です。一緒にすべてを置くあなたが得る:あなたとあなたのコントローラ内で呼び出します

callYoutubeApi: function (cb) { 
    // Load client secrets from a local file. 
    fs.readFile('api/services/client_secret.json', function processClientSecrets(err, content) { 
    if (err) { 
     // Using "return" just prevents you from accidentally continuing in this function. 
     return cb(err); 
    } 
    // Authorize a client with the loaded credentials, then call the YouTube API. 
    // This assumes that "authorize" is synchronous call that returns a value. 
    var auth = YoutubeService.authorize(JSON.parse(content), YoutubeService.getChannel); 
    return cb(undefined, auth); 
    }); 
}, 

YoutubeService.callYoutubeApi(function(err, channelData) { 
    if (err) { 
    return res.serverError(err); 
    } 
    // Now do something with channelData... 
}); 
+0

をたくさんご協力いただきありがとうございますが、私はより良いノードで同期および非同期を理解する必要があります。 } //ここchannelData ... コンソールで何かを、私は{ 場合(ERR){ リターンres.serverError(ERR)は 'YoutubeService.callYoutubeApi(機能(ERR、channelData)を使用してソリューションを試してみました。私はまだ "未定義"を持っています。 –

+0

あなたは 'YoutubeService.authorize'を正しく使用していないと思います。おそらく非同期でも、2番目の引数としてコールバックを渡すことを期待しています... – sgress454

関連する問題