How to fetch data from an API which stream real time data - javascript

I want to use this API here,
https://developer.sportradar.com/docs/read/basketball/NCAA_Mens_Basketball_v7#tournament-summary-seeded-tournaments-only
This endpoint retrieves detailed, real-time information on every game event. I am trying to implement this in node JS. How can I do this? This API redirect to different URL whenever we hit it. Is there any way to do parse data from this? It returns response like this,
{
"heartbeat":{
"interval":5000
}
}
{
"payload":{
"game":{
"id":"0db78438-9663-470f-b3ae-1f9106298e47",
"status":"inprogress",
"coverage":"full",
"scheduled":"2021-02-27T17:00:00+00:00",
"home":{
"name":"Hoosiers",
"market":"Indiana",
"id":"c3f0a8ce-af67-497f-a750-3b859376b20a",
"points":57,
"rank":0,
"bonus":true,
"remaining_timeouts":2
},
"away":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"points":73,
"rank":3,
"remaining_timeouts":1
}
},
"event":{
"id":"a2b43bd2-1b79-4823-b76c-21a09eb1adea",
"event_type":"rebound",
"sequence":1614445806980,
"clock":"18:32",
"clock_decimal":"18:32",
"updated":"2021-10-26T16:29:17Z",
"created":"2021-02-27T17:10:06Z",
"description":"Hunter Dickinson defensive rebound",
"home_points":57,
"away_points":73,
"attribution":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"team_basket":"right"
},
"location":{
"coord_x":102,
"coord_y":236,
"action_area":"backcourt"
},
"possession":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277"
},
"period":{
"id":"1f18ca8c-6a96-43f7-b68c-4d1b333e059c",
"number":1,
"sequence":1,
"type":"half"
},
"on_court":{
"home":{
"name":"Hoosiers",
"market":"Indiana",
"id":"c3f0a8ce-af67-497f-a750-3b859376b20a",
"players":[
{
"full_name":"Aljami Durham",
"jersey_number":"1",
"id":"6897db83-b25f-4c54-832a-0ff0c3cb86ff"
},
{
"full_name":"Rob Phinisee",
"jersey_number":"10",
"id":"481ffe40-392b-4a1b-89ec-0d9453495639"
},
{
"full_name":"Jerome Hunter",
"jersey_number":"21",
"id":"681d2cc6-24b9-4f38-8564-8c0b210a9535"
},
{
"full_name":"Trayce Jackson-Davis",
"jersey_number":"23",
"id":"c468bdc9-4778-496a-985e-7911dc6a1ff2"
},
{
"full_name":"Race Thompson",
"jersey_number":"25",
"id":"ed56bced-c614-4eeb-85ee-812edb594752"
}
]
},
"away":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"players":[
{
"full_name":"Hunter Dickinson",
"jersey_number":"1",
"id":"1d0c6b20-76b7-4a82-ae1d-20b78136525b"
},
{
"full_name":"Isaiah Livers",
"jersey_number":"2",
"id":"34736ed7-c86a-472c-8c1c-683002de6487"
},
{
"full_name":"Mike Smith",
"jersey_number":"12",
"id":"92f6b357-f6cb-40a5-8893-329425fff5ba"
},
{
"full_name":"Franz Wagner",
"jersey_number":"21",
"id":"ec3df621-2a9d-483c-9064-11b44d8841a9"
},
{
"full_name":"Eli Brooks",
"jersey_number":"55",
"id":"8869c334-f08c-4ed9-931c-9d9c657cb7bc"
}
]
}
},
"statistics":[
{
"type":"rebound",
"rebound_type":"defensive",
"team":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277"
},
"player":{
"full_name":"Hunter Dickinson",
"jersey_number":"1",
"id":"1d0c6b20-76b7-4a82-ae1d-20b78136525b"
}
}
]
}
},
"locale":"en",
"metadata":{
"league":"NCAAM",
"match":"sd:match:0db78438-9663-470f-b3ae-1f9106298e47",
"status":"inprogress",
"team":"sd:team:bdc2561d-f603-4fab-a262-f1d2af462277",
"players":"sd:player:6897db83-b25f-4c54-832a-0ff0c3cb86ff,sd:player:481ffe40-392b-4a1b-89ec-0d9453495639,sd:player:681d2cc6-24b9-4f38-8564-8c0b210a9535,sd:player:c468bdc9-4778-496a-985e-7911dc6a1ff2,sd:player:ed56bced-c614-4eeb-85ee-812edb594752,sd:player:1d0c6b20-76b7-4a82-ae1d-20b78136525b,sd:player:34736ed7-c86a-472c-8c1c-683002de6487,sd:player:92f6b357-f6cb-40a5-8893-329425fff5ba,sd:player:ec3df621-2a9d-483c-9064-11b44d8841a9,sd:player:8869c334-f08c-4ed9-931c-9d9c657cb7bc",
"event_type":"rebound",
"event_category":"shot",
"locale":"en",
"operation":"update",
"version":"v7"
}
}
{
"heartbeat":{
"interval":5000
}
}

