Casbin Watcher based on MongoDB Change Streams

Clone this repo:
  1. 9cf453a chore(release): 1.3.0 [skip ci] by semantic-release-bot · 5 months ago master v1.3.0
  2. 01980ad feat: improve README badges (#18) by Copilot · 5 months ago
  3. b53982d chore(release): 1.2.0 [skip ci] by semantic-release-bot · 5 months ago v1.2.0
  4. a7a737d feat: upgrade all packages, upgrade mongodb to v6 (#16) by yiev · 5 months ago
  5. f2a0edb chore(release): 1.1.1 [skip ci] by semantic-release-bot · 2 years, 8 months ago v1.1.1

Node-Casbin Watcher based on MongoDB Change Streams

CI Coverage Status NPM version NPM download Discord

For more information about MongoDB Change Streams, look here.

More information about Casbin Watchers, look here.

Installation

# NPM
npm install --save @casbin/mongo-changestream-watcher

# Yarn
yarn add @casbin/mongo-changestream-watcher

Simple Example using Mongoose Adapter

import { MongoChangeStreamWatcher } from '@casbin/mongo-changestream-watcher';
import { newEnforcer } from 'casbin';

// Initialize the watcher by connecting to a replica set.
const watcher = await MongoChangeStreamWatcher.newWatcher('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0', {collectionName: 'casbin_rule'});
const adapter = await MongooseAdapter.newAdapter('mongodb://localhost:27001,localhost:27002/casbin?replicaSet=rs0');
const enforcer = await newEnforcer('test/fixtures/basic_model.conf', adapter);

// Initialize the enforcer.
const enforcer = await newEnforcer('examples/authz_model.conf', 'examples/authz_policy.csv');

enforcer.setWatcher(watcher);

// By default, the watcher's callback is automatically set to the
// enforcer's loadPolicy() in the setWatcher() call.
// We can change it by explicitly setting a callback.
watcher.setUpdateCallback(() => console.log('Casbin need update'));

Notes

This watcher does not operate with update-calls typically found in other watchers. Mongo Change Stream directly reacts to changes in the database collection, and therefore all other watchers listening to the same stream will be automatically notified when changes do occur. However, this means that watcher also gets notified by its own changes.