Problem with Axios Get request - might be an Asynchronous problem - asynchronous

I seem to be having asynchronous problems. I'm using react, express, sequelize and mariadb for the entire app. I am using axios in my front end to make the get request. However, the get request always returns an empty value. However, in my backend code I know the request is calling the database findAll().
Front-end (React/Axios)
componentDidMount() {
this.getPets();
}
getPets = async () => {
try {
const resp = await axios.get('/getdogs');
this.setState({ pets: resp.body });
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
server.js
app.get('/getdogs', (req, res) => {
console.log("IN THE FUNCTION");
const pets = db.getPets();
console.log("All pets:", JSON.stringify(pets, null, 2));
res.send(pets);
});
database.js
async function getPets() {
const pets = await Pets.findAll();
console.log("All pets:", JSON.stringify(pets, null, 2));
return JSON.stringify(pets, null, 2);
}
output from server.js
nodemon] starting `node server.js`
Listening on port 5000
IN THE FUNCTION
All pets: {}
warning: please use IANA standard timezone format ('Etc/GMT0')
warning: please use IANA standard timezone format ('Etc/GMT0')
Executing (default): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Pets` AS `Pets`;
All pets: [
{
"id": 1,
"name": "HULK",
"createdAt": "2020-09-15T23:09:43.000Z",
"updatedAt": "2020-09-15T23:09:43.000Z"
},
{
"id": 2,
"name": "Martha",
"createdAt": "2020-09-15T23:09:43.000Z",
"updatedAt": "2020-09-15T23:09:43.000Z"
},
{
"id": 3,
"name": "Bernie",
"createdAt": "2020-09-15T23:09:43.000Z",
"updatedAt": "2020-09-15T23:09:43.000Z"
}
]

An axios response does not have body property. Response is in the data property, see Response schema
this.setState({ pets: resp.data });
console.log(resp.data);
You haven't awaited a result from DB:
db.getPets().then(pets => {
console.log("All pets:", JSON.stringify(pets, null, 2));
res.send(pets);
});

Related

Pass variable from client to server-side in NEXTJS

I have already done this but Idk why when I try to apply it again in another code it does not work. So I have this code "Client side"
const response = await fetch("/api/ipfs", {method: "POST", DATA: "holaaaa"});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const result = await response.json()
console.log(result.result)
And this one that is the "Server side"
function uploadIPFS(req, res) {
axios.get(req.body).then(r => {
let metadata = r.data
res.status(200).json({ metadata: metadata });
}).catch(err => console.error(err))
}
export default function handler(req, res) {
if (req.method==='POST') {
uploadIPFS(req, res);
}
}
This is working with another api file I have, so I implement another file that is this one and in another function of the client side make a call to the new api file, the problem is that the variable I want to pass from client to server is the body one, the one that says "holaaaa", is it not working and it throws this error.
API resolved without sending a response for /api/ipfs, this may result in stalled requests.
Error: Cannot read properties of null (reading 'replace')
at dispatchHttpRequest (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\adapters\http.js:161:23)
at new Promise (<anonymous>)
at httpAdapter (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\adapters\http.js:49:10)
at dispatchRequest (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\dispatchRequest.js:58:10)
at Axios.request (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\Axios.js:109:15)
at Axios.<computed> [as get] (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\Axios.js:131:17)
at Function.wrap [as get] (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\helpers\bind.js:9:15)
at uploadIPFS (webpack-internal:///(api)/./pages/api/ipfs.js:17:11)
at handler (webpack-internal:///(api)/./pages/api/ipfs.js:37:9)
at Object.apiResolver (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\next\dist\server\api-utils\node.js:184:15) {
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.27.2'
},
method: 'get',
url: '',
data: undefined
},
url: '',
exists: true
}
any idea abt this?
The request to your API is made, but you are not adding anything to the request body. I think you need to change your DATA property in your fetch call to body:
const response = await fetch("/api/ipfs", { method: "POST", body: "holaaaa" });
Also, since you are passing that body parameter to the axios.get() method in your API handler, I assume it's supposed to be a URL?

React Native FirebaseError: Function Query.startAfter() requires a valid first argument, but it was undefined

So Im receiving an error or:
FirebaseError: Function Query.startAfter() requires a valid
first argument, but it was undefined.
My code:
getMore = async () => {
let check = {};
check = this.state.lastDoc;
console.log(check); //returns a big object I will post below.
if (check) {
this.setState({ isMoreLoading: true });
setTimeout(async () => {
let snapshot = await firebase
.firestore()
.collection("posts")
.orderBy("timestamp", "desc")
.startAfter(check.data().id)
.limit(2)
.get();
};
So I guess this error is about firebase.
WHAT console LOG (check) RETURNS JUST BEFORE BEING USED FOR
startAfter: ITS CUT A BIT BECAUSE IT COULDNT BE POSTED: ITS CUT A BIT
BECAUSE IT COULDNT BE POSTED:
QueryDocumentSnapshot {
"_document": Document {
"converter": [Function anonymous],
"
},
"name": Object {
"stringValue": "NoviMatko",
},
"text": Object {
"stringValue": "For wh perceive laughing six did far.",
},
"timestamp": Object {
"integerValue": "1604771339487",
},
"uid": Object {
"stringValue": "S2BxNARp4Cfinttb1TK5mzAHPb13",
},
},
"name": "projects/eleph-6fee9/databases/(default)/documents/posts/djoSXIPRn1RMxMq2TD4C",
"updateTime": "2020-11-07T17:49:00.119930Z",
},
"version": SnapshotVersion {
"timestamp": Timestamp {
"nanoseconds": 119930000,
"seconds": 1604771340,
},
},
},
"
"[DEFAULT]" => Object {
"apiKey": "AIzaSyDwUBce3WYEl78xA6aag5nzb1xh2xC8dZQ",
"lastLoginAt": "1604691856267",
"phoneNumber": null,
"photoURL": null,
"providerData": Array [
Object {
"displayName": null,
"email": "dwdwadw#gmail.com",
"phoneNumber": null,
"photoURL": null,
"providerId": "password",
"uid": "dwdwadw#gmail.com",
},
],
"redirectEventId": null,
},
"tenantId": null,
"uid": "S2BxNARp4Cfinttb1TK5mzAHPb13",
},
},
},
"instancesDeferred": Map {},
"name": "auth",
},
},
"container": [Ci...(truncated to the first 10000 characters)
Got all results
vVbq2mwrDMseBxCPDj15 => {"avatar":null,"name":"NoviMatko","text":"evoooo","timestamp":1605303464278,"uid":"S2BxNARp4Cfinttb1TK5mzAHPb13"}
vG9p4xL8UqlZBkls1Xv1 => {"avatar":null,"name":"NoviMatko","text":"gdgdgdg","timestamp":1605303411975,"uid":"S2BxNARp4Cfinttb1TK5mzAHPb13"}
xyyZQs5q9OLP2BdqDwJO => {"avatar":null,"name":"NoviMatko","text":"jkj","timestamp":1605136211563,"uid":"S2BxNARp4Cfinttb1TK5mzAHPb13"}
jttcmEM8WFHOXxRIO9q9 => {"avatar":null,"name":"NoviMatko","text":"adawdadjnajodhjadjonadjjajdhajdnjadnjandjnadnadajdnjas","timestamp":1605116149227,"uid":"S2BxNARp4Cfinttb1TK5mzAHPb13"}
qFJwWiS0dpaKFbVOWrG1 => {"avatar":null,"name":"NoviMatko","text":"gsgsefgsfsf😘😘😊😊","timestamp":1605115920543,"uid":"S2BxNARp4Cfinttb1TK5mzAHPb13"}
qD8rrsexA4HrWHvCtfxR => {"avatar":null,"name":"NoviMatko","text":"JLKDBWJENKEFJOFBNKOJSBENFJKSNFJKLSNFJKSJNFJSKFNJSNFNSFNSNFNSJKLEFNSENFSNFJNSEJFNSJFNSJFNSEFNLSNF;SNFS;FH;SFJSFNSJFNSJNFJSNFJSNFNSNFNSFNSJFNSFNSF","timestamp":1605115869284,"uid":"S2BxNARp4Cfinttb1TK5mzAHPb13"}
djoSXIPRn1RMxMq2TD4C => {"avatar":null,"name":"NoviMatko","text":"For who thoroughly her boy estimating conviction. Reme admire in giving. See resolved goodness felicity shy civility domestic had
but. Drawings offended yet answered jennings perceive laughing six did far.","timestamp":1604771339487,"uid":"S2BxNARp4Cfinttb1TK5mzAHPb13"}
eILcb0rPOZ0Rpeoym6uX => {"avatar":"https://firebadia&token=272cfbff-3fd7-4216-a6c3-09ed612eca3e","text":"Fjjfjffj","timestamp":1604395119914,"uid":"oTPw7q2jRWcE3F92U4aXeHHTHDg1"}
y7FN13SKWUDsWdKsGJiT => {"commentCount":3,"likeCount":5,"mood":"Yy","text":"Today is such
a joyful day because its Monday and at Mondays we dont do much at my work #blessed","timestamp":1592776918943,"userHandle":" NRQ2Ewhx76cWVqntRPLV1ygYHB73"}
The error message is telling you that check.data().id was undefined, not check. If you want to see the value of check.data().id, you should log exactly that.
What's likely happening here is that the document you have in hand here doesn't have a property called "id". That would explain why you're seeing this error message.
If you want to use startAfter() correctly, you should actually just pass the entire DocumentSnapshot object to it:
let snapshot = await firebase
.firestore()
.collection("posts")
.orderBy("timestamp", "desc")
.startAfter(check)
.limit(2)
.get();
For more information, see the documentation on the pagination APIs.

How to fetch firestore data via reference value in a key

here is the multiple document for offer and each offer cantains bidderId that is referenced to users collection and user id.
I want to fetch offer list contains user collection.
I am using angularfire and here is my code.
this.liveOffers=this.db.collection("offers",ref => ref.where('offerExpired', '==', 0).where('isStart', '==', 1)).snapshotChanges().pipe(
map(actions => actions.map(a => {
const data={} = a.payload.doc.data() as offer;
const id = a.payload.doc.id;
var bidder=this.db.doc(data.bidderId).snapshotChanges().subscribe(key=>{
console.log(key.payload.data());
});
return { id, ...data,bidder };
})) );
Here console.log(key.payload.data()); is logging the data for user but it can not bind with bidder variable and i can not use the user object in front end.
Please let me know how can I fetch the offer record with user details.
You need to use a combination of switchMap and combineLatest to get it done.
This is a pseudo-code approach
const temp = []
this.offers$ = this.db.collection().snapshotChanges().pipe(
map(auctions=>{
//we save all auctions in temp and return just the bidderId
return auctions.map(auction=>{
const data={} = a.payload.doc.data() as offer;
const id = a.payload.doc.id;
temp.push({id, ...data})
return data.bidderId
})
}),
switchMap(bidderIds=>{
// here you'll have all bidderIds and you need to return the array to query
// them to firebase
return combineLatest(bidderIds.map(bidderId=> return this.db.doc(bidderId)))
}),
map(bidders=>{
// here you'll get all bisders you'll have to set the bidder on each temp obj
// you saved previously
})
)
Make sure you import { combineLatest } from 'rxjs/operators' not 'rxjs'
I found a way. It is working. But I think it is bit big and there might be way to optimize it. Also it is node-js server API and not for the web (JS). Again there might be similar solution for the web (JS)
Once you get data from snapshot object there is _path key in the object returned by data which again have segments which is array and contain collection and ID
const gg = await firestore.collection('scrape').doc('x6F4nctCD').get();
console.log(JSON.stringify(gg.data(), null, 4));
console.log(gg.data().r._path.segments[0]);
console.log(gg.data().r._path.segments[1]);
const gg2 = await firestore
.collection(gg.data().r._path.segments[0])
.doc(gg.data().r._path.segments[1])
.get();
console.log(gg2.data());
{
"fv": {
"_seconds": 1578489994,
"_nanoseconds": 497000000
},
"tsnowpo": 1578489992,
"createdAt": {
"_seconds": 1578489992,
"_nanoseconds": 328000000
},
"r": {
"_firestore": {
"_settings": {
"libName": "gccl",
"libVersion": "3.1.0",
"servicePath": "firestore.googleapis.com",
"port": 443,
"clientConfig": {},
"scopes": [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/datastore"
]
},
"_settingsFrozen": true,
"_serializer": {},
"_projectId": "sss",
"_lastSuccessfulRequest": 1578511337407,
"_preferTransactions": false,
"_clientPool": {
"concurrentOperationLimit": 100,
"activeClients": {},
"terminated": false
}
},
"_path": {
"segments": [
"egpo",
"TJTHMkxOx1C"
]
}
}
}
egpo
TJTHMkxOx1C
{ name: 'Homeware' }

Issue with sending LiveChat messages via DDP in RocketChat

I am trying to use the DDP Realtime API to initiate a LiveChat conversation but I am facing issues.
https://rocket.chat/docs/developer-guides/realtime-api/livechat-api
I am doing all the steps as per the documentation. In the first API outcome, you can see that it saus numAgents: 2 and online: true. However when I try to send a message to the same department, it says: "Sorry, no online agents".
Is there a way to find out the problem?
Result of livechat:getInitialData
{ enabled: true,
title: 'xyz.com',
color: '#C1272D',
registrationForm: false,
room: null,
triggers: [],
departments:
[ { _id: 'CxCTgXL4csw3TcW6S',
enabled: true,
name: 'Support',
description: '',
numAgents: 2,
showOnRegistration: true,
_updatedAt: 2017-09-24T06:46:39.657Z } ],
allowSwitchingDepartments: true,
online: true,
offlineColor: '#666666',
offlineMessage: 'We are not online right now. Please leave us a message:',
offlineSuccessMessage: '',
offlineUnavailableMessage: '',
displayOfflineForm: true,
videoCall: true,
offlineTitle: 'Leave a message',
language: '',
transcript: false,
transcriptMessage: 'Would you like a copy of this chat emailed?' }
Result of livechat:registerGuest
{ userId: 'j65Cp5peeLJLYhWQi',
token: 'J8IpnpB1yN1AYtO0e0EzLhuaRhe0zaZkjHBAamsehSO' }
Result of Login
{ id: 'j65Cp5peeLJLYhWQi',
token: 'J8IpnpB1yN1AYtO0e0EzLhuaRhe0zaZkjHBAamsehSO',
tokenExpires: 2017-12-23T07:45:01.928Z }
Result of sendMessageLivechat
{ isClientSafe: true,
error: 'no-agent-online',
reason: 'Sorry, no online agents',
message: 'Sorry, no online agents [no-agent-online]',
errorType: 'Meteor.Error' }
These are the parameters I am sending to sendMessageLiveChat.
"_id" : "j65Cp5peeLJLYhWQi"
"rid" : "a_random_string"
"msg": "Hello"
"token" : "J8IpnpB1yN1AYtO0e0EzLhuaRhe0zaZkjHBAamsehSO"
Could someone help me?
This is how I called registerGuest.
ddpClient.call("livechat:registerGuest",[{"token":authToken,"name":"test1","email":"test2#gmail.com","department":department._id},25],function(err, info){
});
the token passed by me here is the admin's authToken
The ddpClient object is obtained using the DDP npm package.
I solved this by a combination of
setting the bot as livechat agent & manager at the same time (I've read that tip somewhere it might be nonsense)
in Admin -> Omnichannel -> routing I've set 'accept even when no agents are online' (since my bot was never online, bould it was replying when DMessaged) + 'assign bot agents to new conversations'
I've setup myself a livechat-manager + livechat-agent role, but stayed in a different department, that way I can takeover
The rocket chat live api docs are quite out of date, just got stream-room-messages working because of a random forum post. Generally, registerGuest works with very minimal parameters as well, namely a random, self generated token + a name.
Here's my code for the complete setup
async subscribeToLiveRoom(message){
var _self = this
// let initial = await this.api
// .call("livechat:getInitialData",[token])
// register
const token = this.randomString()
var guestUser = await this.api
.call(
'livechat:registerGuest',
[{
token: token,
name: _self.$auth.user.name
}]
)
.catch(console.error)
console.log('guest', guestUser.visitor.token)
this.setActiveGuest(guestUser)
var roomId = this.randomString()
this.setActiveRoom(roomId)
let msg = await this.api
.call(
'sendMessageLivechat',
[{
_id: _self.randomString(),
rid: roomId,
msg: message,
token: guestUser.visitor.token
}])
.catch(console.error)
try {
let liveStream = await this.$subscribe("stream-livechat-room",[
roomId,
{
"useCollection": true,
"args":[
{
"visitorToken": guestUser.visitor.token
}
]
}
])
this.msgLive = await this.find('stream-livechat-room')
} catch (e) {
console.log(e)
}
//
try {
var roomStream = await this.$subscribe("stream-room-messages",[
roomId,
{
"useCollection": true,
"args":[
{
"visitorToken": guestUser.visitor.token
}
]
}
])
console.log('roomstream')
var update = this.find('stream-room-messages')
} catch (e) {
console.log('an error occured', e)
}
console.log( this.msg)
},
async sendToLiveRoom(message, rId){
var _self = this
// let initial = await this.api
// .call("livechat:getInitialData",[token])
// register
let msg = await this.api
.call(
'sendMessageLivechat',
[{
_id: _self.randomString(),
rid: rId,
msg: message,
token: _self.guest.visitor.token
}])
.catch(console.error)
},
By the way, since it's not well documented, you will get room-messages in livechat rooms via subscribing to stream-room-messages while you get room status changes (like switched to another agent) by subscribing to stream-livechat-room

firebase - How to know which registration_id is bad/expired/deleted

So I am pushining notifications in a batch to multiple devices. I want to delete device GFCM tokens from my databse if they are not in firebase.
Test request:
{"registration_ids": ["fznIum-OIL0:APA91bE9n6gxqVEB3hR0On_TZqH_cOOO7rFyLE5MYbvKXUX3737IonXquZRoHeY1UJf20G4nrahz35p80X8PAPouviYvXgtekAzeDFuwaWyiPI1sFlN1d1wGp5OulXv9wUzHyegeZiih","dsasadadsasdasdasdasdefs","fjb0qTB9ACI:APA91bHvx0pSlq-NuQz-bU70DhL7BXAcd-DqT9YT0ZjYw7R_pkBmr8oe6XdNw8IPlU67d-rXMfRY3mybaO7K5GHo_NH7G-Ya1Ae2xxJP1JIbuuSYomz31y_MPQijFK8w-bZXQ26SWE09"],
"notification":{
"body":"Yoou have a new message from Alice"}}
And response:
{
"multicast_id": 7971310728176484096,
"success": 1,
"failure": 2,
"canonical_ids": 0,
"results": [
{
"error": "NotRegistered"
},
{
"error": "InvalidRegistration"
},
{
"message_id": "0:1481547993513035%4f9c20964f9c2096"
}
]
}
How to detect which registration_ids are bad/Not registered?
Thanks!
Okey, i think i figured it out.
"results": Returns responses/errors in the order you specified it in registration_ids
when you are sending push notification to any mobile,you can find in err that registartion_ids/token isbad /not registered/
var serverKey = 'sdasd';//server key
var fcm = new FCM(serverKey);
var token = "token";//token here
var message = {
to: token,
collapse_key: 'your_collapse_key',
notification: {title: 'hello', body: 'test'},
data: {my_key: 'my value', contents: "stackoverflow.com"}
};
fcm.send(message, function (err, response) {
if (err) {
console.log(err);//find here registration_ids are bad/Not registered?
} else {
console.log(response);
}
});
});

Resources