you can use interval to get the data from API and then passing the data to websocket server

Use eventsource if this event is triggered by your API.
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
Otherwise websocket is much better, than setInterval.

Related

SAPUI5 JSON REST API (non-oData) mock server

How is it possible to use a mock server for JSON REST API and not for a oData service?
I would like to mock http://localhost:8080/api/v1/configs to get a JSON list of all configurations even if I have no backend connection and I am running the app in mock mode.
The following is not working, it returns furthermore the real data and not the mocked data.
mockserver.js:
sap.ui.define([
"sap/ui/core/util/MockServer",
"sap/base/util/UriParameters"
], function (MockServer, UriParameters) {
"use strict";
var oTokenRequest = {
method: "GET",
path: new RegExp("/actuator/info"),
response: function (oXhr, sNodeId) {
jQuery.sap.log.debug("Incoming request for X-CSRF Token");
oXhr.respondJSON(200, {
"X-Csrf-Token": "myFakeToken"
}, {});
}
};
var oMockServer;
return {
init: function () {
var oUriParameters = new UriParameters(window.location.href);
// configure mock server with a delay
MockServer.config({
autoRespond: true,
autoRespondAfter: oUriParameters.get("serverDelay") || 500
});
var oAllConfigurations = {
method: "GET",
path: "/configs", // or "new RegExp(".*?")" for everything after v1/?
response: function (oXhr, sUrlParams) {
oXhr.respondJSON(200, {}, JSON.stringify({
"uuid": "50df30x9-762b-341c-9881-7315l242b6c5",
"name": "Config1",
"description": "Mapping for component1",
"fileVersion": 3,
"createdAt": 1581517043000,
"updatedAt": 1589039157000
}, {
"uuid": "4f68da04-28a2-4a4e-947k-6d7be70cr03k",
"name": "MOCKSERVER-Config2",
"description": "Mapping for component2",
"fileVersion": 12,
"createdAt": 1553685823000,
"updatedAt": 1589363607000
}, {
"uuid": "6g6chg1-23a2-4a3o-332a-2a6be08ca02f",
"name": "Config3",
"description": "Mapping for component3",
"fileVersion": 1,
"createdAt": 1596119686000,
"updatedAt": 1596119686000
}));
}
};
var aRequests = [oTokenRequest];
aRequests = aRequests.concat(oAllConfigurations);
// create
this.oMockServer = new MockServer({
rootUri: "http://localhost:8080/api/v1",
requests: [oAllConfigurations]
});
// start
this.oMockServer.start();
}
};
});
data-sap-ui-oninit in mockServer.html leads to initMockServer.js
initMockServer.js:
sap.ui.define([
"../localService/mockserver"
], function (mockserver) {
"use strict";
// initialize the mock server
mockserver.init();
// initialize the embedded component on the HTML page
sap.ui.require(["sap/ui/core/ComponentSupport"]);
});
Main.controller.js:
//...
_getConfigList: function () {
var oModelConfigList = new JSONModel();
this.request = new BaseRequests();
return fetch("http://localhost:8080/api/v1/configs")
.then((response) => {
if (response.ok) {
return response.json();
} else {
MessageToast.show(response.statusText);
return null;
}
}).then(json => {
if (json) {
oModelConfigList.setData(json);
this.getView().setModel(oModelConfigList, "ConfigList");
}
});
},
//...
The UI5-Mockserver is only for the UI5 V2-Model implementation. Hence you need to build your own.
To keep it as simple as possible; i would suggest to pack everything in a delegate and use a global flag to toggle mock/real requests during runtime.
//
// your delegate
//
sap.ui.define([
"sap/ui/base/Object"
], function (BaseObject) {
"use strict";
const mockData = {
"uuid": "50df30x9-762b-341c-9881-7315l242b6c5",
"name": "Config1",
"description": "Mapping for component1",
"fileVersion": 3,
"createdAt": 1581517043000,
"updatedAt": 1589039157000
}, {
"uuid": "4f68da04-28a2-4a4e-947k-6d7be70cr03k",
"name": "MOCKSERVER-Config2",
"description": "Mapping for component2",
"fileVersion": 12,
"createdAt": 1553685823000,
"updatedAt": 1589363607000
}, {
"uuid": "6g6chg1-23a2-4a3o-332a-2a6be08ca02f",
"name": "Config3",
"description": "Mapping for component3",
"fileVersion": 1,
"createdAt": 1596119686000,
"updatedAt": 1596119686000
}
return BaseObject.extend("my.namespace.delegate.config", {
read: function(){
if(!window.MY_NAME_SPACE_MOCK){
return fetch("api/v1/configs")
.then((response) => {
if (response.ok) {
return response.json();
} else {
//MessageToast.show(response.statusText);
return null;
}
})
}else{
return new Promise((resolve, reject) => {
let wait = setTimeout(() => {
clearTimout(wait);
resolve(mockData);
}, 2000)
})
}
},
});
});
// usage
sap.ui.define([
"my/namespace/delegate/config"
], function (Config) {
onInit: function() {
this._config = new Config();
this._config.read()
.then((data)=>{
console.log("data can be mock or real depending on MY_NAME_SPACE_MOCK")})
},
})
//
// switch on/off mocking anywhere
//
window.MY_NAME_SPACE_MOCK = true;
delete window.MY_NAME_SPACE_MOCK
FYI: domain("localhost") is not part of a normal AJAX request. Once it is deployed; this will not work anymore

