LaraflareDocsFrameworkPackagesReleases13.x

Docs / Digging Deeper / HTTP Client

HTTP Client

Introduction

Laraflare provides an expressive, minimal API around fetch, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laraflare's HTTP client is focused on the most common use cases and a wonderful developer experience.

Note

A Worker has no cURL or sockets, so the client sends every request with fetch. Every request method is therefore asynchronous: await the result.

Making Requests

To make requests, you may use the head, get, post, put, patch, and delete methods provided by the Http facade. First, let's examine how to make a basic GET request to another URL:

import { Http } from '@laraflare/framework';

const response = await Http.get('http://example.com');

The get method returns an instance of ClientResponse, which provides a variety of methods that may be used to inspect the response:

response.body(): string;
response.json(key = null, fallback = null, flags = null): any;
response.object(): any;
response.collect(key = null): Collection;
response.resource(): ReadableStream<Uint8Array>;
response.status(): number;
response.successful(): boolean;
response.redirect(): boolean;
response.failed(): boolean;
response.clientError(): boolean;
response.header(header): string;
response.headers(): Record<string, string[]>;

A response has no bracket access, so read the JSON response data with the json method:

return (await Http.get('http://example.com/users/1')).json('name');

In addition to the response methods listed above, the following methods may be used to determine if the response has a specific status code:

response.ok(): boolean;                  // 200 OK
response.created(): boolean;             // 201 Created
response.accepted(): boolean;            // 202 Accepted
response.noContent(): boolean;           // 204 No Content
response.movedPermanently(): boolean;    // 301 Moved Permanently
response.found(): boolean;               // 302 Found
response.badRequest(): boolean;          // 400 Bad Request
response.unauthorized(): boolean;        // 401 Unauthorized
response.paymentRequired(): boolean;     // 402 Payment Required
response.forbidden(): boolean;           // 403 Forbidden
response.notFound(): boolean;            // 404 Not Found
response.requestTimeout(): boolean;      // 408 Request Timeout
response.conflict(): boolean;            // 409 Conflict
response.unprocessableEntity(): boolean; // 422 Unprocessable Entity
response.tooManyRequests(): boolean;     // 429 Too Many Requests
response.serverError(): boolean;         // >= 500 Server Error

URI Templates

The HTTP client also allows you to construct request URLs using the URI template specification. To define the URL parameters that can be expanded by your URI template, you may use the withUrlParameters method:

await Http.withUrlParameters({
    endpoint: 'https://laraflare.com',
    page: 'docs',
    version: '13.x',
    topic: 'validation',
}).get('{+endpoint}/{page}/{version}/{topic}');

Dumping Requests

If you would like to dump the outgoing request instance before it is sent and end the process, you may add the dd method to the beginning of your request definition:

return Http.dd().get('http://example.com');

Request Data

Of course, it is common when making POST, PUT, and PATCH requests to send additional data with your request, so these methods accept an object of data as their second argument. By default, data will be sent using the application/json content type:

import { Http } from '@laraflare/framework';

const response = await Http.post('http://example.com/users', {
    name: 'Steve',
    role: 'Network Administrator',
});

GET Request Query Parameters

When making GET requests, you may either append a query string to the URL directly or pass an object of key / value pairs as the second argument to the get method:

const response = await Http.get('http://example.com/users', {
    name: 'Taylor',
    page: 1,
});

Alternatively, the withQueryParameters method may be used:

await Http.retry(3, 100).withQueryParameters({
    name: 'Taylor',
    page: 1,
}).get('http://example.com/users');

Sending Form URL Encoded Requests

If you would like to send data using the application/x-www-form-urlencoded content type, you should call the asForm method before making your request:

const response = await Http.asForm().post('http://example.com/users', {
    name: 'Sara',
    role: 'Privacy Consultant',
});

Sending a Raw Request Body

You may use the withBody method if you would like to provide a raw request body when making a request. The content type may be provided via the method's second argument:

