如何从main.js调用供应商库?

时间:2017-08-04 03:07:02

标签: javascript node.js

我有一个基本的电子应用程序,我正在尝试使用供应商提供的js库。他们提供的示例提供了一个静态html页面,其中包括其自定义库和示例js文件。这是html

<HTML>
<HEAD>
<TITLE> MWD Library </TITLE>
</HEAD>
<BODY>
<h2>MWD Library Example</h2>

<input id="authAndConnect" type="button" value="authenticate and connect to stream" onclick="authenticateAndConnectToStream()" /></br></br>
<input id="clickMe" type="button" value="place position" onclick="placePosition()" /></br></br>
<input id="unsubscribeMe" type="button" value="unsubscribe" onclick="unsubscribe()" />
<input id="streamError" type="button" value="reconn to stream" onclick="reconnectToStream()" />
<input id="historicalData" type="button" value="historical data for GOLD" onclick="getHistoricalData()" />
<input id="goldExpiries" type="button" value="expiries for GOLD" onclick="getCurrentGoldExpiries()" /></br></br>
<input id="userTrades" type="button" value="active&completed trades" onclick="getUserTrades()" />
</BODY>

<SCRIPT SRC="jquery.ajax.js"></SCRIPT>
<SCRIPT SRC="mwdlib.js"></SCRIPT>
<SCRIPT SRC="app.js"></SCRIPT>
</HTML>

在上面的示例中,按钮单击调用示例apps.js中的authenticateAndConnectToStream

    //DEMO
//provide API key
MWDLibrary.config("dwR4jXn9ng9U2TbaPG2TzP1FTMqWMOuSrCWSK5vRIW7N9hefYEapvkXuYfVhzmdyFypxdayfkUT07HltIs4pwT0FIqEJ6PyzUz0mIqGj1GtmAlyeuVmSC5IcjO4gz14q");

//authenticate on MarketsWorld
var getAuthTokenParams = {email:"rtmarchionne@gmail.com", password:"Pitts4318AEM"};
var authenticateAndConnectToStream = function(){

  MWDLibrary.getAuthDetails(getAuthTokenParams, function(authDetails) {
    //optional: get older data
    var marketsToSubscribeTo = ['GOLD', 'AUDNZD'];
    for (var i = 0; i < marketsToSubscribeTo.length; i++){
      MWDLibrary.getHistoricalData(marketsToSubscribeTo[i], function(response) {
        console.log(response);
      }, function(errorMessage) {
        console.log(errorMessage);
      });
    }
    //now you can connect to stream
    MWDLibrary.connect(marketsToSubscribeTo, function() {
      addMarketsListeners();
    }, function(errorMessage) {
      console.log(errorMessage);
    });
  }, function(errorMessage) {
   console.log(errorMessage);
 });
};

我想调用以MWDLibrary开头的相同方法。来自我的主要js,如MWDLibrary.config(“dwR4jXn9”)

我的main.js:

const electron = require('electron')
var path = require('path');
var countdown = require(path.resolve( __dirname, "./tradescaler.js" ) );

var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );

const app = electron.app
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain

let mainWindow

app.on('ready', _ => {
   mainWindow = new BrowserWindow({
     height: 360,
     width: 700,
     title: "TradeScaler Beta - Creative Solutions",
     //frame: false,
     alwaysOnTop: true,
     autoHideMenuBar: true,
     backgroundColor: "#FF7E47",

   })

   mainWindow.loadURL('file://' + __dirname + '/tradescaler.html')
   mainWindow
   //mainWindow.setAlwaysOnTop(true, 'screen');
   mainWindow.on('closed', _ => {
     mainWindow = null
   })
 })

ipc.on('countdown-start', _ => {
   console.log('caught it!');
   MWDLibrary.config();
   countdown(count => {
     mainWindow.webContents.send('countdown', count)
   })
})

在上面的main.js中,我收到一条错误消息,指出未定义MWDLibrary。

图书馆的结构是问题吗?我是否必须通过窗口或修改库?

这是我正在尝试使用的库:

