Repository navigation
Expand file tree
/
Copy pathnodejs-client.js
More file actions
164 lines (146 loc) · 4.29 KB
/
Copy pathnodejs-client.js
File metadata and controls
164 lines (146 loc) · 4.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/**
* Example: Sending events to pagingWrick from Node.js apps
*
* Use this in your stockeroo, sentimentAnalyzer, or any Node.js app
*/
const { ServiceBusClient } = require('@azure/service-bus');
const { DefaultAzureCredential } = require('@azure/identity');
/**
* PagingWrick client for sending events
*/
class PagingWrickClient {
constructor(serviceBusNamespace) {
// Use DefaultAzureCredential for managed identity
// Or use connection string for local development
this.credential = new DefaultAzureCredential();
this.fullyQualifiedNamespace = serviceBusNamespace; // e.g., "sb-pagingwrick-dev-xxx.servicebus.windows.net"
this.queueName = 'events';
}
/**
* Send an event to pagingWrick
* @param {Object} event - The event to send
* @param {string} event.source - Your app name (e.g., 'stockeroo')
* @param {'high'|'low'} event.severity - Event severity/priority
* @param {string} event.message - Human-readable message
* @param {Object} [event.metadata] - Optional additional data
*/
async sendEvent(event) {
const client = new ServiceBusClient(this.fullyQualifiedNamespace, this.credential);
const sender = client.createSender(this.queueName);
try {
const message = {
body: {
source: event.source,
severity: event.severity,
message: event.message,
timestamp: new Date().toISOString(),
metadata: event.metadata || {}
}
};
await sender.sendMessages(message);
console.log(`Event sent to pagingWrick: ${event.severity} - ${event.message}`);
} catch (error) {
console.error('Failed to send event to pagingWrick:', error);
throw error;
} finally {
await sender.close();
await client.close();
}
}
/**
* Convenience method for high-severity events
*/
async sendHighSeverity(source, message, metadata = {}) {
return this.sendEvent({
source,
severity: 'high',
message,
metadata
});
}
/**
* Convenience method for low-severity events
*/
async sendLowSeverity(source, message, metadata = {}) {
return this.sendEvent({
source,
severity: 'low',
message,
metadata
});
}
}
// Export for use in other modules
module.exports = { PagingWrickClient };
// ============================================
// EXAMPLE USAGE
// ============================================
// Example 1: Initialize the client
const pagingWrick = new PagingWrickClient('sb-pagingwrick-dev-xxx.servicebus.windows.net');
// Example 2: Send a high-severity alert from stockeroo
async function stockPriceAlert() {
await pagingWrick.sendHighSeverity(
'stockeroo',
'AAPL stock price dropped 15% in the last hour!',
{
stockSymbol: 'AAPL',
currentPrice: 145.50,
previousPrice: 171.20,
percentChange: -15.0
}
);
}
// Example 3: Send a low-severity notification
async function dailySummary() {
await pagingWrick.sendLowSeverity(
'stockeroo',
'Daily portfolio summary: +2.3% overall',
{
totalValue: 50000,
percentChange: 2.3
}
);
}
// Example 4: Error alerts from sentimentAnalyzer
async function sentimentError() {
await pagingWrick.sendHighSeverity(
'sentimentAnalyzer',
'Failed to process batch - API rate limit exceeded',
{
errorCode: 'RATE_LIMIT',
batchSize: 100,
retryAfter: 3600
}
);
}
// Example 5: Integration in Express.js route
/*
const express = require('express');
const app = express();
app.post('/api/stock/alert', async (req, res) => {
try {
const { symbol, price, alert } = req.body;
await pagingWrick.sendHighSeverity(
'stockeroo',
`Alert for ${symbol}: ${alert}`,
{ symbol, price }
);
res.json({ success: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
*/
// Example 6: Try-catch wrapper for non-critical notifications
async function safeSendNotification(severity, message, metadata) {
try {
if (severity === 'high') {
await pagingWrick.sendHighSeverity('yourapp', message, metadata);
} else {
await pagingWrick.sendLowSeverity('yourapp', message, metadata);
}
} catch (error) {
// Don't let notification failures break your app
console.error('Notification failed (non-critical):', error);
}
}