in my code below i'm trying to check if the entered email is NOT exists in the API data this.users.email
but it giving me error: can't read email of undefined.However, when i console.log(this.users) i can see all my data , but when i console.log(this.users.email) it giving me undefined, any idea on how to solve it?
export default {
data() {
return {
error: "",
message:"",
users:[],
Reset: false,
login: {
email: "",
password: "",
},
SendEmail:{
email:"",
}
};
},
methods: {
Submit(){
try {
questionService.RequestResetPassword(this.SendEmail).then((response) => {
console.log(response);
});
}
catch (e) { if(!this.sendEmail.email.includes(this.users.email)){ //error here
this.error="enter an existing email";
}}
}
},
mounted: function () {
questionService.getAllUsers().then((jsonData) => {
this.users = jsonData.data.response;
console.log(this.users) // can appear properly
console.log(this.users.email) //undefined
})}
};
I have a list of contacts where I can add a new contact. As soon a new contact is added, I need to show it on the list of contacts without using refetchQueries. I tried to do this watching on the apollo documentation
addContact(
data: ContactInputData
): ContactPayload
type ContactPayload {
status: Int!
error: ErrorData
data: ContactResponseData
}
type ContactResponseData {
id: String!
}
type ContactInputData {
country: String!
address: String!
company: String!
number: String!
name: String!
email: String!
visibility: Boolean
}
// list of contacts
contacts: ContactListPayload!
type ContactListPayload {
status: Int!
error: ErrorData
data: [Client]!
}
type Client {
id: ID!
email: String!
number: String!
visibility: String!
client_id: String!
country: String!
profile_picture: String!
tags: [Tag]!
notes: [Note]!
}
const formSubmit = async (val: AddContactInputs) => {
console.log('val', val);
const response = await addContact({
variables: {
data: {
...val,
country: '',
address: '',
company: ''
}
},
optimisticResponse: {
__typename: 'Mutation',
addContact: {
__typename: 'ContactPayload',
data: {
// not sure the shape of data
}
}
},
update: (client, { data: { addContact } }) => {
console.log('client', client);
console.log('addContact', addContact);
// if (addContact.status === 201) {}
// read data from our cache
const data: any = client.readQuery({ query: CONTACTS });
console.log('data from cache', data);
// write our data back to cache with the new contacts in it
const newData: any = {
...data,
contacts: { ...data.contacts, data: [...data.contacts.data, addContact.data] }
};
console.log('newData to write', newData);
client.writeQuery({ query: CONTACTS, data: newData });
}
});
console.log('response', response)
};
However, I am confused on the shape of data on optimisticResponse. If you see addContact response model, it just sends id to me. How am i supposed to update the list of contacts where it mainly needs name, email, number?
What I can do in order to fix my problem? I'm a new newbie in javascript and any recomendations or advices could be helpful to me.
var user = {
username: "Andrey",
password: "JavaScript"
},
{
username: "Max",
password: "12345"
},
{
username: "Pasha",
password: "OWL"
};
var database = [user];
var newsfeed = [
{
username: "Bobby",
timeline: "DOOOOOOG!",
},
{
username: "Max",
timeline: "CAAAAT!",
},
{
username: "Lida",
timeline: "John Ceeeenaaaa!",
}
];
var userNamePrompt = prompt("Your Username?");
var passwordPrompt = prompt("Your password?");
function isUserValid(Name, Pass){
for (var i=0; i<database.length; i++){
if (database[i].username === Name &&
database[i].password === Pass) {
return true;
}
}
return false;
}
function SignIn (Name, Pass){
if (isUserValid(Name, Pass)) {
console.log(newsfeed);
}
else {
alert("Sorry smt went wrong!");
}
}
SignIn (userNamePrompt, passwordPrompt);
If the code is working correctly, i should get back an array with a newsfeed, but instead im getting:
Invalid destructuring assignment target
You wrote: var user = { property }{ property }{ property } which doesn't work. This is probably what you meant ( also skips the var database = [ user ]; assignment):
var database = [
{
username: "Andrey",
password: "JavaScript"
},
{
username: "Max",
password: "12345"
},
{
username: "Pasha",
password: "OWL"
};
]
I am using neo4j javascript driver. I am able to run a single query. But I can't able to create multiple nodes with properties. Can anyone tell me how to do?
session
.run('CREATE (fit1:fitproto {title:"Relaince Industries",name:"Rajni",country:"India",email:"rajni#gmail.com"}),(fit2:fitproto {title:"State Bank of India",name:"Rajni",country:"India",email:"rajni#gmail.com"}) RETURN(fitproto)')
.subscribe({
onNext: function (record) {
const node = record.get(1);
console.log(node);
record.forEach(function (res) {
console.log(res.Node);
});
res.send(record.get(0));
},
onCompleted: function () {
session.close();
},
onError: function (error) {
console.log(error);
}
});
You need to pass an array of properties for new nodes through parameters. Then UNWIND it, create a node and SET properties:
session
.run(`
UNWIND $propsArray as props
CREATE (fit:fitproto) SET fit = props
RETURN fit
`, {
propsArray: [{
title: "Relaince Industries",
name: "Rajni",
country: "India",
email: "rajni#gmail.com"
},
{
title: "State Bank of India",
name: "Rajni",
country: "India",
email: "rajni#gmail.com"
}
]
})
.subscribe({
onNext: function(record) {
console.log(record.get('fit'));
},
onCompleted: function() {
session.close();
},
onError: function(error) {
console.log(error);
}
});
I want to create a Rocket Chat client to subscribe to a channel through browser using Realtime API. Documentation here does not provide step by step procedure. Please let me know how to achieve it.
Links to any documentation would be very helpful.
I had less idea about websockets when I asked this question. For the benefit of all, mentioning the steps I followed.
Open websocket
var rocketChatSocket = new WebSocket("ws://locahost:3000/websocket");
Connect
var connectRequest = {
"msg": "connect",
"version": "1",
"support": ["1", "pre2", "pre1"]
}
rocketChatSocket.send(JSON.stringify(connectRequest));
After connecting, keep responding with {"msg":"pong"} for {"msg":"ping"} from server.
Login with authToken received by calling this API
var loginRequest = {
"msg": "method",
"method": "login",
"id": "42",
"params": [
{ "resume": "authToken" }
]
}
rocketChatSocket.send(JSON.stringify(loginRequest));
Subscribe to room
var subscribeRequest = {
"msg": "sub",
"id": "unique-id",
"name": "stream-notify-room",
"params":[
"room-id/event",
false
]
}
rocketChatSocket.send(JSON.stringify(subscribeRequest));
Send message
var request={
"msg": "method",
"method": "sendMessage",
"id": "42",
"params":
[
{
"_id": "message-id",
"rid": "room-id",
"msg": "Hello World!"
}
]
}
rocketChatSocket.send(JSON.stringify(request));
Thank you Mr Nandan,we were able to use your answer to build fully custom client to talk with the rocket chat real time api
here's the link for future people who will want the same thing
https://github.com/lalosh/rocketchat.realTimeAPI.customClient/blob/master/main.js
and here's the code in case you want to check immediately
/*
Rocket Chat Real Time API Custom Client
even though this code works great I don't know what exactly each event we listen for is doing
you can go back to rocket chat real time api for further declarations
we were able to write this code after we test real normal use case of livechat in a web page
and we listen for WebSocket connection inside the browser Network tab(by filtering ws(WebSocket) connections)
*/
let socket = new WebSocket('ws://[rocketChatIP]:[rocketChatPort]/websocket');
//note messageCount is incremented with every message
//but it can works even if you didn't change it
let messagesCount = 1;
// the variables chatToken and chatRoomId are very important
// and they are the identifier to the room(the whole chat) you are using
// if you want to get access to the chat again you need these two variables tokens
let chatToken = generateHash(17);
let chatRoomId = generateHash(17);
let subId = generateHash(17);
let roomSubId = generateHash(17);
let streamLivechatchatRoomId = generateHash(17);
let steamNotifyRoomSubId = generateHash(17);
let name = 'user28';
let email = 'user28#gmail.com';
let guestName = 'guest';
// listen to messages passed to this socket
socket.onmessage = function(e) {
let response = JSON.parse(e.data);
console.log('response', response);
// you have to pong back if you need to keep the connection alive
// each ping from server need a 'pong' back
if (response.msg == 'ping') {
console.log('pong!');
socket.send(JSON.stringify({
msg: 'pong'
}));
return;
}
// here you receive messages from server //notive the event name is: 'stream-room-messages'
if (response.msg === 'changed' && response.collection === 'stream-room-messages') {
console.log('msg received ', response.fields.args[0].msg, 'timestamp ', response.fields.args[0].ts.$date, 'from ' + response.fields.args[0].u.name);
return;
}
// receive all messages which will only succeed if you already have messages
// in the room (or in case you send the first message immediately you can listen for history correctly)
if (response.msg === 'result' && response.result) {
if (response.result.messages) {
let allMsgs = response.result.messages;
console.log('-----previous msgs---------------');
allMsgs.map(x => console.log(x))
console.log('---------------------------------')
}
}
}
//////////////////////////////////////////////
// steps to achieve the connection to the rocket chat real time api through WebSocket
//1 connect
let connectObject = {
msg: 'connect',
version: '1',
support: ['1', 'pre2', 'pre1']
}
setTimeout(() => {
socket.send(JSON.stringify(connectObject));
}, 1000)
//////////////////////////////////////////////
//2 getInitialData
let getInitialDataObject = {
msg: 'method',
method: 'livechat:getInitialData',
params: [String(chatToken), null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(getInitialDataObject));
}, 2000)
//////////////////////////////////////////////
//3 loginByToken
let loginByToken = {
msg: 'method',
method: 'livechat:loginByToken',
params: [String(chatToken)],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(loginByToken));
}, 3000)
//////////////////////////////////////////////
//4 subscribtion
let subObj = {
msg: 'sub',
id: subId,
name: 'meteor.loginServiceConfiguration',
params: []
}
setTimeout(() => {
socket.send(JSON.stringify(subObj));
}, 4000)
//////////////////////////////////////////////
//5 register // you may skip this if you alredy registered
// or you can re use it even though you are registered.. no problems
// the crucial part is the `chatToken` and later on the `chatRoomId`
let registerObj = {
msg: 'method',
method: 'livechat:registerGuest',
params: [{
token: chatToken,
name: name,
email: email,
'department': null
}],
id: String(messagesCount++),
};
setTimeout(() => {
socket.send(JSON.stringify(registerObj));
}, 5000)
//////////////////////////////////////////////////
//6 stream-notify-room
let streamNotifyObj = {
msg: 'method',
method: 'stream-notify-room',
params: [
'null/typing',
guestName, true, {
token: String(chatToken)
}
],
id: String(messagesCount++)
};
setTimeout(() => {
socket.send(JSON.stringify(streamNotifyObj));
}, 6000)
//////////////////////////////////////////////////
//7 send a msg //use the same method to send your own messages again when you are all connected
let myMsg = {
msg: 'method',
method: 'sendMessageLivechat',
params: [{
_id: String(generateHash(17)),
rid: chatRoomId,
msg: 'first message',
token: String(chatToken),
}, null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(myMsg));
}, 7000)
//////////////////////////////////////////////////
//8 send userPresence
let UserPresence = {
msg: 'method',
method: 'UserPresence:connect',
params: [
String(chatToken),
{
visitor: String(chatToken)
}
],
id: String(messagesCount++)
}
setTimeout(() => {
socket.send(JSON.stringify(UserPresence));
}, 8000)
/////////////////////////////////////////////////
//9 loadHistory of old messages
let loadHistory = {
msg: 'method',
method: 'livechat:loadHistory',
params: [{
token: String(chatToken),
rid: String(chatRoomId),
ts: {
$date: new Date().getTime()
}, //current point of time
limit: 50
}],
id: String(messagesCount++)
};
setTimeout(() => {
socket.send(JSON.stringify(loadHistory));
}, 9000)
/////////////////////////////////////////////////
// 10 stream-room-messages
// listen to all received messages
let roomMessagesSub = {
msg: 'sub',
id: String(roomSubId),
name: 'stream-room-messages',
params: [
String(chatRoomId),
{
useCollection: false,
args: [{
visitorToken: String(chatToken)
}]
}
]
};
setTimeout(() => {
socket.send(JSON.stringify(roomMessagesSub));
}, 10000)
/////////////////////////////////////////////////
// 11 getAgentData
let getAgentData = {
msg: 'method',
method: 'livechat:getAgentData',
params: [{
roomId: String(chatRoomId),
token: String(chatToken),
}],
id: String(messagesCount++)
}
setTimeout(() => {
socket.send(JSON.stringify(getAgentData));
}, 11000)
/////////////////////////////////////////////////
//12 stream-livechat-room
let streamLivechatRoom = {
msg: 'sub',
id: String(streamLivechatchatRoomId),
name: 'stream-livechat-room',
params: [
String(chatRoomId),
{
useCollection: false,
args: [{
'visitorToken': String(chatToken)
}]
}
]
}
setTimeout(() => {
socket.send(JSON.stringify(streamLivechatRoom));
}, 12000)
//////////////////////////////////////////
//13 stream-notify-room
let steamNotifyRoomSub = {
msg: 'sub',
id: String(steamNotifyRoomSubId),
name: 'stream-notify-room',
params: [
`${String(chatRoomId)}/typing`,
{
useCollection: false,
args: [{
token: String(chatToken)
}]
}
]
}
setTimeout(() => {
socket.send(JSON.stringify(steamNotifyRoomSub));
}, 13000)
//////////////////////////////////////
//14 userpresence 2
let UserPresence2 = {
msg: 'method',
method: 'UserPresence:online',
params: [String(chatToken)],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(UserPresence2));
}, 14000)
//////////////////////////////////////
//use it to send new messages
function sendNewMsg(msg, messagesCount) {
let myMsg = {
msg: 'method',
method: 'sendMessageLivechat',
params: [{
_id: String(generateHash(17)),
rid: chatRoomId,
msg: String(msg),
token: String(chatToken),
}, null],
id: String(messagesCount++),
}
setTimeout(() => {
socket.send(JSON.stringify(myMsg));
}, 500);
}
function generateHash(targetLength) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < targetLength; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
If you like to use an open source library for this purpose, here is one https://github.com/inf3cti0n95/Rocket.Chat.RealTime.API.RxJS
Here is the sample code:
import { RealTimeAPI } from "rocket.chat.realtime.api.rxjs";
const realTimeAPI = new RealTimeAPI("wss://demo.rocket.chat/websocket");
realTimeAPI.keepAlive();
const auth = realTimeApi.login(USERNAME, PASSWORD);
//Subscribe to messages and errors
auth.subscribe(
(data) => console.log(data),
(err) => console.log(err),
() => console.log('completed'));
//Subscribe to a specific channel, identified by roomId
realtimeAPI.sendMessage({
msg: 'sub',
id: '<a unique Id for subscription>',
name: 'stream-room-messages',
params: [roomId, false],
});