I have my function that create requests to get recents tweets by a keyword (I'm using NodeJS), but I need to stop it after 10 tweets, how can I do that? From the twitter api doc I didn't find anything...
Here only mentions the limit but not how to set it
https://developer.twitter.com/en/docs/twitter-api/rate-limits
Here the code:
const rules = [{
value: //keyword
}]
function streamTweets() {
const stream = needle.get(streamURL, {
headers: {
Authorization: `Bearer ${TOKEN}`
}
})
stream.on('data', (data) => {
try {
const json = JSON.parse(data)
console.log(json)
} catch (error) {
}
})
}
(async () => {
let currentRules
try {
currentRules = await getRules()
await deleteRules(currentRules)
await setRules()
} catch (error) {
console.error(error)
process.exit(1)
}
streamTweets()
})()
Related
Here's the code in react that I am using to get the data from database.
const getData = async (e) => {
const res = await fetch(`${process.env.REACT_APP_BASE_URL}/edit/${id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await res.json();
console.log(data);
if (res.status === 422 || !data) {
console.log("Error");
} else {
setValues(data);
console.log("Data Edited successfully");
}
};
useEffect(() => {
getData();
}, []);
Here's the patch request
router.patch("/edit/:id", async (req, res) => {
try {
const { id } = req.params;
const updateUser = await Crud.findByIdAndUpdate(id, req.body, {
new: true,
});
console.log(updateUser);
res.status(201).json(updateUser);
} catch {
res.status(422).json(error);
}
});
I want to update the data in my application but I cannot get the data from the database. So can anyone tell what the problem is
From frontend, you are calling GET request and from your backend, you're receiving as a patch how it works pls do the same method on both hands
I have a router.get which calls another function, like this:
router.get("/", (req, res) => {
const data = especiaisTest.getEspeciais();
console.log(data);
});
The function which is calling is this one:
function getEspeciais() {
db.query(async (tokenResponse) => {
try {
const response = await axios.get(URL, {
headers: {
Authorization: `Bearer ${tokenResponse.accessToken}`,
},
});
return response.data;
} catch (error) {
console.error(error);
}
});
}
Whenever i call it, I just get console.logged an undefined.
I tried returning a value outside the db.query function, for example:
function getEspeciais() {
db.query(async (tokenResponse) => {
try {
const response = await axios.get(URL, {
headers: {
Authorization: `Bearer ${tokenResponse.accessToken}`,
},
});
return response.data;
} catch (error) {
console.error(error);
}
});
return 'hello'
}
And it will display the 'hello' in the console. How can I get the response.data out of the db.query in order to be able to show the data?
Question codes.
router.get("/", (req, res) => {
const data = especiaisTest.getEspeciais();
console.log(data);
});
function getEspeciais() {
db.query(async (tokenResponse) => {
try {
const response = await axios.get(URL, {
headers: {
Authorization: `Bearer ${tokenResponse.accessToken}`,
},
});
return response.data;
} catch (error) {
console.error(error);
}
});
}
Should be:
router.get("/", async (req, res) => {
const data = await especiaisTest.getEspeciais();
async function getEspeciais() {
return db.query(async (tokenResponse) => {
Then you will see something else rather than undefined.
If return undefined, the db.query method return nothing.
I'm having these calls to list users with groups from google active directory
let globalGroups = null;
let groupMembers = null;
await GetCustomerId(req, res).then( async () => {
// GetGroups is async function saves groups in `globalGroups` variable
await GetGroups(token).then( () => {
globalGroups.forEach( async (group) => {
// GetGroupMembers is async function saves users in `groupMembers` variable
await GetGroupMembers(group.id, token).then( () => {
groupMembers.forEach( (member) => {
// here I log the `member` and have no issues here
if (usersIds.includes(member.id)) {
let user = users.find( ({ id }) => id === member.id );
user.group_ids.push(group.id);
}
else {
member.group_ids = [];
member.group_ids.push(group.id);
users.push(member);
usersIds.push(member.id);
}
})
})
});
// the issue is here without timeout it returns an empty array because it doesn't wait for the loop to finish
console.log(users);
res.status(200).json({"users": users}).send();
}).catch(function(err) {
console.log(err)
res.status(500).json({"error": err}).send();
});
});
This returns an empty array unless I use timeout to return the response like this
setTimeout( () => {
console.log(users);
res.status(200).json({"users": users, "next_page_link": "notFound"}).send();
}, 1000);
How to make it wait till the whole loop ends to return the response without using timeout?
const GetCustomerId = async (req, res, next) => {
try {
let authorization = req.headers['authorization'].split(' ');
if (authorization[0] !== 'Bearer') {
return res.status(401).send();
} else {
await axios({
url: 'https://admin.googleapis.com/admin/directory/v1/users?domain=&maxResults=1',
method: 'get',
headers: {
'Content-Type': "application/json",
'Authorization': ' Bearer ' + authorization[1]
},
})
.then((response) => {
globalCustomerId = response.data.users[0].customerId
})
.catch(function(err) {
console.log(err);
});
}
} catch (err) {
console.log(err);
}
}
const GetGroups = async (token) => {
try {
await axios({
url: 'https://admin.googleapis.com/admin/directory/v1/groups?customer=' + globalCustomerId,
method: 'get',
headers: {
'Content-Type': "application/json",
'Authorization': ' Bearer ' + token
},
})
.then((response) => {
globalGroups = response.data.groups;
})
.catch(function (err) {
return res.status(500).json({"error": err}).send();
});
} catch (err) {
return res.status(403).json(err).send();
}
}
const GetGroupMembers = async (groupId, token) => {
await axios({
url: "https://admin.googleapis.com/admin/directory/v1/groups/" + groupId + "/members",
method: 'get',
headers: {
'Content-Type': "application/json",
'Authorization': ' Bearer ' + token
},
})
.then((response) => {
groupMembers = null;
groupMembers = response.data.members;
})
.catch(function (err) {
return res.status(500).json({"error": err}).send();
});
}
globalGroups.forEach( async (group) => {
An async method inside .forEach doesn't actually do what you might want it to do.
By essentially doing array.forEach(async method) you're invoking a bunch of async calls, 1 per element in the array. It's not actually processing each call one by one and then finally resolving.
Switch to using a regular for loop with await inside it and it will do what you want.
eg.
for (const group of globalGroups) {
await GetGroupMembers(group.id, token)
groupMembers.forEach.....
}
You could do that to force your code to be more synchronous (or use something like Promise.all to be more efficient while still being synchronous) but another issue with the code is you're stuck in callback hell, which leads to less-readable code.
I'd highly recommend refactoring your Get* methods such that they return the values you need. Then you can do something cleaner and predictable/deterministic like:
const globalCustomerId = await GetCustomerId(req, res);
const globalGroups = await GetGroups(token); //note: Promise.all could help here
for (const group of globalGroups) {
const groupMembers = await GetGroupMembers(group.id, token)
groupMembers.forEach.....
}
console.log(users);
res.status(200).json({"users": users}).send();
You can wrap it in a try/catch to take care of error handling. This leads to much cleaner, more concise, and more predictable order of executions.
Hey guys I am trying to pull some data from a http request in a firebase pub sub function. Here is my current function I have ommited my api key
async function requestPromise(path: string) {
return new Promise((resolve, reject) => {
const options = {
hostname: "pro-api.coinmarketcap.com",
path: "/v1/cryptocurrency/listings/latest?start=1&limit=10&convert=USD",
method:"GET",
headers: {
Authorization: "Omitted",
},
};
http.get(options, (resp) => {
let data = "";
resp.on("data", (chunk) => {
data += chunk;
});
resp.on("end", () => {
resolve(data);
});
}).on("error", (error) => {
reject(error);
});
});
}
exports.updateCoinPrices = functions.pubsub.schedule("every 5 minutes")
.onRun(async (context) => {
await (async function () {
try {
await requestPromise("https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=query=limit=").then((data) => {
console.log("the data is")
console.log(data)
});
} catch (error) {
console.error(error);
}
});
return null;
});
Here is what I get from firebase data is
and here is what the data should be coming in as any ideas ?
I want to do make the same api call as made in this postman photo below :
postman
I have already tried the following code but it only returns some html not the desired response
async function vendor_info() {
const options = {
uri: 'http://**.**.**.**/vendor/:username/pj1527',
json: true,
method: 'GET'
};
let vendor_info = undefined;
await requestPromise(options)
.then((body) => {
// err_token = 0;
vendor_info = body[0];
console.log(body);
// console.log(body[0]);
})
.catch(err => {
vendor_info = undefined;
// err_token = 1;
// console.log(err);
});
return vendor_info;
}
EDIT
It's working now, actually the url should be 'http://.../vendor//pj1527' in the request.
If you are using async await then there is no need to use then and catch blocks, Try like this:
async function vendor_info() {
try {
const options = {
uri: 'http://**.**.**.**/vendor/:username/pj1527',
json: true,
method: 'GET'
};
const vendor_info = await requestPromise(options);
console.log('vendor_info: => ', vendor_info);
return vendor_info;
} catch (err) {
console.log('Error: => ', err);
return err;
}
}
Hope this helps :)