MQTTPRESS is another Serverless Architecture using MQTT Broker.
+--------+
| MQTT |
+--------+
| | |
| | +--------------------------------------+
| | |
| +------------------+ |
| | |
+---------------+ +-------------------+ +------------------+
| Server Page | | Client Page (1) | | Client Page (2) |
+---------------+ +-------------------+ +------------------+
emulates this!
+---------------+ +---------------+
| Client Page |------Req----->| Server Page |
| (1) |<-----Res------| |
+---------------+ | |
| |
+---------------+ | |
| Client Page |------Req----->| |
| (2) |<-----Res------| |
+---------------+ +---------------+
const mqttpress = require("mqttpress");
const config = require("./config");
const debug = require("debug")("server");
const mqttname = `ws://${config.mqtt.host}:${config.mqtt.ports.ws}`;
const app = mqttpress();
// add handler #1
debug(`add handler to ${"news/#"}`);
app.hear("news/#", (ctx)=>{
debug(`hear: ${ctx.topic}, from: ${JSON.stringify(ctx.from)}, data: ${JSON.stringify(ctx.data)}`);
ctx.send({msg: `congrat ${ctx.data.winner} win!`});
});
// add handler #2
debug(`add handler to ${"project/+/news"}`);
app.hear("project/+/news", (ctx)=>{
debug(`hear: ${ctx.topic}, from: ${JSON.stringify(ctx.from)}, data: ${JSON.stringify(ctx.data)}`);
ctx.send({msg: `congrat ${ctx.data.loser} lose!`});
});
app.on("listening", ()=>{
debug(`listening ${app.id} on ${mqttname}`);
document.querySelector("#client_page").href = `./client.html?prefix=${prefix}`;
});
app.on("error", (err)=>{
console.error(err.stack);
});
// listen start
app.listen(mqttname);
const mqttpress = require("mqttpress");
const config = require("./config");
const debug = require("debug")("client");
const mqttname = `ws://${config.mqtt.host}:${config.mqtt.ports.ws}`;
const app = mqttpress();
app.on("connect", ()=>{
debug(`connected ${app.id} on ${mqttname}`);
// request #1
debug(`request: news/sports ${JSON.stringify({winner: "tigers"})}`);
app.send("news/sports", {winner: "tigers"}).then((data)=>{
debug(`response: ${JSON.stringify(data)}`);
}).catch((err)=>{
console.error(err.stack);
});
// request #2
debug(`request: project/sports/news ${JSON.stringify({loser: "giants"})}`);
app.send("project/sports/news", {loser: "giants"}).then((data)=>{
debug(`response: ${JSON.stringify(data)}`);
}).catch((err)=>{
console.error(err.stack);
});
});
// connecting
app.connect(mqttname);
% npm install mqttpress