Skip to content

Commit

Permalink
Merge pull request #5 from kibertoad/feature/optional-adapter
Browse files Browse the repository at this point in the history
Make adapter optional to support in-memory cases
  • Loading branch information
simoneb authored Jan 9, 2021
2 parents 63e48a5 + 5b03345 commit 9eedf14
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 deletions.
2 changes: 1 addition & 1 deletion plugin.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ declare module 'fastify' {

export interface FastifyCasbinOptions {
model: string | Model
adapter: string | Adapter
adapter?: string | Adapter
watcher?: Watcher
}

Expand Down
7 changes: 5 additions & 2 deletions plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ const fp = require('fastify-plugin')
const { newEnforcer, casbinJsGetPermissionForUser } = require('casbin')

async function fastifyCasbin (fastify, { model, adapter, watcher }) {
const enforcer = await newEnforcer(model, adapter)
const enforcerParams = adapter ? [model, adapter] : [model]
const enforcer = await newEnforcer(...enforcerParams)

if (watcher) {
enforcer.setWatcher(watcher)
}

await enforcer.loadPolicy()
if (adapter) {
await enforcer.loadPolicy()
}

fastify.onClose(async () => {
await Promise.all(
Expand Down
19 changes: 19 additions & 0 deletions test/casbin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,25 @@ test('preloaded model and adapter should be accepted', t => {
})
})

test('adapter can be omitted for in-memory storage', t => {
t.plan(2)

const fastify = Fastify()
const preloadedModel = new Model()
preloadedModel.loadModel(modelPath)

fastify.register(plugin, {
model: preloadedModel
})

fastify.ready(err => {
t.error(err)
t.ok(fastify.casbin)

fastify.close()
})
})

test('casbinJsGetPermissionForUser should exist', t => {
t.plan(2)

Expand Down
5 changes: 5 additions & 0 deletions test/plugin.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ server.register(fastifyCasbin, {
adapter: 'some adapter',
})

// in-memory adapter
server.register(fastifyCasbin, {
model: 'some file'
})

const model: Model = {} as Model
server.register(fastifyCasbin, {
model: model,
Expand Down

0 comments on commit 9eedf14

Please sign in to comment.