TypeScript

by Ahmad Baktash Hayeri

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/pusher/8.0.1/pusher.min.js"></script>
<div id="app"></div>
<h1 id="status">
  Idle
</h1>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  text-align: center;
}

#status {
  border: 2px solid green;
  height: 40px;
  color: white;
}

TypeScript

interface Person {
  firstName: string;
  lastName:  string;
}

function greeter(person: Person) {
  return "Hello, " + person.firstName + " " + person.lastName;
}

let user = {
	firstName: "Malcolm",
  lastName:  "Reynolds"
};

document.querySelector("#app").innerHTML = greeter(user);


let pusher;

const status = document.querySelector("#status");

const recreatePusher = function () {
console.log('re/createPusher....');
  pusher = new Pusher('appKey', {
    wsHost: 'sockets.local.community.check24-test.de',
    wsPort: 6001,
    forceTLS: false,
    enabledTransports: ['ws', 'wss'],
    cluster: '',
    channelAuthorization: {
      endpoint:
        'https://api.local.community.check24-test.de/chat/notifications/auth',
      transport: 'ajax',
      params: {
        user_id: 15,
      },
    },
  });
  pusher.subscribe('presence-user-15').bind('message-created', data => {
    console.log(data);
    presentor.innerHTML = data?.message?.content;
  });

  pusher.connection.bind('state_change', function (states) {
    console.log(states);
    // states = {previous: 'oldState', current: 'newState'}
    document.querySelector("#status").innerHTML = states.current;
    let interval = null;
    if (states.current === 'failed') {
    console.log('****** failed ******')
      interval = setInterval(() => reconnect(pusher), 2000);
    }
    if (states.current === "connected") {
    	 clearInterval(interval);
    }
  });
};

function reconnect(pusher: Pusher) {
console.log('reconnecting....')
document.querySelector("#status").innerHTML = "Reconnecting...";
	        pusher.connection.connect();
}

recreatePusher();