const response = await Http.withBody(
    photo, 'image/jpeg'
).post('http://example.com/photo');

Multi-Part Requests

If you would like to send files as multi-part requests, you should call the attach method before making your request. This method accepts the name of the file and its contents. If needed, you may provide a third argument which will be considered the file's filename, while a fourth argument may be used to provide headers associated with the file:

import { readFileSync } from 'node:fs';

const response = await Http.attach(
    'attachment', readFileSync('photo.jpg'), 'photo.jpg', { 'Content-Type': 'image/jpeg' }
).post('http://example.com/attachments');

Headers

Headers may be added to requests using the withHeaders method. This withHeaders method accepts an object of key / value pairs:

const response = await Http.withHeaders({
    'X-First': 'foo',
    'X-Second': 'bar',
}).post('http://example.com/users', {
    name: 'Taylor',
});

You may use the accept method to specify the content type that your application is expecting in response to your request:

const response = await Http.accept('application/json').get('http://example.com/users');

For convenience, you may use the acceptJson method to quickly specify that your application expects the application/json content type in response to your request:

const response = await Http.acceptJson().get('http://example.com/users');

The withHeaders method merges new headers into the request's existing headers. If needed, you may replace all of the headers entirely using the replaceHeaders method:

const response = await Http.withHeaders({
    'X-Original': 'foo',
}).replaceHeaders({
    'X-Replacement': 'bar',
}).post('http://example.com/users', {
    name: 'Taylor',
});

Authentication

You may specify basic and digest authentication credentials using the withBasicAuth and withDigestAuth methods, respectively:

// Basic authentication...
const response = await Http.withBasicAuth('taylor@example.com', 'secret').post(/* ... */);

// Digest authentication...
const response = await Http.withDigestAuth('taylor@example.com', 'secret').post(/* ... */);

Note

fetch cannot answer a digest challenge, so sending a request that uses withDigestAuth throws.

Bearer Tokens

If you would like to quickly add a bearer token to the request's Authorization header, you may use the withToken method:

const response = await Http.withToken('token').post(/* ... */);

Timeout

The timeout method may be used to specify the maximum number of seconds to wait for a response. By default, the HTTP client will timeout after 30 seconds:

const response = await Http.timeout(3).get(/* ... */);

If the given timeout is exceeded, an instance of ConnectionException will be thrown.

You may specify the maximum number of seconds to wait while trying to connect to a server using the connectTimeout method. The default is 10 seconds:

const response = await Http.connectTimeout(3).get(/* ... */);

Note

fetch has no separate connect phase, so timeout bounds the whole request and connectTimeout only records the option.

Retries

If you would like the HTTP client to automatically retry the request if a client or server error occurs, you may use the retry method. The retry method accepts the maximum number of times the request should be attempted and the number of milliseconds that laraflare should wait in between attempts:

const response = await Http.retry(3, 100).post(/* ... */);

If you would like to manually calculate the number of milliseconds to sleep between attempts, you may pass a closure as the second argument to the retry method:

const response = await Http.retry(3, (attempt: number, exception: Error) => {
    return attempt * 100;
}).post(/* ... */);

For convenience, you may also provide an array as the first argument to the retry method. This array will be used to determine how many milliseconds to sleep between subsequent attempts:

const response = await Http.retry([100, 200]).post(/* ... */);

If needed, you may pass a third argument to the retry method. The third argument should be a callable that determines if the retries should actually be attempted. For example, you may wish to only retry the request if the initial request encounters a ConnectionException:

import { ConnectionException, Http, PendingRequest } from '@laraflare/framework';

const response = await Http.retry(3, 100, (exception: Error, request: PendingRequest) => {
    return exception instanceof ConnectionException;
}).post(/* ... */);

If a request attempt fails, you may wish to make a change to the request before a new attempt is made. You can achieve this by modifying the request argument provided to the callable you provided to the retry method. For example, you might want to retry the request with a new authorization token if the first attempt returned an authentication error:

