behamin/service-proxy

用于代理或使用有用工具发送请求到其他服务

v3.10.0 2023-06-04 10:01 UTC

README

具有有用工具的服务内部通信
使用laravel http客户端发送请求

安装

composer require behamin/service-proxy

发布配置

php artisan vendor:publish --provider="Behamin\ServiceProxy\Providers\ProxyServiceProvider" --tag config

添加服务

proxy.php 配置文件中添加您的项目的base url和全局头信息

return [
    /**
     * Headers added to every request
     */
    'global_headers' => [
        'Accept' => 'application/json',
        ...
    ],

    'base_url' => env('PROXY_BASE_URL', env('APP_URL')),
];

用法

常规用法

use Behamin\ServiceProxy\Proxy;

// Http Get
Proxy::withToken('Your bearer token')
    ->acceptJson()
    ->retry(3)
    ->withHeaders([
        "Content-Type" => "application\json"
    ])->get('api/articles');
    
Proxy::post('api/articles', [
    "title" => "Test title",
    "body" => "Test body"
]);

Proxy::patch('api/articles/1', [
    "title" => "Test title",
    "body" => "Test body"
]);

Proxy::put('api/articles', [
    "title" => "Test title",
    "body" => "Test body"
]);

Proxy::delete('api/articles/1');

使用http请求

use Behamin\ServiceProxy\Proxy;
use Illuminate\Http\Request;

public function index(Request $request) {
    $serviceName = 'test-service';
    Proxy::request($request, $serviceName);
}

代理事件

成功时

use Behamin\ServiceProxy\Proxy;
use Behamin\ServiceProxy\Responses\ProxyResponse;
 
Proxy::get('api/articles/1')->onSuccess(function (ProxyResponse $proxyResponse) {
        $data = $proxyResponse->data();
        $message = $proxyResponse->message();
        $response = $proxyResponse->response();
        $items = $proxyResponse->items();
        $count = $proxyResponse->count();
        ...
    });

出错时

use Behamin\ServiceProxy\Proxy;
use Behamin\ServiceProxy\Exceptions\ProxyException;
 
Proxy::get('api/articles/1')->onSuccess(function (ProxyException $proxyException) {
        $proxyResponse = $proxyException->proxyResponse;
        $trace = $proxyException->getTraceAsString();
        ...
    });

数据成功时

use Behamin\ServiceProxy\Proxy;
 
Proxy::get('api/articles/1')->onDataSuccess(function (array $data) {
        $id = $data['id'];
    });

数据收集成功时

use Behamin\ServiceProxy\Proxy;
 
Proxy::get('api/articles/1')->onCollectionSuccess(function (array $items, int $count) {
        ...
    });

代理响应方法

use Behamin\ServiceProxy\Proxy;

$proxyResponse = Proxy::get('api/articles/1');

代理请求方法

模拟代理响应

您可以在调用http方法之前使用Proxy类的mock()方法,并在您的'tests/mock'目录中传递json路径,以模拟json来伪造测试模式下的代理响应。示例

use Behamin\ServiceProxy\Proxy;
Proxy::mock('response.json')->get('address');