@aria-framework/notify 0.2.0 → 0.3.1

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.
Files changed (2) hide show
  1. package/package.json +30 -30
  2. package/store.js +93 -45
package/package.json CHANGED
@@ -1,30 +1,30 @@
1
- {
2
- "name": "@aria-framework/notify",
3
- "version": "0.2.0",
4
- "description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery, and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
5
- "license": "UNLICENSED",
6
- "private": false,
7
- "publishConfig": {
8
- "access": "public"
9
- },
10
- "main": "index.js",
11
- "files": [
12
- "index.js",
13
- "store.js",
14
- "hub.js",
15
- "emit.js",
16
- "assets/",
17
- "views/"
18
- ],
19
- "peerDependencies": {
20
- "better-sqlite3": ">=11"
21
- },
22
- "peerDependenciesMeta": {
23
- "better-sqlite3": {
24
- "optional": true
25
- }
26
- },
27
- "scripts": {
28
- "test": "node test/store.js && node test/hub.js && node test/emit.js && node test/bell.js"
29
- }
30
- }
1
+ {
2
+ "name": "@aria-framework/notify",
3
+ "version": "0.3.1",
4
+ "description": "Aria App Framework — notify module. In-app notifications: ownership-scoped rows, a per-process SSE hub for live delivery, and a fire-and-forget emitter that needs no request and no actor, so a scheduler can raise one.",
5
+ "license": "UNLICENSED",
6
+ "private": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "main": "index.js",
11
+ "files": [
12
+ "index.js",
13
+ "store.js",
14
+ "hub.js",
15
+ "emit.js",
16
+ "assets/",
17
+ "views/"
18
+ ],
19
+ "peerDependencies": {
20
+ "better-sqlite3": ">=11"
21
+ },
22
+ "peerDependenciesMeta": {
23
+ "better-sqlite3": {
24
+ "optional": true
25
+ }
26
+ },
27
+ "scripts": {
28
+ "test": "node test/store.js && node test/schema-parity.js && node test/hub.js && node test/emit.js && node test/bell.js"
29
+ }
30
+ }
package/store.js CHANGED
@@ -18,8 +18,30 @@
18
18
  'use strict';
19
19
 
20
20
  /** The columns this module reads and writes. An app's migration must provide at least these. */
21
- const SCHEMA = `
22
- id INTEGER PRIMARY KEY AUTOINCREMENT,
21
+ /**
22
+ * Column list for the app's CREATE TABLE. A FUNCTION of the dialect since 0.3.0: the id column
23
+ * and the timestamp default are the two things engines genuinely differ on, and an app on
24
+ * Postgres cannot use `INTEGER PRIMARY KEY AUTOINCREMENT`.
25
+ *
26
+ * `is_read` stays INTEGER 0/1 rather than becoming BOOLEAN on Postgres — deliberately. A real
27
+ * boolean would make every `is_read = 0` in this file dialect-dependent for no gain, and
28
+ * INTEGER is valid on both.
29
+ */
30
+ // The SQLite default, inline. `SCHEMA = schemaFor(null)` runs at module load, so reaching for
31
+ // @aria-framework/db-worker here made merely REQUIRING this package throw MODULE_NOT_FOUND —
32
+ // notify's manifest declares no dependency or peer on db-worker, and the comments elsewhere in
33
+ // this file call passing { driver } "the zero-dependency property". These are the only two
34
+ // dialect calls the schema makes, and both are one-liners on SQLite, so the default costs
35
+ // nothing and the claim becomes true. A caller wanting Postgres passes the dialect in.
36
+ const SQLITE_DEFAULT = {
37
+ autoIncrementPk: () => 'INTEGER PRIMARY KEY AUTOINCREMENT',
38
+ now: () => "datetime('now')"
39
+ };
40
+
41
+ function schemaFor(dialect) {
42
+ const d = dialect || SQLITE_DEFAULT;
43
+ return `
44
+ id ${d.autoIncrementPk()},
23
45
  user_id INTEGER NOT NULL, -- recipient; FK to the app's users table
24
46
  type TEXT NOT NULL, -- app-defined, e.g. 'assigned' | 'invoice.overdue'
25
47
  title TEXT NOT NULL, -- short line