payment() invoked twice after express checkout button is clicked. Lightbox keep spinning

I am trying to integrate the express-checkout API with node.js and express. It's my first time using PayPal's API and I am having trouble getting the lightbox to stop spinning and allowing the user to approve and authorize the payment. When the user clicks the checkout button, the payment method is invoked twice (2 payments are created with 2 different ids with a time difference of about 2 mins) and the lightbox pops up but keeps spinning and doesn't prompt the user to do anything. I appreciate any help on this.
My client-side code:
<div id="paypal-button"></div>
<script>
paypal.Button.render({
env: 'sandbox', // Or 'sandbox',
commit: true, // Show a 'Pay Now' button
style: {
color: 'gold',
size: 'small'
},
payment: function() {
/* Make a call to the server to set up the payment */
return paypal.request.post("http://localhost:3000/paypal/create-payment")
.then(function(res) {
return res.id;
})
},
onAuthorize: function(data, actions) {
/*
* Execute the payment here
*/
return paypal.request.post("http://localhost:3000/paypal/execute-payment",
{
paymentID: data.paymentID,
payerID: data.payerID
}).then(function(res) {
// The payment is complete!
// You can now show a confirmation message to the customer
window.alert("PAYMENT COMPLETE!");
});
},
onCancel: function(data, actions) {
/*
* Buyer cancelled the payment
*/
console.log("BUYER CANCELLED!");
},
onError: function(err) {
/*
* An error occurred during the transaction
*/
console.log(err);
}
}, '#paypal-button');
</script>
My server-side code:
// CREATE PAYMENT ROUTE
app.post("/paypal/create-payment", function(req, res){
// CREATE JSON REQUEST
var create_payment_json = {
"intent": "sale",
"redirect_urls":
{
"return_url": "https://localhost:3000/success",
"cancel_url": "https://localhost:3000/cancel"
},
"payer":
{
"payment_method": "paypal"
},
"transactions": [
{
"amount":
{
"total": "",
"currency": "USD",
"details":{
"subtotal": "",
"shipping": "0.00",
"tax": "0.00",
"shipping_discount": "0.00"
}
},
"item_list":
{
"items": []
},
"description": "Test shopping cart transaction."
}]
};
// Change the "total", "subtotal", and "items" array in the json request
create_payment_json["transactions"][0]["amount"]["total"] = cart.totalPrice.toString();
create_payment_json["transactions"][0]["amount"]["details"]["subtotal"] = cart.totalPrice.toString();
// Dummy variable for less typing
var itemsArray = create_payment_json["transactions"][0]["item_list"]["items"];
// 1) Access each puppy in the cart
// 2) Create an object with the following properties:
// quantity, name, price, currency, description, and tax
// 3) push that object into itemsArray
cart["puppies"].forEach(function(puppy){
var dummy = {
"quantity" : "1",
"name" : puppy.name,
"price" : puppy.price.toString(),
"currency" : "USD",
"description" : puppy.description,
"tax" : "0"
};
itemsArray.push(dummy);
});
// Send a Create Payment request to the Payments API
paypal.payment.create(create_payment_json, function (error, payment){
if (error) {
console.log(error);
} else {
console.log(payment);
console.log("==============");
}
});
});
// EXECUTE PAYMENT ROUTE
app.post("/paypal/execute-payment", function(req, res){
var payerId = { payer_id: req.query.PayerID };
var paymentId = req.query.paymentId;
console.log("Payer ID: " + payerId);
console.log("Paymend ID: " + paymentId);
paypal.payment.execute(paymentId, payerId, function(error, payment){
if (error){
console.log(error);
} else {
if(payment.state === "approved"){
console.log(payment);
res.send("SUCCESS");
} else {
console.log("payment not successful");
}
}
});
});
The console.log(payment) in the paypal.payment.create method is run twice. That's how I know that the payment method is invoked twice. I don't know how to solve this. Any help or suggestion is appreciated!
Update: changed return res.paymentId into return res.id, but no luck.

