|
11 | 11 | use Tobyz\JsonApiServer\Endpoint\Show; |
12 | 12 | use Tobyz\JsonApiServer\Endpoint\Update; |
13 | 13 | use Tobyz\JsonApiServer\JsonApi; |
| 14 | +use Tobyz\JsonApiServer\Schema\Field\Attribute; |
14 | 15 | use Tobyz\JsonApiServer\Schema\Header; |
15 | 16 | use Tobyz\JsonApiServer\Schema\Type\Integer; |
16 | 17 | use Tobyz\Tests\JsonApiServer\AbstractTestCase; |
@@ -91,4 +92,65 @@ public function test_response_callback( |
91 | 92 |
|
92 | 93 | $this->assertEquals('executed', $response->getHeaderLine('X-Callback')); |
93 | 94 | } |
| 95 | + |
| 96 | + public function test_create_after_callback_runs_before_response() |
| 97 | + { |
| 98 | + $api = new JsonApi(); |
| 99 | + |
| 100 | + $endpoint = Create::make()->saved(function ($model): void { |
| 101 | + $model->after = 'executed'; |
| 102 | + }); |
| 103 | + |
| 104 | + $api->resource( |
| 105 | + new MockResource( |
| 106 | + 'users', |
| 107 | + endpoints: [$endpoint], |
| 108 | + fields: [ |
| 109 | + Attribute::make('after')->get(fn($model, $context) => $model->after ?? null), |
| 110 | + ], |
| 111 | + ), |
| 112 | + ); |
| 113 | + |
| 114 | + $response = $api->handle( |
| 115 | + $this->buildRequest('POST', '/users')->withParsedBody([ |
| 116 | + 'data' => ['type' => 'users'], |
| 117 | + ]), |
| 118 | + ); |
| 119 | + |
| 120 | + $this->assertJsonApiDocumentSubset( |
| 121 | + ['data' => ['attributes' => ['after' => 'executed']]], |
| 122 | + $response->getBody(), |
| 123 | + ); |
| 124 | + } |
| 125 | + |
| 126 | + public function test_update_after_callback_runs_before_response() |
| 127 | + { |
| 128 | + $api = new JsonApi(); |
| 129 | + |
| 130 | + $endpoint = Update::make()->saved(function ($model): void { |
| 131 | + $model->after = 'executed'; |
| 132 | + }); |
| 133 | + |
| 134 | + $api->resource( |
| 135 | + new MockResource( |
| 136 | + 'users', |
| 137 | + models: [(object) ['id' => '1']], |
| 138 | + endpoints: [$endpoint], |
| 139 | + fields: [ |
| 140 | + Attribute::make('after')->get(fn($model, $context) => $model->after ?? null), |
| 141 | + ], |
| 142 | + ), |
| 143 | + ); |
| 144 | + |
| 145 | + $response = $api->handle( |
| 146 | + $this->buildRequest('PATCH', '/users/1')->withParsedBody([ |
| 147 | + 'data' => ['type' => 'users', 'id' => '1'], |
| 148 | + ]), |
| 149 | + ); |
| 150 | + |
| 151 | + $this->assertJsonApiDocumentSubset( |
| 152 | + ['data' => ['attributes' => ['after' => 'executed']]], |
| 153 | + $response->getBody(), |
| 154 | + ); |
| 155 | + } |
94 | 156 | } |
0 commit comments