@airnauts/comments-adapter-mongo 0.1.0 → 0.4.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.
- package/README.md +13 -0
- package/dist/index.js +7 -2
- package/dist/index.js.map +1 -1
- package/dist/repository.d.ts.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -10,6 +10,19 @@ pnpm add @airnauts/comments-adapter-mongo mongodb
|
|
|
10
10
|
|
|
11
11
|
## Usage
|
|
12
12
|
|
|
13
|
+
The simplest path — pass a connection string and let the adapter connect lazily on
|
|
14
|
+
first use (sharing the connection across hot-reloads via `cacheKey`) and ensure its
|
|
15
|
+
indexes for you:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { mongoRepository } from '@airnauts/comments-adapter-mongo'
|
|
19
|
+
|
|
20
|
+
const repository = mongoRepository({ uri: process.env.MONGODB_URI! })
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
If you manage your own `Db` instance, build the repository against it directly and
|
|
24
|
+
create the indexes once at startup:
|
|
25
|
+
|
|
13
26
|
```ts
|
|
14
27
|
import { createMongoRepository, ensureIndexes } from '@airnauts/comments-adapter-mongo'
|
|
15
28
|
|
package/dist/index.js
CHANGED
|
@@ -22,6 +22,7 @@ function toThread(doc) {
|
|
|
22
22
|
return { id: _id, ...rest };
|
|
23
23
|
}
|
|
24
24
|
function toListItem(doc) {
|
|
25
|
+
const root = doc.comments?.[0];
|
|
25
26
|
const {
|
|
26
27
|
_id,
|
|
27
28
|
projectId: _p,
|
|
@@ -31,7 +32,11 @@ function toListItem(doc) {
|
|
|
31
32
|
provenance: _pr,
|
|
32
33
|
...rest
|
|
33
34
|
} = doc;
|
|
34
|
-
return {
|
|
35
|
+
return {
|
|
36
|
+
id: _id,
|
|
37
|
+
...rest,
|
|
38
|
+
rootComment: root ? { text: root.text, createdAt: root.createdAt } : null
|
|
39
|
+
};
|
|
35
40
|
}
|
|
36
41
|
function createMongoRepository({ db }) {
|
|
37
42
|
const col = db.collection(COLLECTION);
|
|
@@ -81,7 +86,7 @@ function createMongoRepository({ db }) {
|
|
|
81
86
|
];
|
|
82
87
|
}
|
|
83
88
|
const docs = await col.find(filter, {
|
|
84
|
-
projection: { comments:
|
|
89
|
+
projection: { comments: { $slice: 1 }, captureContext: 0, provenance: 0 }
|
|
85
90
|
}).sort({ updatedAt: -1, _id: -1 }).limit(limit + 1).toArray();
|
|
86
91
|
const more = docs.length > limit;
|
|
87
92
|
const page = more ? docs.slice(0, limit) : docs;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/repository.ts","../src/indexes.ts"],"sourcesContent":["import type {\n Attachment,\n AttachmentId,\n Comment,\n Thread,\n ThreadId,\n ThreadListItem,\n ThreadStatus,\n} from '@airnauts/comments-core'\nimport {\n type AnchorPatch,\n decodeCursor,\n encodeCursor,\n type ListQuery,\n type ListResult,\n lazyRepository,\n type NewComment,\n type NewThread,\n type Repository,\n type Scope,\n} from '@airnauts/comments-server'\nimport { type Db, type Filter, MongoClient, type UpdateFilter } from 'mongodb'\nimport { ensureIndexes } from './indexes'\n\nexport const COLLECTION = 'threads'\nexport const ATTACHMENTS_COLLECTION = 'attachments'\n\n/** Stored shape: the wire Thread (minus its `id`) keyed by `_id`, plus server-only scope. */\ntype StoredThread = Omit<Thread, 'id'> & {\n _id: string\n projectId: string\n env: string | null\n}\n\n/** Stored shape: the wire Attachment (minus its `id`) keyed by `_id`, plus server-only scope. */\ntype StoredAttachment = Omit<Attachment, 'id'> & {\n _id: string\n projectId: string\n env: string | null\n}\n\nfunction toAttachment(doc: StoredAttachment): Attachment {\n const { _id, projectId: _p, env: _e, ...rest } = doc\n return { id: _id as AttachmentId, ...rest }\n}\n\nfunction scopeFilter(scope: Scope): { projectId: string; env: string | null } {\n return { projectId: scope.projectId, env: scope.env ?? null }\n}\n\nfunction unresolvedCountOf(status: ThreadStatus): number {\n return status === 'open' ? 1 : 0\n}\n\nfunction toThread(doc: StoredThread): Thread {\n const { _id, projectId: _p, env: _e, ...rest } = doc\n return { id: _id as ThreadId, ...rest }\n}\n\nfunction toListItem(doc: StoredThread): ThreadListItem {\n // Strip server-only scope + thread-only payload (also absent under the list projection).\n const {\n _id,\n projectId: _p,\n env: _e,\n comments: _c,\n captureContext: _cc,\n provenance: _pr,\n ...rest\n } = doc\n return { id: _id as ThreadId, ...rest }\n}\n\nexport function createMongoRepository({ db }: { db: Db }): Repository {\n const col = db.collection<StoredThread>(COLLECTION)\n const attachmentsCol = db.collection<StoredAttachment>(ATTACHMENTS_COLLECTION)\n\n return {\n async createThread(input: NewThread): Promise<Thread> {\n const doc: StoredThread = {\n _id: input.id,\n projectId: input.projectId,\n env: input.env ?? null,\n scope: input.scope,\n pageKey: input.pageKey,\n pageUrl: input.pageUrl,\n ...(input.pageTitle !== undefined ? { pageTitle: input.pageTitle } : {}),\n anchor: input.anchor,\n status: input.status,\n anchorState: input.anchorState,\n ...(input.selectionLost !== undefined ? { selectionLost: input.selectionLost } : {}),\n commentCount: 1,\n unresolvedCount: unresolvedCountOf(input.status),\n createdBy: input.createdBy,\n createdAt: input.createdAt,\n updatedAt: input.updatedAt,\n lastActivityAt: input.lastActivityAt,\n schemaVersion: input.schemaVersion,\n comments: [input.firstComment],\n captureContext: input.captureContext,\n ...(input.provenance !== undefined ? { provenance: input.provenance } : {}),\n }\n await col.insertOne(doc)\n return toThread(doc)\n },\n\n async getThread(scope: Scope, id: ThreadId): Promise<Thread | null> {\n const doc = await col.findOne({ _id: id, ...scopeFilter(scope) })\n return doc ? toThread(doc) : null\n },\n\n async listThreads(query: ListQuery): Promise<ListResult> {\n const limit = Math.max(1, Math.min(query.limit, 200))\n const filter: Record<string, unknown> = scopeFilter(query)\n if (query.pageKey !== undefined) filter.pageKey = query.pageKey\n if (query.status !== undefined) filter.status = query.status\n const cursor = query.cursor ? decodeCursor(query.cursor) : undefined\n if (cursor) {\n filter.$or = [\n { updatedAt: { $lt: cursor.updatedAt } },\n { updatedAt: cursor.updatedAt, _id: { $lt: cursor.id } },\n ]\n }\n const docs = await col\n .find(filter as Filter<StoredThread>, {\n projection: { comments: 0, captureContext: 0, provenance: 0 },\n })\n .sort({ updatedAt: -1, _id: -1 })\n .limit(limit + 1)\n .toArray()\n const more = docs.length > limit\n const page = more ? docs.slice(0, limit) : docs\n const last = page[page.length - 1]\n const nextCursor =\n more && last ? encodeCursor({ updatedAt: last.updatedAt, id: last._id }) : null\n return { threads: page.map((d) => toListItem(d as StoredThread)), nextCursor }\n },\n\n async addComment(scope: Scope, threadId: ThreadId, comment: NewComment): Promise<Comment> {\n // unresolvedCount is intentionally untouched: it tracks `status` only, and\n // addComment never changes status. Do NOT add a spurious $inc here.\n const res = await col.updateOne(\n { _id: threadId, ...scopeFilter(scope) },\n {\n $push: { comments: comment },\n $inc: { commentCount: 1 },\n $set: { updatedAt: comment.createdAt, lastActivityAt: comment.createdAt },\n },\n )\n if (res.matchedCount === 0) throw new Error('thread not found')\n return comment\n },\n\n async setStatus(\n scope: Scope,\n threadId: ThreadId,\n status: ThreadStatus,\n now: string,\n ): Promise<Thread> {\n const doc = await col.findOneAndUpdate(\n { _id: threadId, ...scopeFilter(scope) },\n {\n $set: {\n status,\n updatedAt: now,\n lastActivityAt: now,\n unresolvedCount: unresolvedCountOf(status),\n },\n },\n { returnDocument: 'after' },\n )\n if (!doc) throw new Error('thread not found')\n return toThread(doc)\n },\n\n async updateAnchor(\n scope: Scope,\n threadId: ThreadId,\n patch: AnchorPatch,\n now: string,\n ): Promise<ThreadListItem> {\n const set: Record<string, unknown> = {\n anchorState: patch.anchorState,\n updatedAt: now,\n lastActivityAt: now,\n }\n if (patch.selectors !== undefined) set['anchor.selectors'] = patch.selectors\n if (patch.signals !== undefined) set['anchor.signals'] = patch.signals\n if (patch.selectionLost !== undefined) set.selectionLost = patch.selectionLost\n const doc = await col.findOneAndUpdate(\n { _id: threadId, ...scopeFilter(scope) },\n { $set: set } as UpdateFilter<StoredThread>,\n { returnDocument: 'after' },\n )\n if (!doc) throw new Error('thread not found')\n return toListItem(doc)\n },\n\n async putAttachment(scope: Scope, attachment: Attachment): Promise<void> {\n const { id, ...rest } = attachment\n const doc: StoredAttachment = { _id: id, ...scopeFilter(scope), ...rest }\n await attachmentsCol.replaceOne({ _id: id }, doc, { upsert: true })\n },\n\n async getAttachments(scope: Scope, ids: AttachmentId[]): Promise<Attachment[]> {\n if (ids.length === 0) return []\n const docs = await attachmentsCol\n .find({ _id: { $in: ids as unknown as string[] }, ...scopeFilter(scope) })\n .toArray()\n return docs.map((d) => toAttachment(d as StoredAttachment))\n },\n }\n}\n\n/** Open one client, connect, ensure indexes, and build the repository. */\nasync function connectMongo(uri: string): Promise<Repository> {\n const client = new MongoClient(uri)\n try {\n await client.connect() // intentionally left open for the process lifetime on success\n } catch (err) {\n await client.close().catch(() => {}) // best-effort cleanup; swallow secondary errors\n throw err\n }\n const db = client.db() // database name comes from the connection string\n await ensureIndexes(db)\n return createMongoRepository({ db })\n}\n\n/**\n * Host-facing Mongo `Repository`: connects lazily on first use and memoizes the\n * connection (warm serverless / HMR reuse) under `cacheKey`. The single function\n * a host imports — `createMongoRepository`/`ensureIndexes` remain for callers\n * that own their own connection.\n *\n * `cacheKey` defaults to `'mongo'`. If you connect to more than one database in the\n * same process, pass a distinct `cacheKey` per connection — otherwise the second\n * call reuses the first connection under the shared default key.\n */\nexport function mongoRepository({\n uri,\n cacheKey = 'mongo',\n}: {\n uri: string\n cacheKey?: string\n}): Repository {\n return lazyRepository(() => connectMongo(uri), { cacheKey })\n}\n","import type { Db } from 'mongodb'\nimport { COLLECTION } from './repository'\n\n/**\n * Create the scoped indexes from architecture §5. Idempotent: MongoDB's\n * createIndexes is a no-op when an identical index already exists, so this is\n * safe to run on every startup.\n */\nexport async function ensureIndexes(db: Db): Promise<void> {\n await db.collection(COLLECTION).createIndexes([\n { key: { projectId: 1, pageKey: 1 }, name: 'projectId_pageKey' },\n { key: { projectId: 1, updatedAt: -1 }, name: 'projectId_updatedAt' },\n { key: { projectId: 1, status: 1 }, name: 'projectId_status' },\n ])\n}\n"],"mappings":";AASA;AAAA,EAEE;AAAA,EACA;AAAA,EAGA;AAAA,OAKK;AACP,SAA+B,mBAAsC;AAG9D,IAAM,aAAa;AACnB,IAAM,yBAAyB;AAgBtC,SAAS,aAAa,KAAmC;AACvD,QAAM,EAAE,KAAK,WAAW,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI;AACjD,SAAO,EAAE,IAAI,KAAqB,GAAG,KAAK;AAC5C;AAEA,SAAS,YAAY,OAAyD;AAC5E,SAAO,EAAE,WAAW,MAAM,WAAW,KAAK,MAAM,OAAO,KAAK;AAC9D;AAEA,SAAS,kBAAkB,QAA8B;AACvD,SAAO,WAAW,SAAS,IAAI;AACjC;AAEA,SAAS,SAAS,KAA2B;AAC3C,QAAM,EAAE,KAAK,WAAW,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI;AACjD,SAAO,EAAE,IAAI,KAAiB,GAAG,KAAK;AACxC;AAEA,SAAS,WAAW,KAAmC;AAErD,QAAM;AAAA,IACJ;AAAA,IACA,WAAW;AAAA,IACX,KAAK;AAAA,IACL,UAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,YAAY;AAAA,IACZ,GAAG;AAAA,EACL,IAAI;AACJ,SAAO,EAAE,IAAI,KAAiB,GAAG,KAAK;AACxC;AAEO,SAAS,sBAAsB,EAAE,GAAG,GAA2B;AACpE,QAAM,MAAM,GAAG,WAAyB,UAAU;AAClD,QAAM,iBAAiB,GAAG,WAA6B,sBAAsB;AAE7E,SAAO;AAAA,IACL,MAAM,aAAa,OAAmC;AACpD,YAAM,MAAoB;AAAA,QACxB,KAAK,MAAM;AAAA,QACX,WAAW,MAAM;AAAA,QACjB,KAAK,MAAM,OAAO;AAAA,QAClB,OAAO,MAAM;AAAA,QACb,SAAS,MAAM;AAAA,QACf,SAAS,MAAM;AAAA,QACf,GAAI,MAAM,cAA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M,OAAO,QAAQ;AAAA,EACvB,SAAS,KAAK;AACZ,UAAM,OAAO,MAAM,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AACnC,UAAM;AAAA,EACR;AACA,QAAM,KAAK,OAAO,GAAG;AACrB,QAAM,cAAc,EAAE;AACtB,SAAO,sBAAsB,EAAE,GAAG,CAAC;AACrC;AAYO,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA,WAAW;AACb,GAGe;AACb,SAAO,eAAe,MAAM,aAAa,GAAG,GAAG,EAAE,SAAS,CAAC;AAC7D;;;AC9OA,eAAsB,cAAc,IAAuB;AACzD,QAAM,GAAG,WAAW,UAAU,EAAE,cAAc;AAAA,IAC5C,EAAE,KAAK,EAAE,WAAW,GAAG,SAAS,EAAE,GAAG,MAAM,oBAAoB;AAAA,IAC/D,EAAE,KAAK,EAAE,WAAW,GAAG,WAAW,GAAG,GAAG,MAAM,sBAAsB;AAAA,IACpE,EAAE,KAAK,EAAE,WAAW,GAAG,QAAQ,EAAE,GAAG,MAAM,mBAAmB;AAAA,EAC/D,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/repository.ts","../src/indexes.ts"],"sourcesContent":["import type {\n Attachment,\n AttachmentId,\n Comment,\n Thread,\n ThreadId,\n ThreadListItem,\n ThreadStatus,\n} from '@airnauts/comments-core'\nimport {\n type AnchorPatch,\n decodeCursor,\n encodeCursor,\n type ListQuery,\n type ListResult,\n lazyRepository,\n type NewComment,\n type NewThread,\n type Repository,\n type Scope,\n} from '@airnauts/comments-server'\nimport { type Db, type Filter, MongoClient, type UpdateFilter } from 'mongodb'\nimport { ensureIndexes } from './indexes'\n\nexport const COLLECTION = 'threads'\nexport const ATTACHMENTS_COLLECTION = 'attachments'\n\n/** Stored shape: the wire Thread (minus its `id`) keyed by `_id`, plus server-only scope. */\ntype StoredThread = Omit<Thread, 'id'> & {\n _id: string\n projectId: string\n env: string | null\n}\n\n/** Stored shape: the wire Attachment (minus its `id`) keyed by `_id`, plus server-only scope. */\ntype StoredAttachment = Omit<Attachment, 'id'> & {\n _id: string\n projectId: string\n env: string | null\n}\n\nfunction toAttachment(doc: StoredAttachment): Attachment {\n const { _id, projectId: _p, env: _e, ...rest } = doc\n return { id: _id as AttachmentId, ...rest }\n}\n\nfunction scopeFilter(scope: Scope): { projectId: string; env: string | null } {\n return { projectId: scope.projectId, env: scope.env ?? null }\n}\n\nfunction unresolvedCountOf(status: ThreadStatus): number {\n return status === 'open' ? 1 : 0\n}\n\nfunction toThread(doc: StoredThread): Thread {\n const { _id, projectId: _p, env: _e, ...rest } = doc\n return { id: _id as ThreadId, ...rest }\n}\n\nfunction toListItem(doc: StoredThread): ThreadListItem {\n // The list projection slices comments to just the first (root); updateAnchor returns the\n // full doc. Either way comments[0] is the root. Strip the rest of the thread-only payload.\n const root = doc.comments?.[0]\n const {\n _id,\n projectId: _p,\n env: _e,\n comments: _c,\n captureContext: _cc,\n provenance: _pr,\n ...rest\n } = doc\n return {\n id: _id as ThreadId,\n ...rest,\n rootComment: root ? { text: root.text, createdAt: root.createdAt } : null,\n }\n}\n\nexport function createMongoRepository({ db }: { db: Db }): Repository {\n const col = db.collection<StoredThread>(COLLECTION)\n const attachmentsCol = db.collection<StoredAttachment>(ATTACHMENTS_COLLECTION)\n\n return {\n async createThread(input: NewThread): Promise<Thread> {\n const doc: StoredThread = {\n _id: input.id,\n projectId: input.projectId,\n env: input.env ?? null,\n scope: input.scope,\n pageKey: input.pageKey,\n pageUrl: input.pageUrl,\n ...(input.pageTitle !== undefined ? { pageTitle: input.pageTitle } : {}),\n anchor: input.anchor,\n status: input.status,\n anchorState: input.anchorState,\n ...(input.selectionLost !== undefined ? { selectionLost: input.selectionLost } : {}),\n commentCount: 1,\n unresolvedCount: unresolvedCountOf(input.status),\n createdBy: input.createdBy,\n createdAt: input.createdAt,\n updatedAt: input.updatedAt,\n lastActivityAt: input.lastActivityAt,\n schemaVersion: input.schemaVersion,\n comments: [input.firstComment],\n captureContext: input.captureContext,\n ...(input.provenance !== undefined ? { provenance: input.provenance } : {}),\n }\n await col.insertOne(doc)\n return toThread(doc)\n },\n\n async getThread(scope: Scope, id: ThreadId): Promise<Thread | null> {\n const doc = await col.findOne({ _id: id, ...scopeFilter(scope) })\n return doc ? toThread(doc) : null\n },\n\n async listThreads(query: ListQuery): Promise<ListResult> {\n const limit = Math.max(1, Math.min(query.limit, 200))\n const filter: Record<string, unknown> = scopeFilter(query)\n if (query.pageKey !== undefined) filter.pageKey = query.pageKey\n if (query.status !== undefined) filter.status = query.status\n const cursor = query.cursor ? decodeCursor(query.cursor) : undefined\n if (cursor) {\n filter.$or = [\n { updatedAt: { $lt: cursor.updatedAt } },\n { updatedAt: cursor.updatedAt, _id: { $lt: cursor.id } },\n ]\n }\n const docs = await col\n .find(filter as Filter<StoredThread>, {\n projection: { comments: { $slice: 1 }, captureContext: 0, provenance: 0 },\n })\n .sort({ updatedAt: -1, _id: -1 })\n .limit(limit + 1)\n .toArray()\n const more = docs.length > limit\n const page = more ? docs.slice(0, limit) : docs\n const last = page[page.length - 1]\n const nextCursor =\n more && last ? encodeCursor({ updatedAt: last.updatedAt, id: last._id }) : null\n return { threads: page.map((d) => toListItem(d as StoredThread)), nextCursor }\n },\n\n async addComment(scope: Scope, threadId: ThreadId, comment: NewComment): Promise<Comment> {\n // unresolvedCount is intentionally untouched: it tracks `status` only, and\n // addComment never changes status. Do NOT add a spurious $inc here.\n const res = await col.updateOne(\n { _id: threadId, ...scopeFilter(scope) },\n {\n $push: { comments: comment },\n $inc: { commentCount: 1 },\n $set: { updatedAt: comment.createdAt, lastActivityAt: comment.createdAt },\n },\n )\n if (res.matchedCount === 0) throw new Error('thread not found')\n return comment\n },\n\n async setStatus(\n scope: Scope,\n threadId: ThreadId,\n status: ThreadStatus,\n now: string,\n ): Promise<Thread> {\n const doc = await col.findOneAndUpdate(\n { _id: threadId, ...scopeFilter(scope) },\n {\n $set: {\n status,\n updatedAt: now,\n lastActivityAt: now,\n unresolvedCount: unresolvedCountOf(status),\n },\n },\n { returnDocument: 'after' },\n )\n if (!doc) throw new Error('thread not found')\n return toThread(doc)\n },\n\n async updateAnchor(\n scope: Scope,\n threadId: ThreadId,\n patch: AnchorPatch,\n now: string,\n ): Promise<ThreadListItem> {\n const set: Record<string, unknown> = {\n anchorState: patch.anchorState,\n updatedAt: now,\n lastActivityAt: now,\n }\n if (patch.selectors !== undefined) set['anchor.selectors'] = patch.selectors\n if (patch.signals !== undefined) set['anchor.signals'] = patch.signals\n if (patch.selectionLost !== undefined) set.selectionLost = patch.selectionLost\n const doc = await col.findOneAndUpdate(\n { _id: threadId, ...scopeFilter(scope) },\n { $set: set } as UpdateFilter<StoredThread>,\n { returnDocument: 'after' },\n )\n if (!doc) throw new Error('thread not found')\n return toListItem(doc)\n },\n\n async putAttachment(scope: Scope, attachment: Attachment): Promise<void> {\n const { id, ...rest } = attachment\n const doc: StoredAttachment = { _id: id, ...scopeFilter(scope), ...rest }\n await attachmentsCol.replaceOne({ _id: id }, doc, { upsert: true })\n },\n\n async getAttachments(scope: Scope, ids: AttachmentId[]): Promise<Attachment[]> {\n if (ids.length === 0) return []\n const docs = await attachmentsCol\n .find({ _id: { $in: ids as unknown as string[] }, ...scopeFilter(scope) })\n .toArray()\n return docs.map((d) => toAttachment(d as StoredAttachment))\n },\n }\n}\n\n/** Open one client, connect, ensure indexes, and build the repository. */\nasync function connectMongo(uri: string): Promise<Repository> {\n const client = new MongoClient(uri)\n try {\n await client.connect() // intentionally left open for the process lifetime on success\n } catch (err) {\n await client.close().catch(() => {}) // best-effort cleanup; swallow secondary errors\n throw err\n }\n const db = client.db() // database name comes from the connection string\n await ensureIndexes(db)\n return createMongoRepository({ db })\n}\n\n/**\n * Host-facing Mongo `Repository`: connects lazily on first use and memoizes the\n * connection (warm serverless / HMR reuse) under `cacheKey`. The single function\n * a host imports — `createMongoRepository`/`ensureIndexes` remain for callers\n * that own their own connection.\n *\n * `cacheKey` defaults to `'mongo'`. If you connect to more than one database in the\n * same process, pass a distinct `cacheKey` per connection — otherwise the second\n * call reuses the first connection under the shared default key.\n */\nexport function mongoRepository({\n uri,\n cacheKey = 'mongo',\n}: {\n uri: string\n cacheKey?: string\n}): Repository {\n return lazyRepository(() => connectMongo(uri), { cacheKey })\n}\n","import type { Db } from 'mongodb'\nimport { COLLECTION } from './repository'\n\n/**\n * Create the scoped indexes from architecture §5. Idempotent: MongoDB's\n * createIndexes is a no-op when an identical index already exists, so this is\n * safe to run on every startup.\n */\nexport async function ensureIndexes(db: Db): Promise<void> {\n await db.collection(COLLECTION).createIndexes([\n { key: { projectId: 1, pageKey: 1 }, name: 'projectId_pageKey' },\n { key: { projectId: 1, updatedAt: -1 }, name: 'projectId_updatedAt' },\n { key: { projectId: 1, status: 1 }, name: 'projectId_status' },\n ])\n}\n"],"mappings":";AASA;AAAA,EAEE;AAAA,EACA;AAAA,EAGA;AAAA,OAKK;AACP,SAA+B,mBAAsC;AAG9D,IAAM,aAAa;AACnB,IAAM,yBAAyB;AAgBtC,SAAS,aAAa,KAAmC;AACvD,QAAM,EAAE,KAAK,WAAW,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI;AACjD,SAAO,EAAE,IAAI,KAAqB,GAAG,KAAK;AAC5C;AAEA,SAAS,YAAY,OAAyD;AAC5E,SAAO,EAAE,WAAW,MAAM,WAAW,KAAK,MAAM,OAAO,KAAK;AAC9D;AAEA,SAAS,kBAAkB,QAA8B;AACvD,SAAO,WAAW,SAAS,IAAI;AACjC;AAEA,SAAS,SAAS,KAA2B;AAC3C,QAAM,EAAE,KAAK,WAAW,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI;AACjD,SAAO,EAAE,IAAI,KAAiB,GAAG,KAAK;AACxC;AAEA,SAAS,WAAW,KAAmC;AAGrD,QAAM,OAAO,IAAI,WAAW,CAAC;AAC7B,QAAM;AAAA,IACJ;AAAA,IACA,WAAW;AAAA,IACX,KAAK;AAAA,IACL,UAAU;AAAA,IACV,gBAAgB;AAAA,IACh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|
package/dist/repository.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repository.d.ts","sourceRoot":"","sources":["../src/repository.ts"],"names":[],"mappings":"AASA,OAAO,EASL,KAAK,UAAU,EAEhB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAE,KAAK,EAAE,EAA+C,MAAM,SAAS,CAAA;AAG9E,eAAO,MAAM,UAAU,YAAY,CAAA;AACnC,eAAO,MAAM,sBAAsB,gBAAgB,CAAA;
|
|
1
|
+
{"version":3,"file":"repository.d.ts","sourceRoot":"","sources":["../src/repository.ts"],"names":[],"mappings":"AASA,OAAO,EASL,KAAK,UAAU,EAEhB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EAAE,KAAK,EAAE,EAA+C,MAAM,SAAS,CAAA;AAG9E,eAAO,MAAM,UAAU,YAAY,CAAA;AACnC,eAAO,MAAM,sBAAsB,gBAAgB,CAAA;AAsDnD,wBAAgB,qBAAqB,CAAC,EAAE,EAAE,EAAE,EAAE;IAAE,EAAE,EAAE,EAAE,CAAA;CAAE,GAAG,UAAU,CA2IpE;AAgBD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,EAC9B,GAAG,EACH,QAAkB,GACnB,EAAE;IACD,GAAG,EAAE,MAAM,CAAA;IACX,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB,GAAG,UAAU,CAEb"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@airnauts/comments-adapter-mongo",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "MongoDB repository adapter for the Airnauts commenting tool server.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"comments",
|
|
@@ -40,8 +40,8 @@
|
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"mongodb": "^6.12.0",
|
|
43
|
-
"@airnauts/comments-core": "^0.
|
|
44
|
-
"@airnauts/comments-server": "^0.
|
|
43
|
+
"@airnauts/comments-core": "^0.4.0",
|
|
44
|
+
"@airnauts/comments-server": "^0.4.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"mongodb-memory-server": "^10.1.2",
|