diff --git a/docs/fields.md b/docs/fields.md index e5160bb..44630b2 100644 --- a/docs/fields.md +++ b/docs/fields.md @@ -200,13 +200,18 @@ Str::make('email')->writableOnCreate(); ### Default Values If you would like to provide a default value to be used when creating a new -resource if there is no value provided in the request, you can pass a closure to -the `default` method: +resource if there is no value provided in the request, you can pass a closure or +a literal value to the `default` method. + +A closure will receive the current request context as an argument when called. ```php -use Tobyz\JsonApiServer\Field\DateTime; +use Tobyz\JsonApiServer\Field; -DateTime::make('joinedAt')->default(fn() => new \DateTime()); +Field\Str::make('name')->default('Anonymous'); +Field\DateTime::make('joinedAt')->default( + fn(Context $context) => new \DateTime(), +); ``` ### Required diff --git a/src/Schema/Concerns/SetsValue.php b/src/Schema/Concerns/SetsValue.php index d31b775..12384c4 100644 --- a/src/Schema/Concerns/SetsValue.php +++ b/src/Schema/Concerns/SetsValue.php @@ -51,8 +51,12 @@ public function required(bool $required = true): static /** * Set a default value for this field. */ - public function default(?Closure $default): static + public function default(mixed $default): static { + if (!$default instanceof Closure) { + $default = fn() => $default; + } + $this->default = $default; return $this; diff --git a/tests/feature/FieldDefaultTest.php b/tests/feature/FieldDefaultTest.php index 4592fbe..0aa1a38 100644 --- a/tests/feature/FieldDefaultTest.php +++ b/tests/feature/FieldDefaultTest.php @@ -17,7 +17,7 @@ public function setUp(): void $this->api = new JsonApi(); } - public function test_default_value_used_if_field_not_present() + public function test_default_closure_value_used_if_field_not_present() { $this->api->resource( new MockResource( @@ -43,6 +43,32 @@ public function test_default_value_used_if_field_not_present() ); } + public function test_default_literal_value_used_if_field_not_present() + { + $this->api->resource( + new MockResource( + 'users', + endpoints: [Create::make()], + fields: [ + Attribute::make('name') + ->writable() + ->default('default'), + ], + ), + ); + + $response = $this->api->handle( + $this->buildRequest('POST', '/users')->withParsedBody([ + 'data' => ['type' => 'users'], + ]), + ); + + $this->assertJsonApiDocumentSubset( + ['data' => ['attributes' => ['name' => 'default']]], + $response->getBody(), + ); + } + public function test_default_value_not_used_if_field_present() { $this->api->resource(