Skip to content
Snippets Groups Projects
subscribe.ts 1.11 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { CallbackOptions, MakeFn, SubscribeRecipe } from "../../types";
    
    
    const subscriptionPath = "Device.LocalAgent.Subscription.";
    
    
    Marin Karamihalev's avatar
    Marin Karamihalev committed
    const make: MakeFn =
      (call, on): SubscribeRecipe =>
      async (opts, callback) => {
        const id = "NOTIFY@" + (opts.id || uniq());
        const refList = Array.isArray(opts.reference)
          ? opts.reference.join(",")
          : opts.reference;
    
    Marin Karamihalev's avatar
    Marin Karamihalev committed
        const newSubPath = await call("ADD", {
          path: subscriptionPath,
          value: {
            Enable: true,
            ID: id,
            NotifType: opts.notif,
            NotifRetry: "retry" in opts ? opts.retry : true,
            ReferenceList: refList,
            Persistent: false,
          },
        });
    
        // from https://usp.technology/specification/07-index-messages.html#sec:responses-and-retry
    
        const respond = () => call("NOTIFY_RESP", { subscriptionId: id });
        const clear = on(id, (msg, fullMsg, opts) => {
          opts?.sendResp && respond();
          callback(msg, fullMsg);
    
    Marin Karamihalev's avatar
    Marin Karamihalev committed
        });
        return () => {
          clear();
          return call("DELETE", { paths: newSubPath });
        };
      };
    
    
    export default {
      name: "subscribe",
      make,
    };