Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/Http/Middleware/CorrelationId.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@ public function handle(Request $request, Closure $next): Response
{
$cfg = config('microservice.correlation');
$header = $cfg['header'];
$length = (int) ($cfg['length'] ?? 36);

// Use existing header or generate a new UUID
$id = $request->header($header) ?: Str::uuid()->toString();
// Use existing header or generate a new ID of the configured length
$id = $request->header($header);
if (! $id) {
$id = Str::random($length);
}

// Set on request and response
$request->headers->set($header, $id);
Expand Down
40 changes: 40 additions & 0 deletions tests/Middleware/CorrelationIdTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Tests\Middleware;

use Illuminate\Support\Facades\Route;
use Kroderdev\LaravelMicroserviceCore\Http\Middleware\CorrelationId;
use Orchestra\Testbench\TestCase;

class CorrelationIdTest extends TestCase
{
/** @test */
public function it_generates_default_length_correlation_id()
{
$header = 'X-Correlation-ID';
$length = 36;
config()->set('microservice.correlation.header', $header);
config()->set('microservice.correlation.length', $length);

Route::middleware(CorrelationId::class)->get('/correlation-default', fn () => response()->json(['ok' => true]));

$response = $this->get('/correlation-default');

$this->assertSame($length, strlen($response->headers->get($header)));
}

/** @test */
public function it_generates_configured_length_correlation_id()
{
$header = 'X-Correlation-ID';
$length = 20;
config()->set('microservice.correlation.header', $header);
config()->set('microservice.correlation.length', $length);

Route::middleware(CorrelationId::class)->get('/correlation-custom', fn () => response()->json(['ok' => true]));

$response = $this->get('/correlation-custom');

$this->assertSame($length, strlen($response->headers->get($header)));
}
}