Business discovery user media with location - instagram

i'm fetching all user details with latest media and some insights, but the posts are not including the location:
const fields =
'fields=business_discovery.username(jbalvin){id,ig_id,name,username,profile_picture_url,followers_count,media_count,biography,follows_count,media{comments_count,like_count,timestamp,media_type,media_product_type,location{city}}}';
const res = fetch(
`https://graph.facebook.com/v12.0/${id}?${fields}&access_token=${token}`
)
.then((response) => response.json())
.then((data) => console.log(data));
This is the answer i'm getting:
{
business_discovery: {
id: '17841401525860163',
ig_id: 10482862,
name: 'J Balvin',
username: 'jbalvin',
profile_picture_url: 'https://scontent.fbaq2-2.fna.fbcdn.net/v/t51.2885-15/272307439_140470511724764_4263731586488463919_n.jpg?_nc_cat=1&ccb=1-5&_nc_sid=86c713&_nc_eui2=AeErYr-NceD1DvlTdMFw7QPcrlXwvFWx4ZOuVfC8VbHhkxGyDdL5-tOIFpeIU77PgqeJvRY6gXVRGSpdxBP8SxNL&_nc_ohc=RswtWyTHU8wAX_u4pcF&_nc_ht=scontent.fbaq2-2.fna&edm=AL-3X8kEAAAA&oh=00_AT8p18_oXvJsxCQV632bq6vmDcxMrJ9HHnQdk5E-s29bDw&oe=61F82A7A',
followers_count: 51214234,
media_count: 12940,
follows_count: 1927,
media: {
data: [
{
comments_count: 1550,
like_count: 427154,
timestamp: '2022-01-25T01:00:20+0000',
media_type: 'CAROUSEL_ALBUM',
media_product_type: 'FEED',
id: '17928326101919137'
},
],
paging: {
cursors: {
after: 'QVFIUjh1cGMwNnFnbldraGtuOU5fcGNDNFF6ekdvWkhSV3o3SjdJQ25iMl9tU0ZAoNTlMVlEtcnh6VUZAKQnFoLUFTc3phREdlZAmNCR0NGMkV4QldhNkFORk5R'
}
}
}
},
i deleted the other 24 post because the response is too long. The thing is that the post that i'm showing there has a location on instagram, but the api is not responding with it, how can i get the post location?

Related

ERROR: Module not found: Can't resolve 'dns'

I am building an application in React. My problem is that if I navigate to the route '/factura/api/invoices/${invoiceId}' and press the edit button, it should send the information to the MongoDB database and return that everything is fine, but when I do it, I get the following error.
./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0
Module not found: Can't resolve 'dns'
Import trace for requested module:
./node_modules/mongodb/lib/index.js
./pages/facturas/api/edit/[invoiceId]/index.js
https://nextjs.org/docs/messages/module-not-found
I am not sure why I am receiving this error. This is my first part of the code located in the '/facturas/edit/[invoiceId]' folder:
const updateInvoice = async (invoiceId, status) => {
try {
const res = await fetch(`/facturas/api/edit/${invoiceId}`, {
method: 'PUT',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
senderStreet: senderStreet,
senderCity: senderCity,
senderPostalCode: senderPostalCode,
senderCountry: senderCountry,
clientName: clientName,
clientEmail: clientEmail,
clientStreet: clientStreet,
clientCity: clientCity,
clientPostalCode: clientPostalCode,
clientCountry: clientCountry,
description: description,
createdAt: createdAt,
paymentDue: createdAt,
paymentTerms: paymentTerms,
status: status,
items: items,
total: totalAmount
})
})
const data = await res.json()
router.push(`/facturas/invoices/${invoiceId}`)
toast.success(data.message)
} catch (error) {
toast.error("Something is wrong")
console.log(error)
}
}
And this is the second part of the code in the file located in the API folder:
import { MongoClient, ObjectId } from "mongodb";
async function handler(req, res) {
const { invoiceId } = req.query;
const client = await MongoClient.connect('mongodb+srv://test:test#cluster0.uusfifl.mongodb.net/invoices?retryWrites=true&w=majority', { useNewUrlParser: true });
const db = client.db();
const collection = db.collection("allInvoices");
if (req.method === "PUT") {
await collection.updateOne(
{
_id: ObjectId(invoiceId),
},
{
$set: {
senderAddress: {
street: req.body.senderStreet,
city: req.body.senderCity,
postalCode: req.body.senderPostalCode,
country: req.body.senderCountry,
},
clientName: req.body.clientName,
clientEmail: req.body.clientEmail,
clientAddress: {
street: req.body.clientStreet,
city: req.body.clientCity,
postalCode: req.body.clientPostalCode,
country: req.body.clientCountry,
},
createdAt: req.body.createdAt,
paymentDue: req.body.createdAt,
paymentTerms: req.body.paymentTerms,
description: req.body.description,
status: req.body.status,
items: req.body.items,
total: req.body.total,
},
}
);
res.status(200).json({ message: "Invoice updated successfully" });
}
client.close();
}
export default handler;
And here are all the files that I have used, in case you want to see them:
https://github.com/Fukene/tarea_database
Thanks.
I tried to reinstall MongoDB again. I checked that the routes were correct and verified that the MongoDB credentials information were correct. And everything seems to be fine. I still don't know what the problem is.
The confusing thing is that it was working well until I changed the files in folders. I suppose the problem is that the route to some file is wrong, but I haven't found where the problem is.
Edit
I found some posts that say I should move my folders to be directly in the /pages folder, and when I do that my code works perfectly. Why? It's a novice question, but I don't understand how to differentiate what is acting as frontend and what as backend.