import { Http, PendingRequest, RequestException } from '@laraflare/framework';

const response = await Http.withToken(this.getToken()).retry(2, 0, (exception: Error, request: PendingRequest) => {
    if (! (exception instanceof RequestException) || exception.response.status() !== 401) {
        return false;
    }

    request.withToken(this.getNewToken());

    return true;
}).post(/* ... */);

If all of the requests fail, an instance of RequestException will be thrown. If you would like to disable this behavior, you may pass false as the fourth argument to the retry method. When disabled, the last response received by the client will be returned after all retries have been attempted:

const response = await Http.retry(3, 100, null, false).post(/* ... */);

Warning

If all of the requests fail because of a connection issue, a ConnectionException will still be thrown even when the fourth argument is false.

Error Handling

Laraflare's HTTP client does not throw exceptions on client or server errors (400 and 500 level responses from servers). You may determine if one of these errors was returned using the successful, clientError, or serverError methods:

// Determine if the status code is >= 200 and < 300...
response.successful();

// Determine if the status code is >= 400...
response.failed();

// Determine if the response has a 400 level status code...
response.clientError();

// Determine if the response has a 500 level status code...
response.serverError();

// Immediately execute the given callback if there was a client or server error...
response.onError(callback);

Throwing Exceptions

If you have a response instance and would like to throw an instance of RequestException if the response status code indicates a client or server error, you may use the throw or throwIf methods:

import { ClientResponse, Http } from '@laraflare/framework';

const response = await Http.post(/* ... */);

// Throw an exception if a client or server error occurred...
response.throw();

// Throw an exception if an error occurred and the given condition is true...
response.throwIf(condition);

// Throw an exception if an error occurred and the given closure resolves to true...
response.throwIf((response: ClientResponse) => true);

// Throw an exception if an error occurred and the given condition is false...
response.throwUnless(condition);

// Throw an exception if an error occurred and the given closure resolves to false...
response.throwUnless((response: ClientResponse) => false);

// Throw an exception if the response has a specific status code...
response.throwIfStatus(403);

// Throw an exception unless the response has a specific status code...
response.throwUnlessStatus(200);

// Throw an exception if a server error occurred (status >= 500)...
response.throwIfServerError();

// Throw an exception if a client error occurred (status >= 400 and < 500)...
response.throwIfClientError();

return response.json('user.id');

The RequestException instance has a public response property which will allow you to inspect the returned response.

The throw method returns the response instance if no error occurred, allowing you to chain other operations onto the throw method:

return (await Http.post(/* ... */)).throw().json();

If you would like to perform some additional logic before the exception is thrown, you may pass a closure to the throw method. The exception will be thrown automatically after the closure is invoked, so you do not need to re-throw the exception from within the closure:

import { ClientResponse, Http, RequestException } from '@laraflare/framework';

return (await Http.post(/* ... */)).throw((response: ClientResponse, e: RequestException) => {
    // ...
}).json();

By default, RequestException messages are truncated to 120 characters when logged or reported. To customize or disable this behavior, you may utilize the truncateAt and dontTruncate methods when configuring your application's registered behavior in your bootstrap/app.ts file:

import { RequestException } from '@laraflare/framework';

.registered(() => {
    // Truncate request exception messages to 240 characters...
    RequestException.truncateAt(240);

    // Disable request exception message truncation...
    RequestException.dontTruncate();
})

Alternatively, you may customize the exception truncation behavior per request using the truncateExceptionsAt method:

return Http.truncateExceptionsAt(240).post(/* ... */);

Middleware

You may take advantage of middleware to manipulate the outgoing request or inspect the incoming response. A middleware works on the client's request and response objects (Psr7Request and Psr7Response), which are immutable: each with method returns a new object. To manipulate the outgoing request, register a middleware via the withRequestMiddleware method:

import { Http, Psr7Request } from '@laraflare/framework';

