I am trying out SocketCluster for an app where I will need both RPC style as well as One way Event based communication. I am following the Basic Usage section https://socketcluster.io/docs/basic-usage/
If I include socket.procedure and socket.receiver in the same listener loop it won't invoke the event. I want to understand why it is like that.
Really appreciate any input that will clear-up the concept.
Thanks!
My Server Side/Node:
const http = require("http");
const finalHandler = require("finalhandler");
const socketCluster = require("socketcluster-server");
const serveStatic = require("serve-static");
let serve = serveStatic("public", {index: ["index.html"]});
let httpServer = http.createServer(function onfRequest(req, res) {
serve(req, res, finalHandler(req, res))
});
let agServer = socketCluster.attach(httpServer);(async () => {
for await (let {socket} of agServer.listener("connection")) {
// RPC
(async () => {
for await (let req of socket.procedure("customProc1")) {
console.log(`Received RPC request`);
req.end("Success");
}
})();
// Event (One Way)
(async () => {
for await (let data of socket.receiver("customEvent1")) {
console.log(`Received Invoke data: ${data}`);
}
})();
}
})()
httpServer.listen(8000, () => {
console.log(`Server Started On : ${new Date().getTime()}`);
});
On the Client side Index.html/JavaScript:
function fireAnEvent() {
socket.transmit("customEvent1", "My Data");
}
async function callRpc() {
await socket.invoke("customProc1", {greetings: "Hey there function!"});
}
Related
I am using converse.js 7.0.6 version. I am trying to set the subject topic button to be by default hidden, currently, it is visible by default. I have investigated I need to override this function toggleSubjectHiddenState, when I try to use _converse.api.user. I get an error TypeError: Cannot read properties of undefined (reading 'user')
This is how I tried, maybe I am doing wrong something.
export const addModifyHideTopicPlugin = () => {
window.converse.plugins.add('modify-hide-topic', {
overrides: {
ChatRoom: {
toggleSubjectHiddenState: async function () {
const _converse: any = this;
// const muc_jid = this.get('jid');
const jids = await _converse.api.user.settings.get(
'mucs_with_hidden_subject',
[],
);
return _converse.toggleSubjectHiddenState
.apply(_converse, arguments)
.then((response: any) => {
console.log(response, 'response');
return response;
});
},
},
},
});
};
This is the toggleSubjectHiddenState function I am trying to override because this function is handleing the show topic or hide topic.
async toggleSubjectHiddenState () {
const muc_jid = this.get('jid');
const jids = await api.user.settings.get('mucs_with_hidden_subject', []);
if (jids.includes(this.get('jid'))) {
api.user.settings.set('mucs_with_hidden_subject', jids.filter(jid => jid !== muc_jid));
} else {
api.user.settings.set('mucs_with_hidden_subject', [...jids, muc_jid]);
}
},
I am trying to do http post in protractor. The status of http.post sits in pending status and doesn't return any response.
I am calling a method in onPrepare function under specDone:
jasmine.getEnv().addReporter({
specDone: function(result) {
if (result.status == "failed") {
browser.getCapabilities().then(function(caps) {
var browserName = caps.get("browserName");
browser.takeScreenshot().then(function(png) {
var stream = fs.createWriteStream(
"./reports/screenshots/" +
browserName +
"-" +
result.fullName +
".png"
);
stream.write(new Buffer(png, "base64"));
stream.end();
});
});
}
new PortalData().PushDataToPortal("");
}
});
Below function in called from onPrepare, the API takes the parameter from body. I am using protractor-http-client package for API calls.
export class PortalData {
public PushDataToPortal(result) {
const http: HttpClient = new HttpClient();
const LogFilePathInSharedLocation =
"\\\\10.101.101.11\\temp\\DocStar\\Automation\\TestLogs\\Logs.txt";
http
.post(
someurl,
LogFilePathInSharedLocation,
{ "Content-Type": "application/x-www-form-urlencoded" }
)
.then((response: ResponsePromise) => {
console.log(response);
});
}
Please advise. Thanks!
I would suggest you use Http call in beforeAll instead of onPrepare.
You can try superagent or supertest npm modules:
Example for superagent
const superagent = require('superagent');
// callback
superagent
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
.set('X-API-Key', 'foobar')
.set('accept', 'json')
.end((err, res) => {
// Calling the end function will send the request
});
// promise with then/catch
superagent.post('/api/pet').then(console.log).catch(console.error);
// promise with async/await
(async () => {
try {
const res = await superagent.post('/api/pet');
console.log(res);
} catch (err) {
console.error(err);
}
})();
Example for supertest
const supertest = require('supertest');
const request = supertest(`${baseURL}`);
request.put('/test/sendlocal')
.send(profileAddressData.createData)
.set('Content-Type', 'application/json')
.set('Accept', '*/*')
.expect(200)
.end((err, res) => {
if (err) {
console.error('Error: ', err);
console.error('Response: ', res);
}
});
I'm using puppeteer to scrape page that has contents that change periodically and use express to present data in rest api.
If I turn on headless chrome to see what is being shown in the browser, the new data is there, but the data is not showing up in get() and http://localhost:3005/api-weather. The normal browser only shows the original data.
const express = require('express');
const server = new express();
const cors = require('cors');
const morgan = require('morgan');
const puppeteer = require('puppeteer');
server.use(morgan('combined'));
server.use(
cors({
allowHeaders: ['sessionId', 'Content-Type'],
exposedHeaders: ['sessionId'],
origin: '*',
methods: 'GET, HEAD, PUT, PATCH, POST, DELETE',
preflightContinue: false
})
);
const WEATHER_URL = 'https://forecast.weather.gov/MapClick.php?lat=40.793588904953985&lon=-73.95738513173298';
const hazard_url2 = `file://C:/Users/xdevtran/Documents/vshome/wc_api/weather-forecast-nohazard.html`;
(async () => {
try {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on("request", request => {
console.log(request.url());
request.continue();
});
await page.goto(hazard_url2, { timeout: 0, waitUntil: 'networkidle0' });
hazard = {
"HazardTitle": "stub",
"Hazardhref": "stub"
}
let forecast = await page.evaluate(() => {
try {
let forecasts = document.querySelectorAll("#detailed-forecast-body.panel-body")[0].children;
let weather = [];
for (var i = 0, element; element = forecasts[i]; i++) {
period = element.querySelector("div.forecast-label").textContent;
forecast = element.querySelector("div.forecast-text").textContent;
weather.push(
{
period,
forecast
}
)
}
return weather;
} catch (err) {
console.log('error in evaluate: ', err);
res.end();
}
}).catch(err => {
console.log('err.message :', err.message);
});
weather = forecast;
server.get('/api-weather', (req, res) => {
try {
res.end(JSON.stringify(weather, null, ' '));
console.log(weather);
} catch (err) {
console.log('failure: ', err);
res.sendStatus(500);
res.end();
return;
}
});
} catch (err) {
console.log('caught error :', err);
}
browser.close();
})();
server.listen(3005, () => {
console.log('http://localhost:3005/api-weather');
});
I've tried several solutions WaitUntil, WaitFor, .then and sleep but nothing seems to work.
I wonder if it has something to do with express get()? I'm using res.end() instead of res.send() is because the json looks better when I use res.end(). I don't really know the distinction.
I'm also open to using this reload solution. But I received errors and didn't use it.
I also tried waitForNavigation(), but I don't know how it works, either.
Maybe I'm using the wrong search term to find the solution. Could anyone point me in the right direction? Thank you.
I'm struggling with migrating a HAPI function that verifies a JWT token and then makes a database call using the decoded credentials.
The problem is that jwt.verify uses a callback, but Hapi and Hapi.MySQL2 have both been updated to use async functions
The main function is as follows
exports.LoadAuth = (req, h) => {
let token = req.headers.authorization.split(' ')[1]
VerifyToken(token, async function (err, decoded) {
if (!err) {
let sql = '#SELECT STATEMENT USING decoded.id'
const [data] = await mfjobs.query(sql, decoded.id)
let auids = []
data.forEach(function (ag) {
auids.push(ag.Name)
})
auids = base64(auids.toString())
return auids
} else {
return {message: 'Not Authorised'}
}
})
}
The VerifyToken function is as follows:
VerifyToken = (tok, done) => {
jwt.verify(tok, Buffer.from(secret, 'base64'), function (err, decTok) {
if (err) {
done(err)
} else {
done(null, decTok)
}
})
}
Debugging everything above works up to the point that the data should be returned to the front end. At which point I get an ERROR 500
I know that the issue is with the VerifyToken function as if I omit this and hard code the decoded.id into the query the correct data reaches the front end.
Any pointers?
You can convert your VerifyToken function to Promises.
let VerifyToken = (tok) => {
return new Promise((resolve, reject) => {
jwt.verify(tok, Buffer.from(secret, 'base64'), function (err, decTok) {
if (err) {
reject(err)
} else {
resolve(decTok)
}
})
});
}
Now you have a function that you can use with async await notation and internally checks jwt validation via callbacks.
Then we can slightly modify your controller as follows.
exports.LoadAuth = async (req, h) => {
let token = req.headers.authorization.split(' ')[1];
try {
let decoded = await VerifyToken(token);
let sql = '#SELECT STATEMENT USING decoded.id';
const [data] = await mfjobs.query(sql, decoded.id);
let auids = [];
data.forEach(function (ag) {
auids.push(ag.Name)
});
auids = base64(auids.toString());
return auids
} catch (e) {
return {message: 'Not Authorised'}
}
}
We just converted your handler function to async function, and we already have a VerifyToken function that returns a promise so, we can call it with the await operator.
If I am using code such as this (from: http://jaydata.org/blog/jaydata-and-angularjs-continued):
$scope.saveChanges = function () {
$scope.northwind.saveChanges()
.then(function () {
$scope.selectedProduct = null;
},function() {
$scope.northwind.stateManager.reset();
});
};
How do I catch any server-side business validation errors that the server may return?
This works:
$scope.saveChanges = function () {
$scope.ApplicationData.saveChanges()
.then(function () {
$scope.selectedToDo = null;
}, function (error) {
var xml = error.message,
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$ValidationResults = $xml.find("ValidationResults");
angular.forEach($ValidationResults, function (ValidationResult) {
angular.forEach(ValidationResult.childNodes, function (childNode) {
alert(childNode.childNodes[0].textContent);
});
});
$scope.ApplicationData.stateManager.reset();
});
};