Retrieve article object including its image using the Shopify JavaScript Buy SDK custom query - javascript

I'm using the shopify-buy SDK to try and fetch the articles off of my Shopify store just using JavaScript on the frontend, following the "Expanding the SDK" directions here: https://shopify.github.io/js-buy-sdk/#expanding-the-sdk.
Using the code below, I am able to retrieve my articles and some of the fields that I need.
// Build a custom query using the unoptimized version of the SDK
const articlesQuery = client.graphQLClient.query((root) => {
root.addConnection('articles', {args: {first: 10}}, (article) => {
article.add('title')
article.add('handle')
article.add('url')
article.add('contentHtml')
})
})
// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
console.log('articles data')
console.log(data)
})
However, I really need to pull the featured image for each article as well, and unfortunately, when I add the line article.add('image') in my articlesQuery, the resulting articles data logs null. I tried building a custom productsQuery, and that has a similiar problem - I can retrieve some of the product fields, but when I try add the line product.add('images'), I just get null back from the storefront API.
Does anyone have experience building custom/expanded queries and successfully retrieving images?

Try following:
// Fetch all products in your shop
client.graphQLClient.fetchAll().then((acticles) => {
console.log(acticles);
});
And then check in console what sort of available property names your articles have. If SDK allows you get any image data, there should be for sure anything like imageSrc || imageUrl || img......

Thanks to Rebecca Friedman on the js-buy-sdk repo's github issues section for providing this working solution:
const articlesQuery = client.graphQLClient.query((root) => {
root.addConnection('articles', {args: {first: 10}}, (article) => {
article.add('title')
article.add('handle')
article.add('url')
article.add('contentHtml')
article.addField('image', {}, (image) => {
image.add('id')
image.add('originalSrc')
})
})
})
// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
console.log('articles data')
console.log(data) // works!
})
Because the image field is its own object, you have to add a callback function to specify the fields you need.

Related

How to use Apify web scrapper data in a React.js interface?

I'm using Apify web scraper to scrape h1,h2 and a span from a website. I have read all of their docs but I can't seem to find an answer for this.
async function pageFunction(context) {
const $ = context.jQuery;
const h1 = $('main h1').first().text();
const first_h2 = $('h2').first().text();
const random_text_from_the_page = $('main span').text();
// Print some information to actor log
context.log.info(`URL: ${context.request.url}, What is going on?: ${h1}`);
// Manually add a new page to the queue for scraping.
// await context.enqueueRequest({ url: 'http://www.example.com' });
// Return an object with the data extracted from the page.
// It will be stored to the resulting dataset.
return {
url: context.request.url,
h1,
first_h2,
random_text_from_the_page
};
}
How can I use that json data I get back and display it in a simple React UI for people to see?
Is it even possible? If not in React maybe just a simple vanilla JS UI?
Thank you.

How to convert a JS react page into an HTML page

So I'm working on a CMS project that allows users to create their own websites just like wordpress or other CMS platforms...
The users can implement different modals into their websites (text modal, image modal, search modal and other stuff), and then we create an object with the created page infos.
The Object contains all the page infos like the example bellow:
{
pageName: "Home page",
pageLink: "home",
pageSlug: "home-page",
pageMetaDescription: "home meta description",
pageMetaTitle : "home meta title",
pageModals : [
modal1: {
//modal infos here.
}
modal2: {
//modal infos here.
}
]
}
What I'm doing now is stocking these Objects on a database and when the user requests a page, I fetch the object and then generate a react JS file. But this approach isn't the best for performance or SEO.
So I would like to actually generate an HTML file from these Objects and store them in the database and when the user requests a page, it just loads the generated HTML file instead of fetching the Object and populating a react JS page.
If you have an Idea or approach to do this, I would like your help.
Yes you can use Next.js to handle your case
Next allow you to fetch some external data and render html based on api result
Here an example from documentation adapted for your cases
// pagesInfos will be populated at build time by getStaticProps()
function Blog({ pagesInfos }) {
const { pageSlug, pageMetaDescription , pageMetaTitle ...} = pagesInfos
return (
<div>
<h1>{postMetaTitle}</h1>
<p>{pageMetaDescription}</p>
</div>
)
}
// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries.
export async function getStaticProps() {
// Call an external API endpoint to get posts.
// You can use any data fetching library
const res = await fetch('https://.../getPages')
const pagesInfos = await res.json()
// By returning { props: { pagesInfos } }, the Blog component
// will receive `pagesInfos` as a prop at build time
return {
props: {
pagesInfos,
},
}
}
export default Blog
Here is full docs : https://nextjs.org/docs/basic-features/data-fetching/get-static-props

Firebase query array or objects with Javascript

