foobarF
Denoβ€’2y agoβ€’
7 replies
foobar

Share a data between multiple instances Deno Deploy

Hi,

I want to share data between multiple instance.

My first instance create a key. Others new instances have to get the original key from first instance.

I use BroadcastChannel to do it. But it relies on the strong assumption that the first instance can't dissapear ?

Is it true ?

Or do you have a more elegant way to do it (kv ?) ?

/**
 * Channel for broadcasting key
 */
const channel = new BroadcastChannel("KEY");

let firstInstance = true;
// all reload generate a new key
let key = generateKey()

channel.onmessage = async (event: MessageEvent<Message>) => {
  const message = event.data;
  if (message.nature === "newinstance" && firstInstance) {
    // only first instance send key
    // QUESTION : can first instance disappear
    channel.postMessage({ nature: "key", data: key });
  }
  if (message.nature === "key" && firstInstance) {
    // only last instance change
    key = message.data;
    // it is a new instance
    firstInstance = false;
  }
};

/**
 * All instance post the message
 * if 1 instance => no post
 * if 2nd instance => only 1st instance receive message => send key
 * if 3rd instance => only 1st instance send message because 2nd instance has firstInstance = false
 */
channel.postMessage({ nature: "newinstance" });
Was this page helpful?