Closed makowskid closed 2 years ago
<?php
namespace App\JsonApi\Fields;
use LaravelJsonApi\Contracts\Schema\IdEncoder;
use LaravelJsonApi\Eloquent\Fields\ID;
class EfficientUuidEncodedId extends ID implements IdEncoder
{
/**
* Encode the model key to a JSON:API resource ID.
*
* @param string|int $modelKey
* @return string
*/
public function encode($modelKey): string
{
// encode the model key - no need, auto casting
return $modelKey;
}
/**
* Decode the JSON:API resource ID to a model key (id).
*
* Implementations must return `null` if the value cannot be
* decoded to a model key.
*
* @param string $resourceId
* @return string|int|null
*/
public function decode(string $resourceId): int|string|null
{
// decode the JSON:API resource id
return uuid2bin($resourceId);
}
}
Great, thanks for sharing. Good to know you're able to write your own ID field for this scenario, as the package was designed so people could write their own fields!
I'm going to close this issue as there's nothing for me to do with it, but hopefully people will find it if searching for this scenario.
@lindyhopchris yeah, that was my intention, so this can be found next to the package. Just a thought - maybe you can add this as a plugin in the package that can be turned on? Reason - handling UUIDs in APIs is an extremely often happening scenario, binary UUIDs are also used very often these days.
Aaaa also - Needed to add this helper:
if (!function_exists('uuid2bin')) {
/**
* Returns binary format from UUID string
*
* @param $uuid
* @return string
*/
function uuid2bin($uuid): string
{
return \Ramsey\Uuid\Uuid::fromString($uuid)->getBytes();
}
}
and package: https://github.com/ramsey/uuid
@makowskid if there's enough demand then I could add this as a package, but it's a maintenance overhead. Someone could always publish their own package if that helps.
I had to create this ID decoder to have my code compatible with https://github.com/michaeldyrynda/laravel-efficient-uuid. Maybe somebody will find this useful.
` <?php
namespace App\JsonApi\Fields;
use LaravelJsonApi\Contracts\Schema\IdEncoder; use LaravelJsonApi\Eloquent\Fields\ID;
class EfficientUuidEncodedId extends ID implements IdEncoder { /**
@return string */ public function encode($modelKey): string { // encode the model key - no need, auto casting return $modelKey; }
/**
null
if the value cannot be