Files
store-scraper-bot/src/repository/group-repository.js
T
tiennm99 9898f408a2 feat: replace MongoDB driver with Cloudflare KV storage
Drops the mongodb dependency entirely; all four logical collections
(admin singleton, group, apple_app, google_app) now live in a single KV
namespace bound as STORE_KV with prefixed keys. Cache TTL is delegated
to KV via expirationTtl (clamped to the 60s minimum). Document shape,
field names, and Java parity at the doc level are preserved.

- Adds src/repository/kv.js helper (getJson/putJson/del with TTL clamp)
- Rewrites all four *-repository.js modules on top of KV
- Removes src/repository/mongodb.js and the MONGODB_URI env requirement
- Adds an early STORE_KV-binding guard in src/index.js
- Bumps to 0.3.0
2026-05-05 20:39:01 +07:00

63 lines
1.6 KiB
JavaScript

import { del, getJson, putJson } from './kv.js';
import {
groupAddAppleApp,
groupAddGoogleApp,
groupIdToKey,
groupRemoveAppleApp,
groupRemoveGoogleApp,
newGroup,
} from '../models/group.js';
// KV-backed per-group state. Key shape: `group:{chatId}`.
export function createGroupRepository(env) {
function key(groupId) {
return `group:${groupIdToKey(groupId)}`;
}
async function exists(groupId) {
const doc = await getJson(env, key(groupId));
return doc !== null;
}
async function getGroup(groupId) {
const doc = await getJson(env, key(groupId));
return doc ?? newGroup(groupId);
}
async function saveGroup(group) {
await putJson(env, key(group._id), group);
}
async function initGroup(groupId) {
if (await exists(groupId)) return;
await saveGroup(newGroup(groupId));
}
async function deleteGroup(groupId) {
await del(env, key(groupId));
}
async function mutateAndSave(groupId, mutator) {
const group = await getGroup(groupId);
if (!mutator(group)) return false;
await saveGroup(group);
return true;
}
return {
exists,
getGroup,
saveGroup,
initGroup,
deleteGroup,
addAppleApp: (groupId, appId, country) =>
mutateAndSave(groupId, (g) => groupAddAppleApp(g, appId, country)),
removeAppleApp: (groupId, appId) =>
mutateAndSave(groupId, (g) => groupRemoveAppleApp(g, appId)),
addGoogleApp: (groupId, appId, country) =>
mutateAndSave(groupId, (g) => groupAddGoogleApp(g, appId, country)),
removeGoogleApp: (groupId, appId) =>
mutateAndSave(groupId, (g) => groupRemoveGoogleApp(g, appId)),
};
}