summaryrefslogtreecommitdiff
path: root/client/src/lib/config.ts
diff options
context:
space:
mode:
Diffstat (limited to 'client/src/lib/config.ts')
-rw-r--r--client/src/lib/config.ts54
1 files changed, 54 insertions, 0 deletions
diff --git a/client/src/lib/config.ts b/client/src/lib/config.ts
new file mode 100644
index 0000000..fccb09d
--- /dev/null
+++ b/client/src/lib/config.ts
@@ -0,0 +1,54 @@
+import { browser } from '$app/environment';
+import type { Infer } from 'superstruct';
+import { assert, object, optional, number, string } from 'superstruct';
+
+const Config = object({
+ active_project: optional(string())
+});
+
+type Config = Infer<typeof Config>;
+
+const CachedConfig = object({
+ config: Config,
+ expires: number()
+});
+
+type CachedConfig = Infer<typeof CachedConfig>;
+
+const CACHE_TTL = 10 * 60 * 60 * 1000;
+
+async function get_config(): Promise<Config> {
+ // Cache, might be outdated but saves on call to server
+ if (browser) {
+ try {
+ // TODO: Use async localStorage
+ const stored = localStorage.getItem('config');
+ if (stored !== null) {
+ const cached: CachedConfig = JSON.parse(stored);
+ assert(cached, CachedConfig);
+ if (cached.expires < Date.now()) {
+ // TODO: Should we update expires here?
+ // If page is in use we probably don't need to sync for a while.
+ return cached.config;
+ }
+ }
+ } catch {
+ // ignore errors
+ }
+ }
+
+ // Default config
+ // eslint-disable-next-line prefer-const
+ let config: Config = { active_project: undefined };
+
+ // TODO: Fetch config
+
+ if (browser) {
+ const cached: CachedConfig = { config: config, expires: Date.now() + CACHE_TTL };
+ // TODO: Use async localStorage
+ localStorage.setItem('config', JSON.stringify(cached));
+ }
+ return config;
+}
+
+export { type Config, get_config };