LoginSignup
2
2

More than 5 years have passed since last update.

仮想通貨NEMでJavaScriptによるノード接続に失敗した場合に別ノードを自動選択する。

Last updated at Posted at 2017-06-24

ブロックチェーン技術を利用してプログラムを記述する場合、ロードバランサなどの単一障害点の存在を防ぐためにノード接続のロジックをアプリケーション側に持たせる必要がでてきます。

今回は、NEMのAPIを利用する場合の記述例を挙げておきます。

select_node
var NODES = Array(
"alice2.nem.ninja:7890",
"alice3.nem.ninja:7890",
"alice4.nem.ninja:7890",
"alice5.nem.ninja:7890",
"alice6.nem.ninja:7890",
"alice7.nem.ninja:7890"
);

var getEndpoint = function(){

    var target_node =  NODES[Math.floor(Math.random() * NODES.length)];
    return ACCOUNT_TRANSFERS  = "http://" + target_node + "/account/get?address=NBZNQL2JDWTGUAW237PXV4SSXSPORY43GUSWGSB7";
}

var sendAjax = function(){
    $.ajax({url: getEndpoint() ,type: 'GET'}).then(
        function(res){parse_transfers(res)},
        function(res){
            sendAjax();
        }
    );
}

var parse_transfers = function(res){
    console.log(res);
}

sendAjax();

ポイントはノードに非同期接続を行い、失敗した場合に再帰的に接続functionを呼び出している点です。
$.ajaxの部分は簡略化すると以下のようにも書けます。

$.ajax({url: getEndpoint() ,type: 'GET'}).then((res)=>parse_transfers(res),()=>sendAjax());

それでは!

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2