Gregivy / simpleddp

An easy to use DDP client library
MIT License
165 stars 19 forks source link

Handle Offline or Inaccessible Server #45

Open odesey opened 4 years ago

odesey commented 4 years ago

My issue is similar to #18 and #21

I have a react-native app and I connect to my development server like so:

let options = {
  endpoint: 'ws://<server address>:3000/websocket',
  SocketConstructor: ws,
  reconnectInterval: 5000,
  autoConnect: false,
  autoReconnect: false,
  maxTimeout: 3000
};

export const server = new simpleddp(options, [simpleDDPLogin]);
import { server } from 'some file'

connectToServer = () => {
  server
    .connect()
    .then(() => {
      console.log('server connected');  //never gets called
    })
    .catch(er => console.log('connection error', er));  //never gets called
}

If the Meteor server is running, everything works. If I stop the server, and attempt to load the App, the console.log() statements never get called.

I also tied the following:

connectToServer = async () => {
  console.log('connect to server next');
  try {
  await server.connect()
  console.log('CONNECTED?', server.connected); //never gets called
  } catch (error) {
     console.log('connection error:  ', error); //never gets called
   }
};

// some place else
connectToServer();

None of the server.on('error', ...) events are called as well.

How can I check if the server is available and connected?

Thanks.

malusiTowo commented 3 years ago

I am also in need of a way to detect if my server is down.

I have a list of servers and I would like to connect to one that is up and running.

I have taken a similar approach to @odesey.

Here is what I have done so far.

const getServer = () => {
  const serverUrls = [
        "wss://..../websocket",
        "wss://...../websocket",
  ];
  let Server: SimpleDDP | null = null;
  let isServerHealthy = false;

  serverUrls.map(async endpoint => {
    try {
      if (!Server?.connected) {
        const opts = {
          endpoint,
          SocketConstructor: ws,
          reconnectInterval: 500,
          autoConnect: false,
          autoReconnect: false
        };
        Server = new SimpleDDP(opts, [simpleDDPLogin]);
        await Server.connect()
        isServerHealthy = await Server?.call("healthcheck");

      }
      console.log("url", endpoint, isServerHealthy, Server?.connected); // never called

    } catch (err) {
      console.log("Error connect server", err); // never called
    }
  });

  console.log("final status", Server?.connected); // called

  return Server;
};

Also, none of the event callbacks are called.

if the last endpoint in my array is valid, then the connection is established and everything works.

Do you have any ideas on how I could accomplish this?

Thanks.