DenoDDeno
Powered by
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" });
/**
 * 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" });
Deno banner
DenoJoin
Chat about Deno, a modern runtime for JavaScript and TypeScript.
20,934Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Multiple kv connections in deno deploy
Le RutabagaLLe Rutabaga / help
11mo ago
Failed deployment Deno Deploy
ssimonlpSssimonlp / help
16mo ago
Audit KV data in deno deploy
foobarFfoobar / help
2y ago
Deno deploy
TallesTTalles / help
7mo ago