Alternative way to fetch value from a local json file using $http

I want to load countries list from a countries json file stored locally. I have included the file in index.html as:
<!-- Including Json -->
<script src="json/countries.json"></script>
The Json file is saved in json folder with name countries.json, the file contents are as:
[
{
"country_id":"1",
"country_name":"Afghanistan"
},
{
"country_id":"2",
"country_name":"Albania"
},
{
"country_id":"3",
"country_name":"Algeria"
},
{
"country_id":"4",
"country_name":"American Samoa"
},
{
"country_id":"5",
"country_name":"Andorra"
},
{
"country_id":"6",
"country_name":"Angola"
},
{
"country_id":"7",
"country_name":"Anguilla"
},
{
"country_id":"8",
"country_name":"Antarctica"
},
{
"country_id":"9",
"country_name":"Antigua and Barbuda"
},
{
"country_id":"10",
"country_name":"Argentina"
},
{
"country_id":"11",
"country_name":"Armenia"
},
{
"country_id":"12",
"country_name":"Aruba"
},
{
"country_id":"13",
"country_name":"Australia"
},
{
"country_id":"14",
"country_name":"Austria"
},
{
"country_id":"15",
"country_name":"Azerbaijan"
},
{
"country_id":"16",
"country_name":"Bahamas"
},
{
"country_id":"17",
"country_name":"Bahrain"
},
{
"country_id":"18",
"country_name":"Bangladesh"
},
{
"country_id":"19",
"country_name":"Barbados"
},
{
"country_id":"20",
"country_name":"Belarus"
},
{
"country_id":"21",
"country_name":"Belgium"
},
{
"country_id":"22",
"country_name":"Belize"
},
{
"country_id":"23",
"country_name":"Benin"
},
{
"country_id":"24",
"country_name":"Bermuda"
}
]
To just name a few countries.
I could successfully parse the data and populate it to the UI from my controller referring the $htttp.get() service of angular as suggested by #jaime:
//Getting the base url inorder to tell app where to find countries json
var baseUrl = $location.absUrl().substring(0, $location.absUrl().indexOf('www'));
//Fetching the countries Json
return $http.get(baseUrl+'www/json/countries.json')
//On Fetching the countries lsit
.then( function(response){
$scope.countryList = response.data;
});
It works well, no doubt about it. But is there another alternative to achieve this functionality? Without using the $http.get()? I came accross angular.fromJson(), but it won't parse a file path as it requires it's argument to be a json object. Also I came across alternatives using jquery as in https://stackoverflow.com/a/12091134/1904479. is there any other alternative which doesn't require jquery, Instead uses angular or ionic code?
Actually, we can use it, by declaring it in a constants file as:
Step 1) Create a file constants.jsand add the json object into it:
var ConstantsCountries = [
{
"country_id":"1",
"country_name":"Afghanistan"
},
{
"country_id":"2",
"country_name":"Albania"
},
{
"country_id":"3",
"country_name":"Algeria"
},
{
"country_id":"4",
"country_name":"American Samoa"
},
{
"country_id":"5",
"country_name":"Andorra"
},
{
"country_id":"6",
"country_name":"Angola"
},
{
"country_id":"7",
"country_name":"Anguilla"
},
{
"country_id":"8",
"country_name":"Antarctica"
},
{
"country_id":"9",
"country_name":"Antigua and Barbuda"
},
{
"country_id":"10",
"country_name":"Argentina"
},
{
"country_id":"11",
"country_name":"Armenia"
},
{
"country_id":"12",
"country_name":"Aruba"
},
{
"country_id":"13",
"country_name":"Australia"
},
{
"country_id":"14",
"country_name":"Austria"
},
{
"country_id":"15",
"country_name":"Azerbaijan"
},
{
"country_id":"16",
"country_name":"Bahamas"
},
{
"country_id":"17",
"country_name":"Bahrain"
},
{
"country_id":"18",
"country_name":"Bangladesh"
},
{
"country_id":"19",
"country_name":"Barbados"
}
]
Step 2: Include the js file in the index.html as:
<!-----Constants Classes---->
<script src="Constants/Constants.js"></script>
Step 3: Use it in your controller as:
.controller('CountriesCtrl', function ($localStorage,$rootScope,$location,$ionicLoading,$ionicHistory,$timeout) {
$scope.countries = ConstantsCountries;
console.log(angular.toJson($scope.countries));
}))

