Skip to content

MongoDB adapter

@vperms/mongodb-adapter persists subjects and grants in MongoDB. It accepts an already-connected Db instance and never opens or closes connections.

import { MongoClient } from "mongodb";
import { VeguiPermsMongoDBAdapter } from "@vperms/mongodb-adapter";
const adapter = new VeguiPermsMongoDBAdapter({
db: new MongoClient(url).db("vperms"),
});
await adapter.migrate();
interface VeguiPermsMongoDBAdapterOptions {
db: Db;
subjectsCollection?: string; // default "vperms_subjects"
grantsCollection?: string; // default "vperms_grants"
}

migrate() is idempotent and must be called explicitly during setup. It:

  • creates the subjects and grants collections when missing, and
  • creates a unique index on (workspaceId, id) for subjects and on (workspaceId, subjectId, permission) for grants.
type SubjectDocument = {
workspaceId: string;
id: string;
type: SubjectType;
parents: string[];
};
type GrantDocument = {
workspaceId: string;
subjectId: string;
permission: string;
value: boolean;
};

Collection names are exported as SUBJECTS_COLLECTION and GRANTS_COLLECTION, and the document types as SubjectDocument and GrantDocument.

import {
GRANTS_COLLECTION,
SUBJECTS_COLLECTION,
} from "@vperms/mongodb-adapter";
SUBJECTS_COLLECTION; // "vperms_subjects"
GRANTS_COLLECTION; // "vperms_grants"