Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions src/plugin/settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { IDisposable, JsonObject } from "@elgato/utils";
import { withResolvers } from "@elgato/utils";
import { randomUUID } from "node:crypto";

import type { DidReceiveGlobalSettings, DidReceiveSettings } from "../api/index.js";
Expand All @@ -8,6 +9,8 @@ import { ActionEvent } from "./events/action-event.js";
import { DidReceiveGlobalSettingsEvent, type DidReceiveSettingsEvent } from "./events/index.js";
import { requiresVersion } from "./validation.js";

const REQUEST_TIMEOUT = 15 * 1000; // 15s

let __useExperimentalMessageIdentifiers = false;

export const settings = {
Expand Down Expand Up @@ -41,14 +44,29 @@ export const settings = {
* @returns Promise containing the plugin's global settings.
*/
getGlobalSettings: <T extends JsonObject = JsonObject>(): Promise<T> => {
return new Promise((resolve) => {
connection.once("didReceiveGlobalSettings", (ev: DidReceiveGlobalSettings<T>) => resolve(ev.payload.settings));
connection.send({
event: "getGlobalSettings",
context: connection.registrationParameters.pluginUUID,
id: randomUUID(),
});
const id = randomUUID();
const { promise, resolve, reject } = withResolvers<T>();

const timeoutId = setTimeout(() => {
listener.dispose();
reject(new Error("getGlobalSettings timed out"));
}, REQUEST_TIMEOUT);

const listener = connection.disposableOn("didReceiveGlobalSettings", (ev: DidReceiveGlobalSettings<T>): void => {
if (ev.id === id) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This id check can be removed; with global settings being shared, it's safe to assume that any didReceiveGlobalSettings event can fulfil any-and-all pending promises.

For request completeness, the id should still be sent with the request, but needn't be checked when receiving the global settings, e.g. the following is fine:

connection.send({
		event: "getGlobalSettings",
		context: connection.registrationParameters.pluginUUID,
		id: randomUUID(),
});

clearTimeout(timeoutId);
listener.dispose();
resolve(ev.payload.settings);
}
});

connection.send({
event: "getGlobalSettings",
context: connection.registrationParameters.pluginUUID,
id,
});

return promise;
},

/**
Expand Down