Skip to content

Commit 20a3ed6

Browse files
authored
Merge pull request #4 from KroderDev/codex/implement-correlation-id-generation
Respect configured correlation ID length
2 parents eada1e5 + 834ec3f commit 20a3ed6

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

src/Http/Middleware/CorrelationId.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,13 @@ public function handle(Request $request, Closure $next): Response
1919
{
2020
$cfg = config('microservice.correlation');
2121
$header = $cfg['header'];
22+
$length = (int) ($cfg['length'] ?? 36);
2223

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

2630
// Set on request and response
2731
$request->headers->set($header, $id);
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace Tests\Middleware;
4+
5+
use Illuminate\Support\Facades\Route;
6+
use Kroderdev\LaravelMicroserviceCore\Http\Middleware\CorrelationId;
7+
use Orchestra\Testbench\TestCase;
8+
9+
class CorrelationIdTest extends TestCase
10+
{
11+
/** @test */
12+
public function it_generates_default_length_correlation_id()
13+
{
14+
$header = 'X-Correlation-ID';
15+
$length = 36;
16+
config()->set('microservice.correlation.header', $header);
17+
config()->set('microservice.correlation.length', $length);
18+
19+
Route::middleware(CorrelationId::class)->get('/correlation-default', fn () => response()->json(['ok' => true]));
20+
21+
$response = $this->get('/correlation-default');
22+
23+
$this->assertSame($length, strlen($response->headers->get($header)));
24+
}
25+
26+
/** @test */
27+
public function it_generates_configured_length_correlation_id()
28+
{
29+
$header = 'X-Correlation-ID';
30+
$length = 20;
31+
config()->set('microservice.correlation.header', $header);
32+
config()->set('microservice.correlation.length', $length);
33+
34+
Route::middleware(CorrelationId::class)->get('/correlation-custom', fn () => response()->json(['ok' => true]));
35+
36+
$response = $this->get('/correlation-custom');
37+
38+
$this->assertSame($length, strlen($response->headers->get($header)));
39+
}
40+
}

0 commit comments

Comments
 (0)