I've been struggling with creating a firebase query all day!
The below query returns the data as an array from my Firebase realtime database:
exports.getCountry = () => {
return database
.ref("/countries")
.once("value")
.then(data => data.val());
};
This returns the below from the database in the format Array of Objects,
[
{"id":1, "country":"singapore", "population":15000000},
{"id":2, "country":"hongkong", "population":12000000},
{"id":2, "country":"vietnam", "population":2250000}
]
However I want to query the database to just return one record, something along the lines of
exports.getCountry = () => {
return database
.ref("/countries")
.where('id'===1)
.once("value")
.then(data => data.val());
};
would return a single line from my database:
{"id":1, "country":"singapore", "population":15000000}
however I can't get this to work! It should be simple, but I can't get it to play ball!
I referenced these Firebase docs on complex queries.
Piecing together the examples they provide, I think your query should look something like:
var ref = db.ref("countries");
ref.orderByChild("id").equalTo(1).on("value", function(snapshot) {
snapshot.forEach( data => {
console.log(data.val());
});
});
*untested
EDIT:
The docs I linked are to the admin SDK, if you are doing this on the front end with JavaScript, it should still work. The JavaScript SDK appears to have the same query structure - shown in these docs for the JS SDK too.

Userless Authentication Foursquare API "Missing access credentials" - 400 error

Bit of a weird one. I'm building a React js app interacting with the Foursquare API, mainly just to learn about React js and APIs.
I'm using Foursquare to get Venue information, that works fine. I also want to use it to get venue photos which is where the fun starts.
The method that processes the original call to venues is as follows. I'm just putting this here for to provide a control as this works fine. It returns the venue information which i process within the app with no problem:
getVenues: (searchTerm) => {
const urlToFetch =
${urlExplore}${searchTerm}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602;
return fetch(urlToFetch).then( response => {
return response.json();
}).then( jsonResponse => {
if (jsonResponse.response.groups[0].items) {
return jsonResponse.response.groups[0].items.map(item => (
{
id: item.venue.id,
name: item.venue.name,
// blah
}
));
} else {
return [];
}
})
}
So far, so good, it works fine. However, when I try the same approach accessing the photos endpoint, the method returns a series of objects containing meta which says:
​ code: 400
​​ errorDetail: "Missing access credentials. See
https://developer.foursquare.com/docs/api/configuration/authentication for
details."
​​errorType: "invalid_auth"
Suffice to say the information at the link provided doesn't actually give much help :-(
The method I'm using to get the photo information is:
getVenuePhotos: (venueId) => {
const fetchPhotosURL = `${urlPhotos}${venueId}/photos&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602`;
return fetch(fetchPhotosURL).then( response => {
return response.json();
}).then( jsonResponse => {
console.log(jsonResponse);
//blah - removed to save space - see method above, it's pretty much the same
})
}
...both are stored in an object in a separate file which the react component imports.
The url vars resolve as follows (asterisks are my addition):
fetchVenuesURL: https://api.foursquare.com/v2/venues/explore?near=london&limit=10&client_id=**** &client_secret=****&v=20180602
fetchPhotosURL: https://api.foursquare.com/v2/venues/4ac518eff964a52064ad20e3/photos&limit=10&client_id=**** &client_secret=****&v=20180602
Does anyone have any idea why this might be happening?
thanks in advance
I think there is a typo in your URL.
Replace
${urlPhotos}${venueId}/photos&limit=10&client...
with
${urlPhotos}${venueId}/photos?limit=10&client...

How to retrieve both caller-name and carrier from Twilio in node.js?

Im having problems working with the twilio-api for node.
i wrote this code:
let typeArray = ['caller-name','carrier'];
this.client.phoneNumbers(phoneNumberToCheck).get({
type: typeArray
}, (error, number) => {
// working on the number data results
// ...
});
The problem is that i dont get ANY of them(carrier/caller-name) - although passing array to argument 'type' is the way to do it in other languages(php,c#..) but it doesnt work on node.js, instead i get this:
// -> get
{
"caller_name":null,
"country_code":"US",
"phone_number":"+123456789",
"national_format":"(248) 123-456",
"carrier":null,
"add_ons":null,
"url":"https://lookups.twilio.com/v1/PhoneNumbers/+123456789",
"callerName":null,
"countryCode":"US",
"phoneNumber":"+123456789",
"nationalFormat":"(248) 123-456",
"addOns":null
}
note: if i send each one separately (only carrier or only caller-name) - i get the partial information for each.
how can i get both in one request in node.js?
Twilio developer evangelist here.
You should be calling the Lookups API in Node this way:
client.lookups.phoneNumbers.get(phoneNumber)
.fetch({
type: ['carrier', 'caller-name']
},
function(err, result) {
// do something
}
)
The docs are a little lacking in Node.js on the Lookups documentation and I will raise that with the team.

Categories

Resources