const response = await Http.withRequestMiddleware(
    (request: Psr7Request) => {
        return request.withHeader('X-Example', 'Value');
    }
).get('http://example.com');

Likewise, you can inspect the incoming HTTP response by registering a middleware via the withResponseMiddleware method:

import { Http, Psr7Response } from '@laraflare/framework';

const response = await Http.withResponseMiddleware(
    (response: Psr7Response) => {
        const header = response.getHeader('X-Example');

        // ...

        return response;
    }
).get('http://example.com');

Global Middleware

Sometimes, you may want to register a middleware that applies to every outgoing request and incoming response. To accomplish this, you may use the globalRequestMiddleware and globalResponseMiddleware methods. Typically, these methods should be invoked in the boot method of your application's AppServiceProvider:

import { Http } from '@laraflare/framework';

Http.globalRequestMiddleware((request) => request.withHeader(
    'User-Agent', 'Example Application/1.0'
));

Http.globalResponseMiddleware((response) => response.withHeader(
    'X-Finished-At', new Date().toISOString()
));

Request Options

You may specify additional request options for an outgoing request using the withOptions method, such as timeout, allow_redirects and headers, along with fetch's own options (cache, signal, cf). The withOptions method accepts an object of key / value pairs:

const response = await Http.withOptions({
    timeout: 5,
}).get('http://example.com/users');

Global Options

To configure default options for every outgoing request, you may utilize the globalOptions method. Typically, this method should be invoked from the boot method of your application's AppServiceProvider:

import { Http, ServiceProvider } from '@laraflare/framework';

export class AppServiceProvider extends ServiceProvider {
    /**
     * Bootstrap any application services.
     */
    override boot(): void {
        Http.globalOptions({
            allow_redirects: false,
        });
    }
}

Concurrent Requests

Sometimes, you may wish to make multiple HTTP requests concurrently. In other words, you want several requests to be dispatched at the same time instead of issuing the requests sequentially. This can lead to substantial performance improvements when interacting with slow HTTP APIs.

Request Pooling

Thankfully, you may accomplish this using the pool method. The pool method accepts a closure which receives a Pool instance, allowing you to easily add requests to the request pool for dispatching:

import { Http, Pool } from '@laraflare/framework';

const responses = await Http.pool((pool: Pool) => [
    pool.get('http://localhost/first'),
    pool.get('http://localhost/second'),
    pool.get('http://localhost/third'),
]);

return responses[0].ok() &&
       responses[1].ok() &&
       responses[2].ok();

As you can see, each response instance can be accessed based on the order it was added to the pool. If you wish, you can name the requests using the as method, which allows you to access the corresponding responses by name:

import { Http, Pool } from '@laraflare/framework';

const responses = await Http.pool((pool: Pool) => [
    pool.as('first').get('http://localhost/first'),
    pool.as('second').get('http://localhost/second'),
    pool.as('third').get('http://localhost/third'),
]);

return responses.first.ok();

The maximum concurrency of the request pool may be controlled by providing the second argument to the pool method. This value determines the maximum number of HTTP requests that may be concurrently in-flight while processing the request pool:

const responses = await Http.pool((pool: Pool) => [
    // ...
], 5);

If a pooled request fails at the connection level (for example, a timeout or DNS failure), the corresponding entry in the responses array will be a ConnectionException instance instead of a ClientResponse instance:

for (const response of responses) {
    if (response instanceof Error) {
        // The request failed to connect...
    } else if (response.failed()) {
        // The request connected but received an error response...
    }
}

Customizing Concurrent Requests

The pool method cannot be chained with other HTTP client methods such as the withHeaders or withMiddleware methods. If you want to apply custom headers or middleware to pooled requests, you should configure those options on each request in the pool:

import { Http, Pool } from '@laraflare/framework';

const headers = {
    'X-Example': 'example',
};

