@getanthill/datastore
Version:
Event-Sourced Datastore
71 lines (61 loc) • 1.69 kB
JavaScript
const MQTT = require('async-mqtt');
const client = MQTT.connect('tcp://localhost', {
protocolVersion: 5,
clean: true,
});
const doStuff = async () => {
console.log('Starting');
try {
client.on('message', function (topic, message) {
const entity = JSON.parse(message.toString());
console.log(topic, entity);
if (topic.startsWith('ds/accounts/created/success')) {
// client.end();
client.publish(
`ds/accounts/updated/${entity.account_id}`,
JSON.stringify({
firstname: 'Bernard',
}),
{
properties: {
userProperties: {
authorization: 'token',
},
},
},
);
}
if (topic === 'ds/accounts/updated/{account_id}/success') {
client.end();
}
if (topic === 'ds/accounts/patched/{account_id}/success') {
client.end();
}
});
await client.subscribe('$share/group/ds/accounts/#');
await client.publish(
'ds/accounts/created/request',
JSON.stringify({
firstname: 'Alice',
email: `alice+${(Math.random() * 1e12).toFixed(0)}@doe.org`,
auth: 'auth',
}),
{
properties: {
userProperties: {
authorization: 'token',
},
},
},
);
// This line doesn't run until the server responds to the publish
// await client.end();
// This line doesn't run until the client has disconnected without error
console.log('Done');
} catch (e) {
// Do something about it!
console.log(e.stack);
process.exit();
}
};
client.on('connect', doStuff);