(function(window){

    'use strict';
    function init(){
      var MWDLibrary = {};
      var transferProtocol = "https://"
      var streamTransferProtocol = "https://"
      var baseTLD = "www.marketsworld.com"
      var basePort = ""
      var streamBaseTLD = "www.marketsworld.com"
      var streamPort = ""

      var authToken = "";
      var publicId = "";
      var userLevel = "user";
      var apiKey   = "-";
      var streamUrl = "";
      var streamToken = "";
      var subscribedChannels = [];
      var streamEvents = {};
      var offersWithExpiries = [];
      var filteredExpiries = {};
      var positions = {};

      var evtSource;

      MWDLibrary.config = function(apiUserKey){
        apiKey = apiUserKey;
      }

      MWDLibrary.expiries = function(market){
        return filteredExpiries[market];
      }

      MWDLibrary.connect = function(channelsToSubscribeTo, successHandler, errorHandler){
        //console.log("Connecting...");
        if(publicId === ""){
          errorHandler("Please authenticate first.");
          return;
        }

        var dispatchUrl = streamTransferProtocol+streamBaseTLD+streamPort+'/api/dispatcher';
        getJSON(dispatchUrl, apiKey, authToken, function(data){
          var data_from_json = JSON.parse(data);
          if(data_from_json.url){
            var url = data_from_json.url+'/announce?callback=__callback&publicToken='+publicId+'&userLevel='+userLevel+'&_='+(new Date().getTime() / 1000);
              getJSON(url, apiKey, authToken, function(data) {
                var data_from_json = JSON.parse(data);
                if(data_from_json.url){
                  streamUrl = data_from_json.url.substring(0,data_from_json.url.lastIndexOf("/user"));
                  streamToken = data_from_json.url.split("token=")[1];
                  MWDLibrary.subscribe(channelsToSubscribeTo, function(subscribeResponseData) {
                    evtSource = new EventSource(streamTransferProtocol+data_from_json.url);
                    evtSource.onopen = sseOpen;
                    evtSource.onmessage = sseMessage;
                    evtSource.onerror = sseError;
                    successHandler('connected');
                    return;

                  }, function(errorMessage) {
                    errorHandler(errorMessage);
                    return;
                  });
                }
                else{
                  //console.log(data);
                  errorHandler('Something went wrong.');
                  return;
                }
              }, function(status) {
                //console.log(status);
                errorHandler(status);
                return;
              });

          }
          else{
                  //console.log(data);
                  errorHandler('Something went wrong.');
                  return;
                }
        }, function(status) {
                //console.log(status);
                errorHandler(status);
                return;
              });
      }

      MWDLibrary.subscribe = function(channelsToSubscribeTo, successHandler, errorHandler){
        //console.log("Subscribing...");
        if(publicId === ""){
          errorHandler("Please authenticate first.");
          return;
        }

        var channels = 'ALL|TEST|private.'+publicId;

        if (channelsToSubscribeTo.length > 0){
          var auxChannels = '';
          if(subscribedChannels.length > 0){
            channels = subscribedChannels[0];
            for(var j = 1; j < subscribedChannels.length; j++){
              channels = channels +'|'+subscribedChannels[j];
            }
          }
          for(var i = 0; i < channelsToSubscribeTo.length; i++)
          {
            if(subscribedChannels.indexOf(channelsToSubscribeTo[i])==-1){
              auxChannels = auxChannels+'|'+channelsToSubscribeTo[i]+'|'+channelsToSubscribeTo[i]+'.game#1';
            }
          }
          channels = channels+auxChannels;
        }
        else{
          if (subscribedChannels.length == 0)
          {
            channels = channels+'|GOLD|GOLD.game#1';
          }
          else{
            channels = subscribedChannels[0];
            for (var j = 1; j < subscribedChannels.length; j++){
              channels = channels + '|' + subscribedChannels[j];
            }
          }
        }

        var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/subscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
        //subscribe to channels
        getJSON(subscribeUrl, apiKey, authToken, function(subscribeData) {
          var subscribeData_from_json = JSON.parse(subscribeData);
          subscribedChannels = subscribeData_from_json.channels;
          //console.log(subscribedChannels);

          for (var i = 0; i < subscribedChannels.length; i++)
          {
            if (subscribedChannels[i] == 'ALL')
            {
              streamEvents[subscribedChannels[i]] = {};
              streamEvents[subscribedChannels[i]]['heartbeat'] = new CustomEvent('ALL.heartbeat', {'detail':'-'});
              streamEvents[subscribedChannels[i]]['status'] = new CustomEvent('ALL.status', {'detail':'-'});
              continue;
            }

            if (subscribedChannels[i].lastIndexOf('private') > -1)
            {
              streamEvents[subscribedChannels[i]] = {};
              streamEvents[subscribedChannels[i]]['positions'] = new CustomEvent('PRIVATE.positions', {'detail':'-'});
              streamEvents[subscribedChannels[i]]['balance'] = new CustomEvent('PRIVATE.balance', {'detail':'-'});
              continue;
            }

            if (subscribedChannels[i].lastIndexOf('game') > -1)
            {
              streamEvents[subscribedChannels[i]] = {};
              streamEvents[subscribedChannels[i]]['expiry'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.expiry', {'detail':'-'});
              streamEvents[subscribedChannels[i]]['spread'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.spread', {'detail':'-'});
              streamEvents[subscribedChannels[i]]['payout'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.payout', {'detail':'-'});
              streamEvents[subscribedChannels[i]]['offer'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.offer', {'detail':'-'});
              continue;
            }

            streamEvents[subscribedChannels[i]] = {};
            streamEvents[subscribedChannels[i]]['value'] = new CustomEvent(subscribedChannels[i]+'.value', {'detail':'-'});
          }

          successHandler(subscribeData_from_json);
        }, function(status) {
          errorHandler(status);
        });
      }

      MWDLibrary.unsubscribe = function(channelsToUnsubscribeFrom, successHandler, errorHandler){
        //console.log("Unsubscribing...");
        if(publicId === ""){
          errorHandler("Please authenticate first.");
          return;
        }

        if(channelsToUnsubscribeFrom.length == 0){
          errorHandler("Please select markets to unsubscribe from.");
          return;
        }

        var channels = channelsToUnsubscribeFrom[0]+'|'+channelsToUnsubscribeFrom[0]+'.game#1';
        for(var i = 1; i < channelsToUnsubscribeFrom.length; i++)
        {
          channels = channels+'|'+channelsToUnsubscribeFrom[i]+'|'+channelsToUnsubscribeFrom[i]+'.game#1';
        }

        var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/unsubscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);

        //subscribe to channels
        getJSON(subscribeUrl, apiKey, authToken, function(unsubscribeData) {
          var unsubscribeData_from_json = JSON.parse(unsubscribeData);
          var unsubscribedChannels = unsubscribeData_from_json.channels;
          for(var i = 0; i < unsubscribedChannels.length; i++)
          {
            var index = subscribedChannels.indexOf(unsubscribedChannels[i]);
            if(index != -1) {
              subscribedChannels.splice(index, 1);
            }
          }
          //console.log(subscribedChannels);
          successHandler(unsubscribeData_from_json);
        }, function(status) {
          errorHandler(status);
        });
      }

      MWDLibrary.getAuthDetails = function(params, successHandler, errorHandler){
        //console.log("getting auth token...");
        var url = transferProtocol+baseTLD+basePort+'/api/v2/sessions';
        postJSON(url, apiKey, authToken, params, function(data) {
          var data_from_json = JSON.parse(data);
          if (!data_from_json.error){
            authToken = data_from_json.api_session_token.token;
            publicId = data_from_json.api_session_token.user.public_id;
            successHandler(data_from_json.api_session_token);
            return;
          }
          else{
            errorHandler(data_from_json.error);
            return;
          }
        }, function(status) {
          errorHandler(status);
          return;
        });
      }

      MWDLibrary.placePosition = function(params, successHandler, errorHandler){
        //console.log("placing a position...");
        if(publicId === ""){
          errorHandler("Please authenticate first.");
          return;
        }
        var url = transferProtocol+baseTLD+basePort+'/api/v2/positions';

        if(params.market == ''){
          errorHandler('Market code is missing.');
          return;
        }

        var position = positions[params.market];
        if(!position || position.market_value <= 0){
          errorHandler('No data for this market.');
          return;
        }
        if(!params.offer_id || params.offer_id == ''){
          errorHandler('Offer id is missing.');
          return;
        }

        if(!params.resolution_at || params.resolution_at <= 0){
          errorHandler('Expiry time is missing.');
          return;
        }

        if(!params.type || params.type == ''){
          errorHandler('Position type is missing.');
          return;
        }

        if(!params.wager || params.wager <= 0){
          errorHandler('Wager is missing.');
          return;
        }

        position.offer_id = params.offer_id;
        position.resolution_at = params.resolution_at;
        position.type = params.type;
        position.wager = params.wager;

        //console.log(position);
        postJSON(url, apiKey, authToken, position, function(data) {
          var data_from_json = JSON.parse(data);
          if (!data_from_json.error){
            successHandler(data_from_json);
            return;
          }
          else{
            errorHandler(data_from_json.error);
            return;
          }
        }, function(status) {
          errorHandler(status+' - make sure all parameters are set correctly and wait 10 seconds between bets');
          return;
        });
      }

      MWDLibrary.getMarkets = function(successHandler, errorHandler){
        //console.log("getting markets list...");
        getJSON(transferProtocol+baseTLD+basePort+'/api/v2/markets.json', apiKey, authToken, function(data) {
          var data_from_json = JSON.parse(data);
          for (var i = 0; i < data_from_json.length; i++) {
            var status = "closed";
            if (data_from_json[i].market.next_open_time > data_from_json[i].market.next_close_time)
            {
              status = "open";
            }
            data_from_json[i].market.status = status;
          }
          successHandler(data_from_json);
        }, function(status) {
          errorHandler(status);
        });
      }


      var sortedOffersWithExpiries = offers.sort(compareOffersBtOrder);
      for (var i=0; i<sortedOffersWithExpiries.length;i++)
      {
        expiryValue = 0;
        expiryResult = 0;
        var expiriesCopy = sortedOffersWithExpiries[i].expiries;

        for (var index = 0; index<expiriesCopy.length;index++)
        {
          expiryValue = expiriesCopy[index]
          if (expiryValue > lastExpiry)
          {
            expiryResult = expiryValue
            break
          }
        }

        if (expiryResult != 0)
        {
          var tuple = {};
          tuple.timestamp = expiryValue/1000;
          tuple.offerId = sortedOffersWithExpiries[i].offer;
          tuple.cutout = sortedOffersWithExpiries[i].cutout;
          expiriesFinalList.push(tuple);
          lastExpiry = expiryValue
        }
      }

      return expiriesFinalList;
    }

    function compareOffersBtOrder(a,b) {
      if (a.order < b.order)
        return -1;
      if (a.order > b.order)
        return 1;
      return 0;
    }
})/*(window)-->*/;

1 个答案:

答案 0 :(得分:0)

您错过了mwdlib

末尾的.js文件扩展名

您可能需要使用完整的系统路径而不是相对的路径来要求它。

var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );