Hi, and welcome to the forum!
I sort of see what you are doing. I’ll try to rewrite your code to make it work.
But just one note first: Events are always sent on a resource/model (eg. example.model
in your case). So, you can see example.model as your event “channel”.
And to trigger the event, I would recommend a call request instead. In REST terms, think of it as using POST instead of GET to trigger the event. GET requests can be cached and such, causing the trigger never to happen.
//server.js
// This looks good. Nothing changed here.
nats.subscribe("get.example.model", (req, reply) => {
nats.publish(
reply,
JSON.stringify({ result: { model: { message: "Hi, there!" } } })
);
});
// Make sure you also handle access requests.
// This one gives anyone access to get example.model,
// and anyone can call any method (and trigger happy events :) )
nats.subscribe("access.example.model", (req, reply) => {
nats.publish(
reply,
JSON.stringify({ result: { get: true, call: "*" } })
);
});
// Instead of get, we add a call method to "example.model" and call it "trigger"
nats.subscribe("call.example.model.trigger", (req, reply) => {
nats.publish(
"event.example.model.happy", // Send the "happy" event on "example.model"
JSON.stringify({
message: "i'm happy",
})
);
// Reply with a result. This means the trigger call went well.
nats.publish(
reply,
JSON.stringify({ result: "Happiness is triggered!" })
);
});
//express.js
app.get("/", (req, res) => {
// Assuming client is a ResClient instance, we call the trigger method instead of doing a get request
// Does express.js have access to NATS?
// Then you can sent the trigger call directly over NATS, instead of through Resgate.
client
.call("example.model", "trigger")
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
res.send("Hello World!");
});
//vuejs
mounted() {
this.client = new ResClient(`ws://localhost`);
this.client.get("example.model").then(model => {
console.log(model);
// We listen to happy events on the model.
model.on("happy", res => {
console.log("Happy event: ", res);
})
});
// We cannot listen to events directly on the client.
// Events are always sent on resources.
// This client.on method is just for listening to client errors and such.
//this.client.on("example.happy", res => {
// console.log(res);
//});
}
Hope that clear things up.
Best regards,
Samuel