const responses = await Http.pool((pool: Pool) => [
    pool.withHeaders(headers).get('http://example.test/test'),
    pool.withHeaders(headers).get('http://example.test/test'),
    pool.withHeaders(headers).get('http://example.test/test'),
]);

Request Batching

Another way of working with concurrent requests in laraflare is to use the batch method. Like the pool method, it accepts a closure which receives an HttpBatch instance, allowing you to easily add requests to the request pool for dispatching, but it also allows you to define completion callbacks:

import {
    ClientResponse,
    ConnectionException,
    Http,
    HttpBatch,
    RequestException,
} from '@laraflare/framework';

const responses = await Http.batch((batch: HttpBatch) => [
    batch.get('http://localhost/first'),
    batch.get('http://localhost/second'),
    batch.get('http://localhost/third'),
]).before((batch: HttpBatch) => {
    // The batch has been created but no requests have been initialized...
}).progress((batch: HttpBatch, key: number | string, response: ClientResponse) => {
    // An individual request has completed successfully...
}).then((batch: HttpBatch, results) => {
    // All requests completed successfully...
}).catch((batch: HttpBatch, key: number | string, response: ClientResponse | RequestException | ConnectionException) => {
    // Batch request failure detected...
}).finally((batch: HttpBatch, results) => {
    // The batch has finished executing...
}).send();

Like the pool method, you can use the as method to name your requests:

const responses = await Http.batch((batch: HttpBatch) => [
    batch.as('first').get('http://localhost/first'),
    batch.as('second').get('http://localhost/second'),
    batch.as('third').get('http://localhost/third'),
]).send();

After a batch is started by calling the send method, you can't add new requests to it. Trying to do so will result in a BatchInProgressException exception being thrown.

The maximum concurrency of the request batch may be controlled via the concurrency method. This value determines the maximum number of HTTP requests that may be concurrently in-flight while processing the request batch:

const responses = await Http.batch((batch: HttpBatch) => [
    // ...
]).concurrency(5).send();

Inspecting Batches

The HttpBatch instance that is provided to batch completion callbacks has a variety of properties and methods to assist you in interacting with and inspecting a given batch of requests:

// The number of requests assigned to the batch...
batch.totalRequests;

// The number of requests that have not been processed yet...
batch.pendingRequests;

// The number of requests that have failed...
batch.failedRequests;

// The number of requests that have been processed thus far...
batch.processedRequests();

// Indicates if the batch has finished executing...
batch.finished();

// Indicates if the batch has request failures...
batch.hasFailures();

Deferring Batches

When the defer method is invoked, the batch of requests is not executed immediately. Instead, laraflare will execute the batch after the current application request's HTTP response has been sent to the user, keeping your application feeling fast and responsive:

import { Http, HttpBatch } from '@laraflare/framework';

Http.batch((batch: HttpBatch) => [
    batch.get('http://localhost/first'),
    batch.get('http://localhost/second'),
    batch.get('http://localhost/third'),
]).then((batch: HttpBatch, results) => {
    // All requests completed successfully...
}).defer();

Macros

The HTTP client allows you to define "macros", which can serve as a fluent, expressive mechanism to configure common request paths and headers when interacting with services throughout your application. To get started, you may define the macro within the boot method of your application's AppServiceProvider class:

import { Http, ServiceProvider } from '@laraflare/framework';

export class AppServiceProvider extends ServiceProvider {
    /**
     * Bootstrap any application services.
     */
    override boot(): void {
        Http.macro('github', function () {
            return Http.withHeaders({
                'X-Example': 'example',
            }).baseUrl('https://github.com');
        });
    }
}

Once your macro has been configured, you may invoke it from anywhere in your application to create a pending request with the specified configuration:

const response = await Http.github().get('/');

Testing

Many laraflare services provide functionality to help you easily and expressively write tests, and the HTTP client is no exception. The Http facade's fake method allows you to instruct the HTTP client to return stubbed / dummy responses when requests are made.