google maps, client libraries node js, distance matrix request js

I am trying to implement a google maps distance matrix api request using, node JS google Client library. specifically
#googlemaps/google-maps-services-js
The problem am facing, I can only finds source code example for elevation in the documentation.
const client = new Client({});
client
.elevation({
params: {
locations: [{ lat: 45, lng: -110 }],
key: "asdf",
},
timeout: 1000, // milliseconds
})
.then((r) => {
console.log(r.data.results[0].elevation);
})
.catch((e) => {
console.log(e.response.data.error_message);
});
I need source code example for Distance Matrix so I can implement point to point distance calculation within node JS, using the client library.
const client = new Client({});
client
.distanceMatrixrequest()
client
.distancematrix({
params: {
key: '<YOUR_KEY>',
origins: ['Greenwich, England'],
destinations: ['Stockholm, Sweden'],
travelMode: 'DRIVING',
// Feel free to set more params
},
timeout: 1000, // milliseconds
})
.then((r) => {
console.log(r.data.rows[0]?.elements);
res.json(r.data);
})
.catch((e) => {
console.log(e.response.data.status);
});
Response comes in this format:
[
{
distance: { text: '1,880 km', value: 1880123 },
duration: { text: '20 hours 59 mins', value: 75548 },
status: 'OK'
}
]

Need help to store variant data in shopify using "Shopify API Node.js"

Hi recently I am working with reactjs & nodejs project and developing a new dashboard module like this.
ERROR SCREEN-SHOT
now i want to add a product to Shopify but i will send data using API for variant but by default, it saves default Shopify data like this.
[enter image description here][2]
And here is my code 
Main Function On Submit click
const productAddEditSubmit = () => {
var productObject = {
name: fullProductData.name,
description: fullProductData.description,
category_id: fullProductData.category_id,
certification_type_id: fullProductData.certification_type_id,
artwork_origin_id: fullProductData.artwork_origin_id,
price: fullProductData.price,
currency: fullProductData.currency,
quantity: fullProductData.quantity,
sku: fullProductData.sku,
status: fullProductData.status,
purchase_url: fullProductData.purchase_url,
// user_id: user._id,
update_date: new Date(),
}
if (productActionValue.hasOwnProperty('id')) {
// dispatch(updateProduct(fullProductData._id, productObject, tempMediaList))
}
else {
dispatch(addProductData(productObject));
}
}
Action File
export const addProductData = (product) => dispatch => {
axios.post('/api/shopifyProduct', product).then((res) => {
dispatch({
type: ADD_PRODUCT,
payload: res.data
})
})
}
[Final Data Sent to Shopify DB Using shopify-api-node NPM Package][5]
Post Route
router.post('/', (req, res) => {
const getProductDataFromFrontEndPartOne = {
title: req.body.name,
body_html: req.body.description,
product_type: req.body.category_id,
status: "draft"
}
// getProductDataFromFrontEndPartOne this object data store in shopify
shopify.product.create(getProductDataFromFrontEndPartOne)
.then((res) => {
// after res i did not store this object (getProductDataFromFrontEndPartTwo) into shopify.
const getProductDataFromFrontEndPartTwo = {
id: res.id,
price: req.body.price,
sku: req.body.sku,
inventory_quantity: req.body.quantity
}
shopify.productVariant.create(getProductDataFromFrontEndPartTwo)
})
.catch(err => res.status(404).json({ success: false }));
});
Shopify.product.create using this function to save data in Shopify if res is successful after I did send variant data into their particular product using res.id.

