@zerotal/settings 0.0.0-stage → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ import { DB } from "@zerotal/orm";
2
+ import type { ScopeRef } from "../scope.ts";
3
+ import type { SettingsStore, StoredSetting } from "./SettingsStore.ts";
4
+
5
+ /** A row as the database returns it. Booleans and ids vary by engine. */
6
+ interface Row {
7
+ setting_key: string;
8
+ scope_key: string;
9
+ tenant_id: number | string | null;
10
+ user_id: string | null;
11
+ value: string;
12
+ hidden: boolean | number | string | null;
13
+ updated_by: string | null;
14
+ updated_at: string | null;
15
+ }
16
+
17
+ function toStored(row: Row): StoredSetting {
18
+ return {
19
+ key: row.setting_key,
20
+ scope: row.scope_key,
21
+ tenantId: row.tenant_id === null ? null : Number(row.tenant_id),
22
+ userId: row.user_id,
23
+ value: row.value,
24
+ // SQLite and MySQL hand back 0/1, PostgreSQL a boolean.
25
+ hidden: row.hidden === true || Number(row.hidden) === 1,
26
+ updatedBy: row.updated_by,
27
+ updatedAt: row.updated_at === null ? null : String(row.updated_at),
28
+ };
29
+ }
30
+
31
+ /**
32
+ * Overrides in the app's database, through the ORM's query builder — so it runs
33
+ * wherever the app's connection does: SQLite, PostgreSQL or MySQL.
34
+ *
35
+ * One row per setting and level, unique on `(setting_key, scope_key)`. The table
36
+ * is created on boot by the provider; see {@link settingsSchemaConcern}.
37
+ */
38
+ export class DatabaseStore implements SettingsStore {
39
+ constructor(private readonly table: string = "zerotal_settings") {}
40
+
41
+ async find(keys: readonly string[], scopes: readonly string[]): Promise<StoredSetting[]> {
42
+ if (keys.length === 0 || scopes.length === 0) return [];
43
+ const rows = await DB.table(this.table)
44
+ .whereIn("setting_key", [...keys])
45
+ .whereIn("scope_key", [...scopes])
46
+ .get<Row>();
47
+ return rows.map(toStored);
48
+ }
49
+
50
+ private async _one(key: string, scope: string): Promise<StoredSetting | null> {
51
+ const row = await DB.table(this.table)
52
+ .where("setting_key", key)
53
+ .where("scope_key", scope)
54
+ .first<Row>();
55
+ return row ? toStored(row) : null;
56
+ }
57
+
58
+ async put(
59
+ key: string,
60
+ scope: ScopeRef,
61
+ value: string,
62
+ updatedBy: string | null,
63
+ ): Promise<StoredSetting | null> {
64
+ const now = new Date().toISOString();
65
+ const changes = { value, hidden: false, updated_by: updatedBy, updated_at: now };
66
+ const before = await this._one(key, scope.id);
67
+ if (before) {
68
+ await this._update(key, scope.id, changes);
69
+ return before;
70
+ }
71
+ try {
72
+ await DB.table(this.table).insert({
73
+ setting_key: key,
74
+ scope_key: scope.id,
75
+ tenant_id: scope.tenant,
76
+ user_id: scope.user,
77
+ created_at: now,
78
+ ...changes,
79
+ });
80
+ return null;
81
+ } catch (error) {
82
+ // Another process inserted the same level between the read and the insert:
83
+ // the unique index refused the second row. Write over the one that won.
84
+ const raced = await this._one(key, scope.id);
85
+ if (!raced) throw error;
86
+ await this._update(key, scope.id, changes);
87
+ return raced;
88
+ }
89
+ }
90
+
91
+ async setHidden(
92
+ key: string,
93
+ scope: string,
94
+ hidden: boolean,
95
+ updatedBy: string | null,
96
+ ): Promise<StoredSetting | null> {
97
+ const before = await this._one(key, scope);
98
+ if (!before) return null;
99
+ await this._update(key, scope, {
100
+ hidden,
101
+ updated_by: updatedBy,
102
+ updated_at: new Date().toISOString(),
103
+ });
104
+ return before;
105
+ }
106
+
107
+ private async _update(key: string, scope: string, data: Record<string, unknown>): Promise<void> {
108
+ await DB.table(this.table).where("setting_key", key).where("scope_key", scope).update(data);
109
+ }
110
+ }
@@ -0,0 +1,62 @@
1
+ import type { ScopeRef } from "../scope.ts";
2
+ import type { SettingsStore, StoredSetting } from "./SettingsStore.ts";
3
+
4
+ /**
5
+ * Overrides in process memory, with the same rules as the database: one entry
6
+ * per setting and level, hidden rather than deleted. What `SettingsFake` runs on,
7
+ * so a test of tenant or user overrides needs no table.
8
+ */
9
+ export class MemoryStore implements SettingsStore {
10
+ private readonly _rows = new Map<string, StoredSetting>();
11
+
12
+ private static _id(key: string, scope: string): string {
13
+ return `${key}\u0000${scope}`;
14
+ }
15
+
16
+ async find(keys: readonly string[], scopes: readonly string[]): Promise<StoredSetting[]> {
17
+ const out: StoredSetting[] = [];
18
+ for (const row of this._rows.values()) {
19
+ if (keys.includes(row.key) && scopes.includes(row.scope)) out.push({ ...row });
20
+ }
21
+ return out;
22
+ }
23
+
24
+ async put(
25
+ key: string,
26
+ scope: ScopeRef,
27
+ value: string,
28
+ updatedBy: string | null,
29
+ ): Promise<StoredSetting | null> {
30
+ const id = MemoryStore._id(key, scope.id);
31
+ const before = this._rows.get(id);
32
+ this._rows.set(id, {
33
+ key,
34
+ scope: scope.id,
35
+ tenantId: scope.tenant,
36
+ userId: scope.user,
37
+ value,
38
+ hidden: false,
39
+ updatedBy,
40
+ updatedAt: new Date().toISOString(),
41
+ });
42
+ return before ? { ...before } : null;
43
+ }
44
+
45
+ async setHidden(
46
+ key: string,
47
+ scope: string,
48
+ hidden: boolean,
49
+ updatedBy: string | null,
50
+ ): Promise<StoredSetting | null> {
51
+ const row = this._rows.get(MemoryStore._id(key, scope));
52
+ if (!row) return null;
53
+ const before = { ...row };
54
+ Object.assign(row, { hidden, updatedBy, updatedAt: new Date().toISOString() });
55
+ return before;
56
+ }
57
+
58
+ /** Every stored override, hidden ones included. For assertions. */
59
+ all(): StoredSetting[] {
60
+ return [...this._rows.values()].map((row) => ({ ...row }));
61
+ }
62
+ }
@@ -0,0 +1,43 @@
1
+ import type { ScopeRef } from "../scope.ts";
2
+
3
+ /** One stored override, as a store hands it back. */
4
+ export interface StoredSetting {
5
+ key: string;
6
+ /** The level's id: `global`, `tenant:7`, `tenant:7:user:42`, `user:42`. */
7
+ scope: string;
8
+ tenantId: number | null;
9
+ userId: string | null;
10
+ /** The value, JSON-encoded. */
11
+ value: string;
12
+ /** Hidden overrides are kept, and skipped when reading. */
13
+ hidden: boolean;
14
+ /** Who last changed it, when a user did. */
15
+ updatedBy: string | null;
16
+ updatedAt: string | null;
17
+ }
18
+
19
+ /**
20
+ * Where overrides live.
21
+ *
22
+ * There is deliberately no way to delete one. Hiding an override stops it
23
+ * applying and keeps its value, so it can be restored and its history still reads
24
+ * against a row that exists.
25
+ */
26
+ export interface SettingsStore {
27
+ /** Every override of these keys at these levels, hidden ones included. */
28
+ find(keys: readonly string[], scopes: readonly string[]): Promise<StoredSetting[]>;
29
+ /** Write a value at a level, making it visible. Resolves to the row as it was before. */
30
+ put(
31
+ key: string,
32
+ scope: ScopeRef,
33
+ value: string,
34
+ updatedBy: string | null,
35
+ ): Promise<StoredSetting | null>;
36
+ /** Hide or unhide an override. Resolves to the row as it was before, or `null` when there is none. */
37
+ setHidden(
38
+ key: string,
39
+ scope: string,
40
+ hidden: boolean,
41
+ updatedBy: string | null,
42
+ ): Promise<StoredSetting | null>;
43
+ }