Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: context adapter #207

Merged
merged 2 commits into from
Sep 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/Adapters.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -558,3 +558,32 @@ There're details about how to write an adapter.
### Who is responsible to create the DB?

As a convention, the adapter should be able to automatically create a database named ``casbin`` if it doesn't exist and use it for policy storage. Please use the Xorm adapter as a reference implementation: <https://github.com/casbin/xorm-adapter>

## Context Adapter

[ContextAdapter](https://github.com/casbin/casbin/blob/master/persist/adapter_context.go) provides a context-aware interface for Casbin adapters.

Through context, you can implement features such as timeout control for the Adapter API

### Example

[gormadapter](https://github.com/casbin/gorm-adapter) supports adapter with context, the following is a timeout control implemented using context

```go
ca, _ := NewContextAdapter("mysql", "root:@tcp(127.0.0.1:3306)/", "casbin")
// Limited time 300s
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Microsecond)
defer cancel()

err := ca.AddPolicyCtx(ctx, "p", "p", []string{"alice", "data1", "read"})
if err != nil {
panic(err)
}
```

### How to write an context adapter

`ContextAdapter` API only has an extra layer of context processing than ordinary `Adapter` API,
and on the basis of implementing ordinary Adapter API, you can encapsulate your own processing logic for context

A simple reference to the `gormadapter`: [context_adapter.go](https://github.com/casbin/gorm-adapter/blob/master/context_adapter.go)
Loading