Skip to content

feat(client): allow overriding of Accept header per request #347

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 4, 2025

Conversation

manchenkoff
Copy link
Owner

Is your PR related to a specific issue/feature? Please describe and mention issues.

Allows users to override Accept header value for custom scenarios, when non-JSON response is expected.

For example, when using StreamResponse in Laravel

final class QuoteController extends Controller
{
    public function __invoke(Request $request): JsonResponse|StreamedResponse
    {
        /** @var string $quote */
        $quote = Inspiring::quotes()->random();
        [$text, $author] = explode(' - ', $quote);

        if ($request->header('Accept') === 'text/event-stream') {
            return response()->eventStream(
                function () use ($text, $author) {
                    yield $text;
                }
            );
        }

        $data = [
            'text' => $text,
            'author' => $author,
        ];

        return response()->json($data);
    }
}

In this case, in the Nuxt application we can make a request by using useSanctumClient like this:

const sanctumFetch = useSanctumClient()
const response = await sanctumFetch<ReadableStream, 'stream'>(
    '/api/quote',
    {
        headers: {
            Accept: 'text/event-stream',
        },
        responseType: 'stream',
    },
)

const reader = response.pipeThrough(new TextDecoderStream()).getReader()

while (true) {
    const { value, done } = await reader.read()

    if (done)
        break

    console.log('Received:', value)
}

@manchenkoff manchenkoff merged commit bce0620 into main Apr 4, 2025
4 checks passed
@manchenkoff manchenkoff deleted the stream-response branch April 4, 2025 23:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant