Node學習筆記 《EventProxy》

問題描述:

今天調用百度接口,獲取token時,判斷如果過期,就自動獲取,結果token過期的代碼可以運行,但是沒過期的代碼就是不執行
(代碼見末尾)

原因分析:

糾結了好久,發現是時序問題,ep.all()函數必須在ep.emit()函數的前面,不然emit就找不到不到接收它的主體。。

解決辦法:

將ep.all()放到ep.emit()的前面

結語:

仔細讀文檔的重要性:all方法將handler註冊到事件組合上。當註冊的多個事件都觸發後,將會調用handler執行,每個事件傳遞的數據,將會依照事件名順序,傳入handler作爲參數。
文檔地址:https://www.npmjs.com/package/eventproxy

代碼

// ==================================== Baidu Unit API ===============================================
router.route('/baidu-unit-api')
    .post((req, res, next)=>{
        // token獲取
        var tokenJsonStr = fs.readFileSync('./config/baiduToken.txt')
        var tokenJsonObj = JSON.parse(tokenJsonStr)
        var expires = tokenJsonObj.expires
        var token = tokenJsonObj.token
        var timeStamp = Date.now()
        console.log(' expires:' + expires + ', currentTimeStamp:' + timeStamp)
        // 輸入文本(對話的問題)
        // 放在ep.emit()前面
        ep.all('setToken', (token)=>{
            var text = req.body.text
            const logId = Date.now()
            const options = {
                url: 'https://aip.baidubce.com/rpc/2.0/unit/bot/chat?access_token=' + token,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8'
                },
                // body 只接受 string or Buffer,且header中類型爲 json
                body:JSON.stringify({
                    version: '2.0',
                    bot_id: '68010',
                    log_id: logId,
                    request:{
                        'user_id': 'UNIT_DEV_V11J',
                        'query_info':{
                            'asr_candidates': [],
                            'type': 'TEXT',
                            'source': 'KEYBOARD'
                        },
                        'query': text,
                        'bernard_level': 1
                    },
                    bot_session:''
                })
            }
            function callback(error, response, body) {
                if (!error && response.statusCode == 200) {
                const info = JSON.parse(body);
                console.log(body)
                if(info.error_msg){
                    res.send(new Error(info.error_msg))
                }else{
                    console.log('=== result: ', info.result.response.action_list[0].say)
                    res.send(new Success(info))  
                }
                }else{
                    console.log('=== response', response)
                    console.log('=== body', body)
                    console.log('=== error: ', error)
                }
            }
            request(options, callback);    
        })
        if(expires < timeStamp){
            // 調用api獲取token 並寫入文件保存
            getBaiduToken()
            ep.all('getBaiduToken', (jsonBody)=>{
                // 寫入文件
                token = jsonBody.access_token
                // baiduUnitAccessToken = jsonBody.access_token
                var timestamp = Date.now()
                var expires_in = jsonBody.expires_in * 1000 // s -> ms
                var configJson = {'token': jsonBody.access_token, 'expires': timestamp + expires_in }
                fs.writeFileSync('./config/baiduToken.txt', JSON.stringify(configJson))
                // 放在ep.all 後面
                ep.emit('setToken', token)
            })
        }else{
	        // 放在ep.all 後面
            ep.emit('setToken', token)
        }
    })
    
function getBaiduToken(){
    const options = {
        url: 'https://aip.baidubce.com/oauth/2.0/token',
        method: 'POST',
        form:{
            grant_type: 'client_credentials',
            client_id: baiduUnitApiKey,
            client_secret: baiduUnitSecretKey
        }
    }
	function callback(error, response, body) {
	    if (!error && response.statusCode == 200) {
	      const jsonBody = JSON.parse(body);
	      console.log('=== result: ', body)
	    ep.emit('getBaiduToken', jsonBody)
	    }
	  }
	request(options, callback);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章