saloonphp / saloon

🤠 Build beautiful API integrations and SDKs with Saloon
https://docs.saloon.dev
MIT License
2.03k stars 105 forks source link

Using non-standard HTTP methods #411

Closed mikaeljorhult closed 3 months ago

mikaeljorhult commented 3 months ago

I'm looking into using Saloon to connect to a CalDav server. This however will require the use of non-standard HTTP methods (PROPFIND, REPORT).

Is there way to use these in Saloon requests?

Sammyjo20 commented 3 months ago

Hey @mikaeljorhult

I have never heard of these HTTP methods before! 😅 The HTTP method is an enum so I think it would be difficult to extend it... That being said you may be able to hack it slightly by writing a PSR handler in your connector. For example

Your connector

You could add a method called handlePsrRequest and change the HTTP method from a method you can add from your request class.

<?php

namespace App\Http\Integrations\Test;

use Psr\Http\Message\RequestInterface;
use Saloon\Http\Connector;
use Saloon\Http\PendingRequest;
use Saloon\Traits\Plugins\AcceptsJson;

class TestConnector extends Connector
{
    use AcceptsJson;

    /**
     * The Base URL of the API
     */
    public function resolveBaseUrl(): string
    {
        return 'https://tests.saloon.dev/api';
    }

    /**
     * Default headers for every request
     */
    protected function defaultHeaders(): array
    {
        return [];
    }

    /**
     * Default HTTP client options
     */
    protected function defaultConfig(): array
    {
        return [];
    }

    public function handlePsrRequest(RequestInterface $request, PendingRequest $pendingRequest): RequestInterface
    {
        return $request->withMethod($pendingRequest->getRequest()->getNativeMethod());
    }
}

Your request

You would add the getNativeMethod on your request like this

<?php

namespace App\Http\Integrations\Test\Requests;

use GuzzleHttp\RequestOptions;
use Saloon\Enums\Method;
use Saloon\Http\Request;

class UserRequest extends Request
{
    /**
     * The HTTP method of the request
     */
    protected Method $method = Method::GET;

    /**
     * The endpoint for the request
     */
    public function resolveEndpoint(): string
    {
        return '/user';
    }

    public function getNativeMethod(): string
    {
        return 'PROPFIND';
    }
}

With this way, you would be overwriting the protected Method $method property on your request, so this could be anything.

mikaeljorhult commented 3 months ago

Thank you @Sammyjo20! I didn't know about these HTTP methods either just last week. =) Very much an edge case though as they seem to be more or less specific to WebDAV.

Your solution is working great. I did try similar ideas but managed to miss handlePsrRequest. Thank you again and have a great week!