@@ -30,27 +52,62 @@ const SCHEMA = `
30
52
  entity_type TEXT, -- app's record type, e.g. 'ticket' | 'invoice'
31
53
  entity_id INTEGER,
32
54
  is_read INTEGER NOT NULL DEFAULT 0,
33
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
55
+ created_at TEXT NOT NULL DEFAULT (${d.now()}),
34
56
  read_at TEXT
35
57
  `;
58
+ }
59
+
60
+ /** The SQLite schema, unchanged, for consumers that predate schemaFor(). */
61
+ const SCHEMA = schemaFor(null);
36
62
 
37
63
  /**
38
64
  * @param {Function} getDb returns the better-sqlite3 handle. A function, not a handle, because
39
65
  * the worker opens the database after modules are required.
40
66
  * @param {string} table defaults to `notifications`
41
67
  */
42
- function createStore({ getDb, table = 'notifications' } = {}) {
43
- if (typeof getDb !== 'function') throw new Error('notify: getDb() is required');
68
+ /**
69
+ * @param {object} opts
70
+ * driver the @aria-framework/db-worker driver (preferred since 0.3.0) — engine-agnostic
71
+ * getDb LEGACY: a function returning a better-sqlite3 handle. Still accepted so a consumer
72
+ * can upgrade this package before it upgrades its wiring; wrapped in a driver here.
73
+ * table defaults to 'notifications'
74
+ *
75
+ * EVERY METHOD IS ASYNC as of 0.3.0. There is no synchronous Postgres driver, so a store that
76
+ * runs on both engines has no choice — and the DB worker already awaits whatever a model method
77
+ * returns, so the cost lands on the ~6 call sites inside a consumer's model, not on its routes.
78
+ */
79
+ function createStore(opts = {}) {
80
+ const { table = 'notifications' } = opts;
81
+ let driver = opts.driver || null;
82
+ if (!driver) {
83
+ if (typeof opts.getDb !== 'function') {
84
+ throw new Error('notify: pass { driver } (preferred) or { getDb } (legacy)');
85
+ }
86
+ // Adopt the raw handle rather than opening anything: the app owns the connection.
87
+ const { createSqliteDriver } = require('@aria-framework/db-worker');
88
+ let adopted = null;
89
+ driver = new Proxy({}, {
90
+ get(_t, prop) {
91
+ if (!adopted) adopted = createSqliteDriver({ adopt: opts.getDb() });
92
+ return adopted[prop];
93
+ }
94
+ });
95
+ }
96
+
44
97
  // Interpolated once, at construction, from a value the APP supplies — never from a request.
45
98
  const T = String(table).replace(/[^A-Za-z0-9_]/g, '');
46
99
  if (!T) throw new Error('notify: table name must be a plain identifier');
47
100
 
48
- const unreadCount = (userId) => getDb()
49
- .prepare(`SELECT COUNT(*) AS c FROM ${T} WHERE user_id = ? AND is_read = 0`)
50
- .get(userId).c;
101
+ const d = () => driver.dialect;
102
+
103
+ async function unreadCount(userId) {
104
+ const r = await driver.get(`SELECT COUNT(*) AS c FROM ${T} WHERE user_id = ? AND is_read = 0`, [userId]);
105
+ return Number(r.c);
106
+ }
51
107
 
52
108
  return {
53
109
  SCHEMA,
110
+ schemaFor,
54
111
  table: T,
55
112
 
56
113
  /**
@@ -59,76 +116,67 @@ function createStore({ getDb, table = 'notifications' } = {}) {
59
116
  * Returns the ids actually written so the caller can hand them to the hub. De-duplicated,
60
117
  * because "the assignee" and "a collaborator" are frequently the same person and two bells
61
118
  * for one event reads as a bug.
62
- *
63
- * @param {number[]} userIds
64
- * @param {{type, title, body?, link?, actor_name?, entity_type?, entity_id?}} p
65
- * @returns {{userIds: number[]}}
66
119
  */
67
- createMany(userIds, p = {}) {
120
+ async createMany(userIds, p = {}) {
68
121
  const ids = [...new Set((userIds || []).filter((v) => v != null).map(Number))]
69
122
  .filter((n) => Number.isInteger(n));
70
123
  // A notification with no type or no title has nothing to show; refusing quietly is right
71
124
  // because the caller is fire-and-forget and must not learn about this through a throw.
72
125
  if (!ids.length || !p.type || !p.title) return { userIds: [] };
73
126
 
74
- const db = getDb();
75
- const ins = db.prepare(`
76
- INSERT INTO ${T} (user_id, type, title, body, link, actor_name, entity_type, entity_id)
77
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
78
- `);
79
- db.transaction(() => {
127
+ await driver.transaction(async (tx) => {
80
128
  for (const uid of ids) {
81
- ins.run(uid, p.type, p.title, p.body || null, p.link || null,
82
- p.actor_name || null, p.entity_type || null, p.entity_id || null);
129
+ await tx.run(
130
+ `INSERT INTO ${T} (user_id, type, title, body, link, actor_name, entity_type, entity_id)
131
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
132
+ [uid, p.type, p.title, p.body || null, p.link || null,
133
+ p.actor_name || null, p.entity_type || null, p.entity_id || null]
134
+ );
83
135
  }
84
- })();
136
+ });
85
137
  return { userIds: ids };
86
138
  },
87
139
 
88
140
  unreadCount,
89
141
 
90
142
  /** Latest N (read and unread) for the bell, plus the unread count. */
91
- recent(userId, limit = 15) {
143
+ async recent(userId, limit = 15) {
92
144
  const lim = Math.min(50, Math.max(1, parseInt(limit, 10) || 15));
93
- const items = getDb().prepare(
94
- `SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`
95
- ).all(userId, lim);
96
- return { unread: unreadCount(userId), items };
145
+ const items = await driver.all(
146
+ `SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`, [userId, lim]);
147
+ return { unread: await unreadCount(userId), items };
97
148
  },
98
149
 
99
150
  /** Paginated history for a full notifications page. */
100
- listPage(userId, page = 1, pageSize = 25) {
101
- const db = getDb();
151
+ async listPage(userId, page = 1, pageSize = 25) {
102
152
  const p = Math.max(1, parseInt(page, 10) || 1);
103
153
  const size = Math.min(100, Math.max(5, parseInt(pageSize, 10) || 25));
104
- const total = db.prepare(`SELECT COUNT(*) AS c FROM ${T} WHERE user_id = ?`).get(userId).c;
105
- const rows = db.prepare(
106
- `SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`
107
- ).all(userId, size, (p - 1) * size);
154
+ const total = Number((await driver.get(`SELECT COUNT(*) AS c FROM ${T} WHERE user_id = ?`, [userId])).c);
155
+ const rows = await driver.all(
156
+ `SELECT * FROM ${T} WHERE user_id = ? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`,
157
+ [userId, size, (p - 1) * size]);
108
158
  return {
109
159
  rows, total, page: p, pageSize: size,
110
160
  pages: Math.max(1, Math.ceil(total / size)),
111
- unread: unreadCount(userId)
161
+ unread: await unreadCount(userId)
112
162
  };
113
163
  },
114
164
 
115
165
  /** Mark one read — ONLY if it belongs to userId. The scope is the authorisation. */
116
- markRead(id, userId) {
117
- const r = getDb().prepare(
118
- `UPDATE ${T} SET is_read = 1, read_at = datetime('now')
119
- WHERE id = ? AND user_id = ? AND is_read = 0`
120
- ).run(id, userId);
166
+ async markRead(id, userId) {
167
+ const r = await driver.run(
168
+ `UPDATE ${T} SET is_read = 1, read_at = ${d().now()}
169
+ WHERE id = ? AND user_id = ? AND is_read = 0`, [id, userId]);
121
170
  return { changed: r.changes };
122
171
  },
123
172
 
124
- markAllRead(userId) {
125
- const r = getDb().prepare(
126
- `UPDATE ${T} SET is_read = 1, read_at = datetime('now')
127
- WHERE user_id = ? AND is_read = 0`
128
- ).run(userId);
173
+ async markAllRead(userId) {
174
+ const r = await driver.run(
175
+ `UPDATE ${T} SET is_read = 1, read_at = ${d().now()}
176
+ WHERE user_id = ? AND is_read = 0`, [userId]);
129
177
  return { changed: r.changes };
130
178
  }
131
179
  };
132
180
  }
133
181
 
134
- module.exports = { createStore, SCHEMA };
182
+ module.exports = { createStore, SCHEMA, schemaFor };