8000 [Docs] Add some minor doc changes · AxonDivisionDev/laravel-json-api@61d99b0 · GitHub
[go: up one dir, main page]

Skip to content

Commit 61d99b0

Browse files
committed
[Docs] Add some minor doc changes
1 parent 626de2a commit 61d99b0

File tree

2 files changed

+115
-34
lines changed

2 files changed

+115
-34
lines changed

docs/features/broadcasting.md

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ We therefore broadcast using the JSON API format.
88

99
## Broadcasting Events
1010

11-
We have included a `BroadcastsData` trait that can be applied to an broadcastable event to help with serializing
11+
We have included a `BroadcastsData` trait that can be applied to a broadcastable event to help with serializing
1212
data to the JSON API format. This adds a `serializeData()` method to your event that you can use in Laravel's
1313
`broadcastWith()` hook. For example:
1414

@@ -64,7 +64,7 @@ class PostPublished implements ShouldBroadcast
6464
In most scenarios, the broadcasting of the data will occur as a queued job. This means that the event will need to
6565
know which JSON API to use to serialize the data.
6666

67-
In the example above, no API is specified so the `default` API will be used. If you need to use another API, you
67+
10000 In the example above, no API is specified so the default API will be used. If you need to use another API, you
6868
can set the `broadcastApi` property. For example, this will use the `v1` API:
6969

7070
```php
@@ -78,3 +78,39 @@ class PostPublished implements ShouldBroadcast
7878
// ...
7979
}
8080
```
81+
82+
If you need to programmatically work out the API, overload the `broadcastApi` method.
83+
84+
### Including Resources
85+
86+
If you want the broadcast data to be a [compound document](http://jsonapi.org/format/#document-compound-documents),
87+
you can specify the include paths when serializing the data. Pass the include paths as the second
88+
function argument, for example:
89+
90+
```php
91+
protected function broadcastWith()
92+
{
93+
return $this->serializeData($this->post, ['author', 'tags']);
94+
}
95+
```
96+
97+
### Sparse Fieldsets
98+
99+
You can also choose which fields to serialize when creating the broadcast data. Sparse fieldsets are
100+
defined using an array keyed by the resource type, with the values being the fields that should be
101+
serialized for that type.
102+
103+
In the following example, only the `title`, `content` and `author` fields will be serialized for `posts`
104+
resources, and only the `name` field for `users` resources.
105+
106+
```php
107+
protected function broadcastWith()
108+
{
109+
$fieldsets = [
110+
'posts' => ['title', 'content', 'author'],
111+
'users' => ['name']
112+
];
113+
114+
return $this->serializeData($this->post, [], $fieldsets);
115+
}
116+
```

docs/features/errors.md

Lines changed: 77 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,107 @@
1-
# Custom Errors
1+
# Errors
22

33
## Introduction
44

5-
This package allows you to return [JSON API error objects](http://jsonapi.org/format/1.0/#error-objects) which can include various information about what went wrong.
5+
The JSON API spec defines [error objects](http://jsonapi.org/format/#errors) that are returned
6+
in the top-level `errors` member of the response body. This package automatically handles converting
7+
common Laravel exceptions to these error objects, for example HTTP exceptions and validation exceptions.
68

7-
## Custom Errors In Controllers
9+
In addition, it provides the ability for you to return custom errors as needed. This chapter describes
10+
how to return your own error responses.
811

9-
This is particularly useful for errors that you have to manually present to the user through the controller. In order to magically return errors, you would need to use the `ErrorsAwareTrait`.
12+
## Creating Error Objects
1013

14+
Error objects can be constructed from array key/value pairs using the static `create` method on
15+
the package's error class. All the keys described in the specification's
16+
[error objects](http://jsonapi.org/format/#error-objects) chapter are supported.
1117

12-
Below is an example of a scenario which a user fails to login due to incorrect credentials.
18+
For example:
1319

1420
```php
15-
namespace App\Http\Controllers\Api\V1;
21+
use CloudCreativity\LaravelJsonApi\Document\Error;
22+
23+
$error = Error::create([
24+
'id' => '91053382-7c00-45eb-bdcc-8359d03debbb',
25+
'status' => '500',
26+
'code' => 'unexpected',
27+
'title' => 'Unexpected Error',
28+
'detail' => 'Something went wrong.',
29+
'meta' => ['foo' => 'bar'],
30+
]);
31+
```
32+
33+
## Controller Hooks
34+
35+
All [controller hooks](../basics/controllers.md) can return a HTTP response that will be used instead
36+
of the normal response generated by the controller. This means you can use these controller hooks
37+
to return JSON API error responses.
38+
39+
The `JsonApiController` has a responses factory that can create error responses. This can be used
40+
to return an error response in a controller hook, as demonstrated in the following example:
1641

17-
use CloudCreativity\LaravelJsonApi\Contracts\Http\Requests\RequestInterface as JsonApiRequest;
42+
```php
1843
use CloudCreativity\LaravelJsonApi\Document\Error;
1944

20-
class JsonWebTokensController extends Controller
45+
class PaymentController extends JsonApiController
2146
{
22-
protected function guard()
23-
{
24-
return Auth::guard('jwt');
25-
}
2647

27-
public function create(JsonApiRequest $request)
48+
protected function creating()
2849
{
29-
$resource_attributes = $request->getDocument()->getResource()->getAttributes();
30-
$credentials = [
31-
'email' => $resource_attributes->email,
32-
'password' => $resource_attributes->password,
33-
];
34-
35-
if ($this->guard()->attempt($credentials)) {
36-
// Success!
37-
} else {
38-
// Incorrect login details
50+
if (/** some condition */) {
3951
return $this->reply()->errors(Error::create([
40-
'status' => 422,
41-
'title' => 'Login failed.',
42-
'detail' => 'These credentials do not match our records.'
52+
'title' => 'Payment Required',
53+
'detail' => 'Your card has expired.',
54+
'status' => '402',
4355
]));
44-
4556
}
4657
}
4758
}
4859
```
4960

5061
And the response given would be the following:
5162

52-
```json
63+
```http
64+
HTTP/1.1 402 Payment Required
65+
Content-Type: application/vnd.api+json
66+
5367
{
5468
"errors": [
5569
{
56-
"status": "422",
57-
"title": "Login failed.",
58-
"detail": "These credentials do not match our records."
70+
"title": "Payment Required",
71+
"detail": "Your card has expired."
72+
"status": "402"
5973
}
6074
]
6175
}
62-
```
76+
```
77+
78+
You can pass either a single error object, or an array of error objects to the `errors()` reply method.
79+
The HTTP status of the response will be calculated from the status in the error objects.
80+
81+
## Throwing Errors
82+
83+
It is also possible to throw a `JsonApiException` from anywhere in your code. This will be converted
84+
to a JSON API response. For example:
85+
86+
```php
87+
use Neomerx\JsonApi\Exceptions\JsonApiException;
88+
use CloudCreativity\LaravelJsonApi\Document\Error;
89+
90+
try {
91+
dispatchNow(new ChargeCard($token));
92+
} catch (\App\PaymentException $ex) {
93+
Error::create([
94+
'title' => 'Payment Required',
95+
'detail' => $ex->getMessage(),
96+
'status' => '402',
97+
]);
98+
99+
throw new JsonApiException($error, 402, $ex);
100+
}
101+
```
102+
103+
The JSON API exception takes three arguments:
104+
105+
- An error object or an array of error objects.
106+
- The HTTP status code.
107+
- The previous exception.

0 commit comments

Comments
 (0)
0