How access Fauna's "after" cursors in Next.js API routes

I am building an application using Next.Js and Fauna where when a user visits the /accounts route, it fetches Next.js API route /api/fauna/accounts which makes a query to Fauna to get all the accounts the user owns then returns that response to the page and renders the data in a table.
Fetch inside /accounts looks like so:
function Accounts() {
const [data, setData] = useState(null)
useEffect(() => {
fetch('api/accounts')
.then((res) => res.json())
.then((data) => {
setData(data)
})
}, [])
return (
<Table>
{...data}
</Table>
)
}
The response inside /api/fauna/accounts returns an "after" cursor used for pagination. This is what the response looks like on the server inside /api/fauna/accounts
{
after: [
Time("2022-03-08T15:59:43.284410Z"),
Ref(Collection("accounts"), "325579003214692417"),
Ref(Collection("accounts"), "325579003214692417")
],
data: [...]
}
However, when that response is sent back to the /accounts route, the "after" cursor is formatted completely differently than on the server which makes it difficult to paginate with. The response for the "after" cursor looks like this:
{
after: [
{ "#ts": "2022-03-08T15:49:23.686204Z" },
{
"#ref": {
id: "325578353522245700",
collection: { "#ref": { id: "accounts", collection: { "#ref": { id: "collections" } } } }
}
},
{
"#ref": {
id: "325578353522245700",
collection: { "#ref": { id: "accounts", collection: { "#ref": { id: "collections" } } } }
}
}
],
data: [...]
}
How do I paginate to the next page when the "after" cursor is formated like so?
The format that you're seeing is Fauna's wire protocol. JSON doesn't handle embedded objects like References (among other complex response values), so those get serialized in a way that can be round-tripped.
The JavaScript driver includes a utility library called _json.js, which can take care of reconstituting the original cursor value:
const faunadb = require('faunadb')
const json = require('faunadb/src/_json')
const q = faunadb.query
// assuming response contains the wire protocol data from a pagination query
const deserialized = json.parseJSON(response)
// then you can include the `after` field in a subsequent query
const response2 = client.query(
q.Paginate(
q.Match(q.Index("your_index"), [<terms>]),
{
after: deserialized.after
}
)
)
.then(res => console.log(res))
.catch(err => console.err("Error:", err))

how can we use data received through axios put request on client side in mern stack?

I have sent category Id to the Nodejs through this code
const catHandler = async (catId) => {
const data = Axios.put('/api/products/categories/filter', {catId: catId},
{
"headers": { "content-type": "application/json", },
}
).then( categoriesProducts => {
console.log(categoriesProducts.data.products)
})
}
and this is my route for this
router.put('/categories/filter', async (req, res) => {
try {
const findCategory = await Category.find({ _id: req.body.catId });
if (findCategory) {
const productsByCategory = await Product.find(
{ category: req.body.catId }
).then(products => {
res.status(200).json({ products });
})
}
} catch (error) {
console.log('categories filter error', error)
}
})
The products of specific category are being shown in the console.log(categoriesProducts.data.products) on the react front end side like below
0: {_id: "5f7c88756746363148792982", name: "Simple Pizza", price: 5.6, image: "1601996916374.jpg", countInStock: 434, …}
1: {_id: "5f7c88976746363148792983", name: "Smoked Pizza", price: 7.8, image: "1601996951114.jpg", countInStock: 88, …}
2: {_id: "5f7c88c56746363148792984", name: "Large Cheezy Pizza", price: 9.4, image: "1601996997474.jpg", countInStock: 434, …}
But I want to display these products on the front end side. I have tried to use axios.get method but with get method how can I can send category Id to backend. So if any one has any idea how to do that Plz guide me.
you can use the query params with get method in node js
you can get query params by req.query in nodeJs
example
passing category id from front end -
api/products/categories/filter?cid=1
getting query param in the backend
const catId = req.query.cid
You can use below code to pass parameter to API get method.
fetch("/api/products/categories/filter?catId" + catId)
.then((res) => res.json())
.then((json) => {
this.setState({
Items: json,
});
});
And also you first create new state named as Items such as below.
this.state = {
Items: []
};
And finally Iterate on Items.
BR

Resources