1
+ import ServerStopped from '../models/ServerStopped' ;
2
+ import * as Nats from 'nats' ;
3
+ import {
4
+ ErrorCode ,
5
+ NatsTypescriptTemplateError
6
+ } from '../NatsTypescriptTemplateError' ;
7
+ /**
8
+ * Module which wraps functionality for the `v0/rust/servers/{server_id}/events/stopped` channel
9
+ * @module v0RustServersServerIdEventsStopped
10
+ */
11
+ /**
12
+ * Internal functionality to setup subscription on the `v0/rust/servers/{server_id}/events/stopped` channel
13
+ *
14
+ * @param onDataCallback to call when messages are received
15
+ * @param nc to subscribe with
16
+ * @param codec used to convert messages
17
+ * @param server_id parameter to use in topic
18
+ * @param options to subscribe with, bindings from the AsyncAPI document overwrite these if specified
19
+ */
20
+ export function subscribe (
21
+ onDataCallback : (
22
+ err ? : NatsTypescriptTemplateError ,
23
+ msg ? : ServerStopped , server_id ? : string ) => void ,
24
+ nc : Nats . NatsConnection ,
25
+ codec : Nats . Codec < any > , server_id : string ,
26
+ options ? : Nats . SubscriptionOptions
27
+ ) : Promise < Nats . Subscription > {
28
+ return new Promise ( async ( resolve , reject ) => {
29
+ let subscribeOptions : Nats . SubscriptionOptions = {
30
+ ...options
31
+ } ;
32
+ try {
33
+ let subscription = nc . subscribe ( `v0.rust.servers.${ server_id } .events.stopped` , subscribeOptions ) ;
34
+ ( async ( ) => {
35
+ for await ( const msg of subscription ) {
36
+ const unmodifiedChannel = `v0.rust.servers.{server_id}.events.stopped` ;
37
+ let channel = msg . subject ;
38
+ const serverIdSplit = unmodifiedChannel . split ( "{server_id}" ) ;
39
+ const splits = [
40
+ serverIdSplit [ 0 ] ,
41
+ serverIdSplit [ 1 ]
42
+ ] ;
43
+ channel = channel . substring ( splits [ 0 ] . length ) ;
44
+ const serverIdEnd = channel . indexOf ( splits [ 1 ] ) ;
45
+ const serverIdParam = "" + channel . substring ( 0 , serverIdEnd ) ;
46
+ let receivedData : any = codec . decode ( msg . data ) ;
47
+ onDataCallback ( undefined , ServerStopped . unmarshal ( receivedData ) , serverIdParam ) ;
48
+ }
49
+ console . log ( "subscription closed" ) ;
50
+ } ) ( ) ;
51
+ resolve ( subscription ) ;
52
+ } catch ( e : any ) {
53
+ reject ( NatsTypescriptTemplateError . errorForCode ( ErrorCode . INTERNAL_NATS_TS_ERROR , e ) ) ;
54
+ }
55
+ } )
56
+ }
0 commit comments