Faking Responses

For example, to instruct the HTTP client to return empty, 200 status code responses for every request, you may call the fake method with no arguments:

import { Http } from '@laraflare/framework';

Http.fake();

const response = await Http.post(/* ... */);

Faking Specific URLs

Alternatively, you may pass an object to the fake method. The object's keys should represent URL patterns that you wish to fake and their associated responses. The * character may be used as a wildcard character. You may use the Http facade's response method to construct stub / fake responses for these endpoints:

Http.fake({
    // Stub a JSON response for GitHub endpoints...
    'github.com/*': Http.response({ foo: 'bar' }, 200, headers),

    // Stub a string response for Google endpoints...
    'google.com/*': Http.response('Hello World', 200, headers),
});

Any requests made to URLs that have not been faked will actually be executed. If you would like to specify a fallback URL pattern that will stub all unmatched URLs, you may use a single * character:

Http.fake({
    // Stub a JSON response for GitHub endpoints...
    'github.com/*': Http.response({ foo: 'bar' }, 200, { Headers: 'value' }),

    // Stub a string response for all other endpoints...
    '*': Http.response('Hello World', 200, { Headers: 'value' }),
});

For convenience, simple string, JSON, and empty responses may be generated by providing a string, object, or number as the response:

Http.fake({
    'google.com/*': 'Hello World',
    'github.com/*': { foo: 'bar' },
    'chatgpt.com/*': 200,
});

Calling fake again does not replace the stubs you have already registered. New stubs are added after the existing ones, and the first stub that matches a request's URL provides its response. So if a test fakes a URL and later calls fake with the same URL pattern, the earlier stub keeps responding. Every matching stub is still invoked on each request, so a response sequence registered for the same URL is consumed even when an earlier stub provides the response.

Faking Exceptions

Sometimes you may need to test your application's behavior if the HTTP client encounters a ConnectionException when attempting to make a request. You can instruct the HTTP client to throw a connection exception using the failedConnection method:

Http.fake({
    'github.com/*': Http.failedConnection(),
});

To test your application's behavior if a RequestException is thrown, you may use the failedRequest method:

throw Http.failedRequest({ code: 'not_found' }, 404);

Faking Response Sequences

Sometimes you may need to specify that a single URL should return a series of fake responses in a specific order. You may accomplish this using the Http.sequence method to build the responses:

Http.fake({
    // Stub a series of responses for GitHub endpoints...
    'github.com/*': Http.sequence()
        .push('Hello World', 200)
        .push({ foo: 'bar' }, 200)
        .pushStatus(404),
});

When all the responses in a response sequence have been consumed, any further requests will cause the response sequence to throw an exception. If you would like to specify a default response that should be returned when a sequence is empty, you may use the whenEmpty method:

Http.fake({
    // Stub a series of responses for GitHub endpoints...
    'github.com/*': Http.sequence()
        .push('Hello World', 200)
        .push({ foo: 'bar' }, 200)
        .whenEmpty(Http.response()),
});

If you would like to fake a sequence of responses but do not need to specify a specific URL pattern that should be faked, you may use the Http.fakeSequence method:

Http.fakeSequence()
    .push('Hello World', 200)
    .whenEmpty(Http.response());

Fake Callback

If you require more complicated logic to determine what responses to return for certain endpoints, you may pass a closure to the fake method. This closure will receive an instance of ClientRequest and should return a response instance. Within your closure, you may perform whatever logic is necessary to determine what type of response to return:

import { ClientRequest, Http } from '@laraflare/framework';

Http.fake((request: ClientRequest) => {
    return Http.response('Hello World', 200);
});

Inspecting Requests

When faking responses, you may occasionally wish to inspect the requests the client receives in order to make sure your application is sending the correct data or headers. You may accomplish this by calling the Http.assertSent method after calling Http.fake.