Looping through JSON with jQuery

Sorry, I'm sure there's a duplicate of this but I'm really new to jQuery. I have the following JSON string...
{
"totalNumEntries":2,
"pageType":"CampaignPage",
"totalBudget":{
"period":{
"value":"DAILY"
},
"amount":{
"comparableValueType":"Money",
"microAmount":0
},
"deliveryMethod":null
},
"entries":[
{
"id":733413,
"name":"Interplanetary Cruise #1345659006301",
"status":null,
"servingStatus":null,
"startDate":null,
"endDate":null,
"budget":null,
"biddingStrategy":null,
"conversionOptimizerEligibility":null,
"campaignStats":{
"startDate":null,
"endDate":null,
"network":{
"value":"ALL"
},
"clicks":null,
"impressions":null,
"cost":null,
"averagePosition":null,
"averageCpc":null,
"averageCpm":null,
"ctr":null,
"conversions":null,
"viewThroughConversions":null,
"statsType":"CampaignStats"
},
"adServingOptimizationStatus":null,
"frequencyCap":{
"impressions":0,
"timeUnit":null,
"level":null
},
"settings":null,
"networkSetting":null,
"forwardCompatibilityMap":null
},
{
"id":733414,
"name":"Interplanetary Cruise banner #1345659006387",
"status":null,
"servingStatus":null,
"startDate":null,
"endDate":null,
"budget":null,
"biddingStrategy":null,
"conversionOptimizerEligibility":null,
"campaignStats":{
"startDate":null,
"endDate":null,
"network":{
"value":"ALL"
},
"clicks":null,
"impressions":null,
"cost":null,
"averagePosition":null,
"averageCpc":null,
"averageCpm":null,
"ctr":null,
"conversions":null,
"viewThroughConversions":null,
"statsType":"CampaignStats"
},
"adServingOptimizationStatus":null,
"frequencyCap":{
"impressions":0,
"timeUnit":null,
"level":null
},
"settings":null,
"networkSetting":null,
"forwardCompatibilityMap":null
}
]
}
This is returned from /google/getCampaigns in my application. I'm looping through it with the following code, but the page stays blank...
<script>
$(document).ready(function() {
$.getJSON('google/getCampaigns', function(data) {
$.each(data.entries, function(index) {
$('span').append(index.name);
});
});
});
</script>
Loading...
<span />
Can anyone see what I'm doing wrong?
Thanks,
David
The each statement should like this:
$.each(data.entries, function(index,element) {
$('span').append(element.name);
});
or another approach would be
$.each(data.entries, function(index) {
$('span').append(data.entries[index].name);
});
Hope this will fix your problem.
what is the need of passing anything else not even index this will help you for sure
$.each(data.entries, function() {
$('span').append(this.name);
});

