feat: allow defining signal type

this makes using especially the frontend API much usable as the signal
can be typed instead having plain json object to play around with.

Signed-off-by: Heikki Hellgren <heikki.hellgren@op.fi>
This commit is contained in:
Heikki Hellgren
2024-02-02 08:31:39 +02:00
parent 216fce4b2c
commit 1ab22c40e0
10 changed files with 65 additions and 41 deletions
+4 -5
View File
@@ -8,6 +8,7 @@ import { DiscoveryApi } from '@backstage/core-plugin-api';
import { IdentityApi } from '@backstage/core-plugin-api';
import { JsonObject } from '@backstage/types';
import { SignalApi } from '@backstage/plugin-signals-react';
import { SignalSubscriber } from '@backstage/plugin-signals-react';
// @public (undocumented)
export class SignalClient implements SignalApi {
@@ -23,12 +24,10 @@ export class SignalClient implements SignalApi {
// (undocumented)
static readonly DEFAULT_RECONNECT_TIMEOUT_MS: number;
// (undocumented)
subscribe(
subscribe<SignalType extends JsonObject = JsonObject>(
channel: string,
onMessage: (message: JsonObject) => void,
): {
unsubscribe: () => void;
};
onMessage: (message: SignalType) => void,
): SignalSubscriber;
}
// @public (undocumented)
+14 -12
View File
@@ -13,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { SignalApi } from '@backstage/plugin-signals-react';
import { SignalApi, SignalSubscriber } from '@backstage/plugin-signals-react';
import { JsonObject } from '@backstage/types';
import { DiscoveryApi, IdentityApi } from '@backstage/core-plugin-api';
import { v4 as uuid } from 'uuid';
type Subscription = {
channel: string;
callback: (message: JsonObject) => void;
callback: (message: any) => void;
};
const WS_CLOSE_NORMAL = 1000;
@@ -62,16 +62,16 @@ export class SignalClient implements SignalApi {
private reconnectTimeout: number,
) {}
subscribe(
subscribe<SignalType extends JsonObject = JsonObject>(
channel: string,
onMessage: (message: JsonObject) => void,
): { unsubscribe: () => void } {
onMessage: (message: SignalType) => void,
): SignalSubscriber {
const subscriptionId = uuid();
const exists = [...this.subscriptions.values()].find(
sub => sub.channel === channel,
);
this.subscriptions.set(subscriptionId, {
channel: channel,
channel,
callback: onMessage,
});
@@ -178,12 +178,14 @@ export class SignalClient implements SignalApi {
private handleMessage(data: MessageEvent) {
try {
const json = JSON.parse(data.data) as JsonObject;
if (json.channel) {
for (const sub of this.subscriptions.values()) {
if (sub.channel === json.channel) {
sub.callback(json.message as JsonObject);
}
const json = JSON.parse(data.data);
if (!json.channel) {
return;
}
for (const sub of this.subscriptions.values()) {
if (sub.channel === json.channel) {
sub.callback(json.message);
}
}
} catch (e) {