The assertSent method accepts a closure which will receive a ClientRequest instance and should return a boolean value indicating if the request matches your expectations. In order for the test to pass, at least one request must have been issued matching the given expectations:

import { ClientRequest, Http } from '@laraflare/framework';

Http.fake();

await Http.withHeaders({
    'X-First': 'foo',
}).post('http://example.com/users', {
    name: 'Taylor',
    role: 'Developer',
});

Http.assertSent((request: ClientRequest) => {
    return request.hasHeader('X-First', 'foo') &&
           request.url() === 'http://example.com/users' &&
           request.data().name === 'Taylor' &&
           request.data().role === 'Developer';
});

If needed, you may assert that a specific request was not sent using the assertNotSent method:

import { ClientRequest, Http } from '@laraflare/framework';

Http.fake();

await Http.post('http://example.com/users', {
    name: 'Taylor',
    role: 'Developer',
});

Http.assertNotSent((request: ClientRequest) => {
    return request.url() === 'http://example.com/posts';
});

You may use the assertSentCount method to assert how many requests were "sent" during the test:

Http.fake();

Http.assertSentCount(5);

Or, you may use the assertNothingSent method to assert that no requests were sent during the test:

Http.fake();

Http.assertNothingSent();

Recording Requests / Responses

You may use the recorded method to gather all requests and their corresponding responses. The recorded method returns a collection of arrays that contains instances of ClientRequest and ClientResponse:

Http.fake({
    'https://laraflare.com': Http.response(null, 500),
    'https://example.com/': Http.response(),
});

await Http.get('https://laraflare.com');
await Http.get('https://example.com/');

const recorded = Http.recorded();

const [request, response] = recorded.all()[0];

Additionally, the recorded method accepts a closure which will receive an instance of ClientRequest and ClientResponse and may be used to filter request / response pairs based on your expectations:

import { ClientRequest, ClientResponse, Http } from '@laraflare/framework';

Http.fake({
    'https://laraflare.com': Http.response(null, 500),
    'https://example.com/': Http.response(),
});

await Http.get('https://laraflare.com');
await Http.get('https://example.com/');

const recorded = Http.recorded((request: ClientRequest, response: ClientResponse) => {
    return request.url() !== 'https://laraflare.com' &&
           response.successful();
});

Preventing Stray Requests

If you would like to ensure that all requests sent via the HTTP client have been faked throughout your individual test or complete test suite, you can call the preventStrayRequests method. After calling this method, any requests that do not have a corresponding fake response will throw an exception rather than making the actual HTTP request:

import { Http } from '@laraflare/framework';

Http.preventStrayRequests();

Http.fake({
    'github.com/*': Http.response('ok'),
});

// An "ok" response is returned...
await Http.get('https://github.com/example/project');

// An exception is thrown...
await Http.get('https://laraflare.com');

Sometimes, you may wish to prevent most stray requests while still allowing specific requests to execute. To accomplish this, you may pass an array of URL patterns to the allowStrayRequests method. Any request matching one of the given patterns will be allowed, while all other requests will continue to throw an exception:

import { Http } from '@laraflare/framework';

Http.preventStrayRequests();

Http.allowStrayRequests([
    'http://127.0.0.1:5000/*',
]);

// This request is executed...
await Http.get('http://127.0.0.1:5000/generate');

// An exception is thrown...
await Http.get('https://laraflare.com');

Events

Laraflare fires three events during the process of sending HTTP requests. The RequestSending event is fired prior to a request being sent, while the ResponseReceived event is fired after a response is received for a given request. The ConnectionFailed event is fired if no response is received for a given request.

The RequestSending and ConnectionFailed events both contain a public request property that you may use to inspect the ClientRequest instance. Likewise, the ResponseReceived event contains a request property as well as a response property which may be used to inspect the ClientResponse instance. You may create event listeners for these events within your application:

import { Event, RequestSending } from '@laraflare/framework';

Event.listen(RequestSending, (event: RequestSending) => {
    // event.request ...
});
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.