Hi! I'm banging my head against the wall trying t...
# help
p
Hi! I'm banging my head against the wall trying to get an ApolloApi stack to connect to a WebSocketApi stack, via a websocket, so I can send update notifications out when mutations have been called. For whatever reason, when I try to connect to the WebSocketApi stack it never gets to the point where it fires the onopen event (I'm using ws). Here's the code from my graph stack that's trying to connect and send a message to the websocket stack:
Copy code
export abstract class WebSocketClient {
  private static _websocket: WebSocket;

  public static Send(data: { message_kind: E_MessageKind, message_content: any}) {
    console.log(JSON.stringify(process.env.WEB_SOCKET_URL), "WEB SOCKET URL");
    try {
        WebSocketClient._websocket = new WebSocket(process.env.WEB_SOCKET_URL || "");
        WebSocketClient._websocket.onopen = () => {
          console.log("WS OPEN");
          WebSocketClient._websocket.send(JSON.stringify(data));
        }
        WebSocketClient._websocket.onclose = () => console.log("WS CLOSE");
        WebSocketClient._websocket.onerror = () => console.log("WS ERROR");
        WebSocketClient._websocket.onmessage = () => console.log("WS MESSAGE");
      } catch (err) {
      console.error(err);
      throw err;
    }
  }
}
None of the console.logs ever get triggered and there's no exception thrown. There's also no console.log fired from my websocket stack when this call is made, though it is from an angular app and from wscat. Anyone got any ideas how to fix it? I've got no error to dig into so I'm getting close to hitting a dead end...
I'm wondering if it's something to do with the lamba exiting before the websocket connection has been made, which would mean I need to somehow had async/await somewhere?
Yup, my guess was right. I changed the code to add a Promise around the websocket connection and that fixed it;
Copy code
export abstract class OnlineBookingNotifier {
  private static _webSocket: WebSocket;

  public static async Send(data: { message_kind: E_MessageKind, message_content: any}) {
    console.log(process.env.WEB_SOCKET_URL, "WEB SOCKET URL");
    try {
      OnlineBookingNotifier._webSocket = await OnlineBookingNotifier.Connect();
      OnlineBookingNotifier._webSocket.send(JSON.stringify(data));
    } catch (err) {
      console.error(err);
      throw err;
    }
  }

  private static async Connect() : Promise<any> {
    return new Promise((resolve, reject) => {
      const websocket = new WebSocket(process.env.WEB_SOCKET_URL || "");
      
      websocket.onopen = () => {
        console.log("WS OPEN");
        resolve(websocket);
      };

      websocket.onerror = (err) => {
        reject(err);
      }
    })
  }
}
I'll leave this here in case it helps anyone else though.
f
Ah I see. Glad u figured it out!