Dojo declare - base class is not a callable constructor

I try in Dojo
var a=new DATALINK_MSTP();
but I got error base class is not a callable constructor
dojo.declare("DATALINK", null, {
_id:'',
_type:'',
_network:'',
_mac:'',
_hop_count:'',
_mqueue:'',
constructor: function(){
this._id='';
this._type='';
this._newtwork='';
this._mac='';
this._hop_count='';
this._mqueue=new MQUEUE();
},
get_id:function(){
return this._id;
},
set_id:function(id){
this._id=id;
},
get_type:function(){
return this._type;
},
set_type:function(type){
this._type=type;
},
get_network:function(){
return this._network;
},
set_network:function(network){
this._network=network;
},
get_mac:function(){
return this._mac;
},
set_mac:function(mac){
this._mac=mac;
},
get_hop_count:function(){
return this._hop_count;
},
set_hop_count:function(hop_count){
this._hop_count=hop_count;
},
get_mqueue:function(){
return this.mqueue;
},
set_mqueue:function(mqueue){
this._mqueue=mqueue;
},
generate_div:function(){
},
generate_xml:function(){
}
});
dojo.declare("DATALINK_MSTP","DATALINK", {
_mstp:'',
constructor: function(){
this._mstp=new MSTP();
},
get_mstp:function(){
return this._mstp;
},
set_mstp:function(mstp){
this._mstp=mstp;
},
generate_xml:function(){
}
});
dojo.declare("DATALINK_BIP","DATALINK", {
_bip:'',
constructor: function(/*id,type, network, mac, hop_count,mqueue,bip*/){
this._bip=new BIP();
},
get_bip:function(){
return this._bip;
},
set_bip:function(bip){
this._bip=bip;
},
generate_xml:function(){
}
});
I worked earlier with Dojo and it workd fine, but I have some arguments at constructor classes(I have tested MSTP class, it works fine). Can anybody tell me where I make mistake ?
try this :
dojo.declare("DATALINK_MSTP", DATALINK, {...});
dojo.declare("DATALINK_BIP", DATALINK, {...});

Categories

Resources