Simplifying JS query from JSON API - javascript

I'm trying to display some data from a API, using similar to the below example.
I need to feed in data such as a Video ID from a CMS, which will then retrieve additional data from the API about the video.
The below example works, but I'm not sure I've written it in the best way - and I would like to be able to set a variable using a Video ID from the CMS's front end template string. Below I am having to repeat the Video ID in order to get it to work - and I'm struggling to simplify this.
Any help appreciated!
async function getSomething() {
let request = {
item: {
name: "example",
colour: "red"
},
video: ["12345"]
};
let url = new URL("https://example.com");
url.searchParams.append('data', JSON.stringify(request));
let response = await fetch(url);
let data = await response.json();
console.log(data.video);
return data;
}
getSomething().then(data =>
document.querySelector('[data-video-id]').innerHTML = data.video.12345.label
);

Related

How to make an element contenteditable and send the new string to Node/Express-server

So I have built an REST API with working endpoints GET, POST, PUT and DELETE on an Express server and currently working on the clientside. The Express server is reading and writing to a JSON-file. So on the clientside I've done a HTML and a scriptfile, I've managed to make a GET-request and render what's in the JSON-file so far on the HTML. Also I've managed to make a inputform on the HTML and make a POST-request that makes a new object with all keys/values I would like the object to have. So my thought was that to make a PUT-request and update a certain object. Is it possible to use the HTML attribute contenteditable? At the part where I'm rendering everything from the script-file I'm in a for of loop and also making a addEventListener where I'd like to send the NEW information from the contenteditable element to the async/await-function that is making the PUT-request. But at all tries I'm only able to see the old information.
async function printCharacters(){
const get = await fetch ('http://localhost:3000/api')
const characters = await get.json()
for(const character of characters){
const characterContainers = document.createElement("div");
main.appendChild(characterContainers);
characterContainers.className = "characterContainer";
const characterName = document.createElement("p");
characterName.setAttribute("contenteditable", "true");
characterName.innerHTML = character.characterName;
characterContainers.appendChild(characterName);
const updateButton = document.createElement("button");
updateButton.className = "updateButton";
updateButton.innerText = "Update";
characterContainers.appendChild(updateButton);
updateButton.addEventListener("click", () => {
updateCharacter(characterName.innerHTML);
});
}
}
async function updateCharacter(data){
const response = await fetch (`http://localhost:3000/api/update/${data.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"characterName": data.characterName
})
})
return response.json();
};
I've tried making outside a function and then it's possible to console.log and catch the new information.
updateButton.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const changedData = {
id: character.id,
characterName: characterName.innerHTML,
class: characterClass.innerHTML,
weapon: characterWeapon.innerHTML,
description: characterDescription.innerHTML
};
updateCharacter(changedData);
This was the working solution. I've tried before to get innerHTML both inside and outside the eventListener, but to get the updated information inside the element it has to be inside the eventListener and also the addition of preventDefault and stopPropagation.

I have embedded visuals from a power bi report, is it possible to fetch the data inside these?

I have these visuals: that I want to fetch only the title "Førstehjelp" and the value "50" from, without the frame around etc. Is this possible with Javascript or do I have to edit the power bi report to make it look the way I want?
You can use visual.exportData to export data from a report visual.
Follow the below steps:
Get the Visual name using the getVisuals() API.
try {
// Retrieve the page collection.
const pages = await report.getPages();
// Retrieve the active page.
let activePage = pages.filter(function (page) {
return page.isActive;
})[0];
const visuals = await page.getVisuals();
console.log(
visuals.map(function (visual) {
return {
name: visual.name,
type: visual.type,
title: visual.title,
layout: visual.layout
};
})); catch (errors) {
console.log(errors); }
After you the get the Visual name, use the exportData API to export the data.
// Retrieve the target visual.
let visual = visuals.filter(function (visual) {
return visual.name === "VisualName";
})[0];
const result = await visual.exportData(models.ExportDataType.Summarized);
console.log(result.data); }
Reference:
https://learn.microsoft.com/javascript/api/overview/powerbi/export-data

Cant work out out fetch api of met office to html page

Been tasked with displaying details from the met office data point api using javascript onto a html page and have only a brief knowledge of using the fetch api function.The met office uses users keys for their data point that needs inserted into the url in order to access the data. Im currently using the url that displays location information and would like to start with displaying the longitude and lattidide.
Ive wrote a html page and used an example I found of using fetch online but still no luck of displaying an data.
async function getLocations() {
let url = 'http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/json/sitelist?key=231f9773-2c4f-4afd-beee-6878c1c63f0a';
try {
let res = await fetch(url);
return await res.json();
} catch (error) {
console.log(error);
}
}
async function renderLocations() {
let locations = await getLocations();
let html = '';
locations.forEach(Location => {
let htmlSegment = `<div class="Location">
<h2>${Location.longitude} ${Location.latitude}</h2>
</div>`;
html += htmlSegment;
});
let container = document.querySelector('.container');
container.innerHTML = html;
}
renderLocations();
<div class="container"></div>
By trying out the API endpoint by myself and logging out the result of getLocations(), I see that the structure of the Object looks like:
{
Locations: {
Location: [
...data
]
}
}
So to fix your code, change from
locations.forEach(Location => {
to
locations.Locations.Location.forEach(Location => {

How to setup Appinsights with azure search javascript sdk

From the Azure Search documentation I know that we have to get some search information to setup appinsights telemetry.
The problem is: How do I get SearchID information from the #azure/search-documents SearchDocumentResult?
Using the #azure/search-documents module, you can set up your client and add custom headers to operations like so:
const { SearchClient, AzureKeyCredential } = require("#azure/search-documents");
const indexName = "nycjobs";
const apiKey = "252044BE3886FE4A8E3BAA4F595114BB";
const client = new SearchClient(
`https://azs-playground.search.windows.net/`,
indexName,
new AzureKeyCredential(apiKey)
);
async function main() {
var searchId = '';
const searchResults = await client.search('Microsoft', {
top: 3,
requestOptions: {
customHeaders: {
'Access-Control-Expose-Headers': 'x-ms-azs-searchid',
'x-ms-azs-return-searchid': 'true'
},
shouldDeserialize: (response) => {
searchId = response.headers.get('x-ms-azs-searchid');
return true;
}
}
});
console.log(`Search ID: ${searchId}\n`);
for await (const result of searchResults.results) {
console.log(`${result.document.business_title}\n${result.document.job_description}\n`);
}
}
It seems that currently the only way to get them out is the shouldDeserialize callback as shown in the example since it gives you the raw response including the headers before deserializing when the headers are stripped from some objects, such as those paged response objects returned by search.
I'm assuming that you care more about search query telemetry and not indexer telemetry, but please correct me if I'm wrong. Is this documentation page helpful? https://learn.microsoft.com/azure/search/search-traffic-analytics
From that page, here is how you set the searchId:
request.setRequestHeader("x-ms-azs-return-searchid", "true");
request.setRequestHeader("Access-Control-Expose-Headers", "x-ms-azs-searchid");
var searchId = request.getResponseHeader('x-ms-azs-searchid');
Please let me know if I'm misunderstanding the question.

Pulling Articles from Large JSON Response

I'm trying to code something which tracks the Ontario Immigrant Nominee Program Updates page for updates and then sends an email alert if there's a new article. I've done this in PHP but I wanted to try and recreate it in JS because I've been learning JS for the last few weeks.
The OINP has a public API, but the entire body of the webpage is stored in the JSON response (you can see this here: https://api.ontario.ca/api/drupal/page%2F2020-ontario-immigrant-nominee-program-updates?fields=body)
Looking through the safe_value - the common trend is that the Date / Title is always between <h3> tags. What I did with PHP was create a function that stored the text between <h3> into a variable called Date / Title. Then - to store the article body text I just grabbed all the text between </h3> and </p><h3> (basically everything after the title, until the beginning of the next title), stored it in a 'bodytext' variable and then iterated through all occurrences.
I'm stumped figuring out how to do this in JS.
So far - trying to keep it simple, I literally have:
const fetch = require("node-fetch");
fetch(
"https://api.ontario.ca/api/drupal/page%2F2020-ontario-immigrant-nominee-program-updates?fields=body"
)
.then((result) => {
return result.json();
})
.then((data) => {
let websiteData = data.body.und[0].safe_value;
console.log(websiteData);
});
This outputs all of the body. Can anyone point me in the direction of a library / some tips that can help me :
Read through the entire safe_value response and break down each article (Date / Title + Article body) into an array.
I'm probably then just going to upload each article into a MongoDB and then I'll have it checked twice daily -> if there's a new article I'll send an email notif.
Any advice is appreciated!!
Thanks,
You can use regex to get the content of Tags e.g.
/<h3>(.*?)<\/h3>/g.exec(data.body.und[0].safe_value)[1]
returns August 26, 2020
With the use of some regex you can get this done pretty easily.
I wasn't sure about what the "date / title / content" parts were but it shows how to parse some html.
I also changed the code to "async / await". This is more of a personal preference. The code should work the same with "then / catch".
(async () => {
try {
// Make request
const response = await fetch("https://api.ontario.ca/api/drupal/page%2F2020-ontario-immigrant-nominee-program-updates?fields=body");
// Parse response into json
const data = await response.json();
// Get the parsed data we need
const websiteData = data.body.und[0].safe_value;
// Split the html into seperate articles (every <h2> is the start of an new article)
const articles = websiteData.split(/(?=<h2)/g);
// Get the data for each article
const articleInfo = articles.map((article) => {
// Everything between the first h3 is the date
const date = /<h3>(.*)<\/h3>/m.exec(article)[0];
// Everything between the first h4 is the title
const title = /<h4>(.*)<\/h4>/m.exec(article)[0];
// Everything between the first <p> and last </p> is the content of the article
const content = /<p>(.*)<\/p>/m.exec(article)[0];
return {date, title, content};
});
// Show results
console.log(articleInfo);
} catch(error) {
// Show error if there are any
console.log(error);
}
})();
Without comments
(async () => {
try {
const response = await fetch("https://api.ontario.ca/api/drupal/page%2F2020-ontario-immigrant-nominee-program-updates?fields=body");
const data = await response.json();
const websiteData = data.body.und[0].safe_value;
const articles = websiteData.split(/(?=<h2)/g);
const articleInfo = articles.map((article) => {
const date = /<h3>(.*)<\/h3>/m.exec(article)[0];
const title = /<h4>(.*)<\/h4>/m.exec(article)[0];
const content = /<p>(.*)<\/p>/m.exec(article)[0];
return {date, title, content};
});
console.log(articleInfo);
} catch(error) {
console.log(error);
}
})();
I just completed creating .Net Core worker service for this.
The value you are looking for is "metatags.description.og:updated_time.#attached.drupal_add_html_head..#value"
The idea is if the last updated changes you send an email notification!
Try this in you javascript
fetch(`https://api.ontario.ca/api/drupal/page%2F2021-ontario-immigrant-nominee-program-updates`)
.then((result) => {
return result.json();
})
.then((data) => {
let lastUpdated = data.metatags["og:updated_time"]["#attached"].drupal_add_html_head[0][0]["#value"];
console.log(lastUpdated);
});
I will be happy to add you to the email list for the app I just created!

Categories