You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/usage/resources/hooks.md
+117-9Lines changed: 117 additions & 9 deletions
Original file line number
Diff line number
Diff line change
@@ -1,3 +1,4 @@
1
+
1
2
# Resource Hooks
2
3
This section covers the usage of **Resource Hooks**, which is a feature of`ResourceDefinition<T>`. See the [ResourceDefinition usage guide](resource-definitions.md) for a general explanation on how to set up a `ResourceDefinition<T>`.
3
4
@@ -13,14 +14,15 @@ Understanding the semantics will be helpful in identifying which hooks on `Resou
options.EnableResourceHooks=true; // default is false
184
+
options.LoadDatabaseValues=false; // default is true
185
+
}
186
+
);
187
+
...
188
+
}
189
+
```
190
+
For this example, we may set `LoadDatabaseValues` to `false`. See the [Loading database values](#loading-database-values) example for more information about this option.
191
+
192
+
The simplest case of resource hooks we can then implement should not require a lot of explanation. This hook would triggered by any default JsonApiDotNetCore API route for `Article`.
@@ -294,6 +314,94 @@ public class PersonResource : ResourceDefinition<Person>
294
314
```
295
315
Note that not only anonymous people will be excluded when directly performing a `GET /people`, but also when included through relationships, like `GET /articles?include=author,reviewers`. Simultaneously, `if` condition that checks for `ResourcePipeline.Get` in the `PersonResource` ensures we still get expected responses from the API when eg. creating a person with `WantsPrivacy` set to true.
296
316
317
+
## Loading database values
318
+
When a hook is executed for a particular resource, JsonApiDotNetCore can load the corresponding database values and provide them in the hooks. This can be useful for eg.
319
+
* having a diff between a previous and new state of a resource (for example when updating a resource)
320
+
* performing authorization rules based on the property of a resource.
321
+
322
+
For example, consider a scenario in with the following two requirements:
323
+
* We need to log all updates on resources revealing their old and new value.
324
+
* We need to check if the property `IsLocked` is set is `true`, and if so, cancel the operation.
325
+
326
+
Consider an `Article` with title *Hello there* and API user trying to update the the title of this article to *Bye bye*. The above requirements could be implemented as follows
0 commit comments