jiwei / easy-http-sdk
http client sdk generation.
0.2.2
2024-08-22 03:46 UTC
Requires
- php: >7.2.5
- ext-json: *
- guzzlehttp/guzzle: ^7.5
- psr/log: 2.0
- symfony/cache: ^5.4
- twig/twig: ^3.0
- yosymfony/toml: ^1.0
Requires (Dev)
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2025-03-09 06:57:54 UTC
README
使用
安装
composer require jiwei/easy-http-sdk
配置Option
使用 ./vendor/bin/easysdk-option -p XXX
来进行生成Option类
详情可使用 -h
来查看其他参数
class XXXOption extends Option
{
/** @var string API鉴权地址 */
private const AUTH_API_ROUTE = "/api/access/token";
/** @var int API鉴权过期时间 */
const AUTH_CACHE_EXPIRES_AT = 2400;
/** @var string 实现了AuthMiddlewareInterface 的鉴权中间件(可以不指定默认使用 JWT Breare Token的方式) */
const AUTH_MIDDLEWARE = AuthMiddlewareInterface::class;
/** @var array<string, string> API HOST */
const ENDPOINT_HOSTS = [
"local" => "127.0.0.1:9094",
"development" => "47.112.148.159:8981",
"production" => "127.0.0.1:9900",
];
/**
* 鉴权模式 需要自行实现
*
* @return Closure
*/
public function authorization(): Closure
{
return function (Client $client): string {
// 借客户端一用
$request = new Request('post', self::AUTH_API_ROUTE, [], json_encode([
"app_key" => $this->getAppId(),
"app_secret" => $this->getAppSecret()
]));
$response = $client->send($request);
if ($response->getStatusCode() >= 400) {
throw new InvalidArgumentException("invalid account.");
}
$rpcResult = json_decode($response->getBody()->getContents(), true);
if (json_last_error()) {
throw new InvalidArgumentException("invalid auth response");
}
$token = $rpcResult["token"] ?? "";
if ($token === "") {
throw new InvalidArgumentException("invalid account.");
}
return $token;
};
}
/**
* 结果处理策略,默认使用 DefaultErrorHandlingPolicy
*
* @return HandlingPolicyInterface
*/
public function handlingPolicy(): HandlingPolicyInterface
{
return new ForFormHandlingPolicy();
}
}
2. 配置 Endpoint
首先创建一个endpoint
文件夹,编写Endponit.toml
配置文件
[all]
description = "搜索XXX"
endpoint = "/api/xxx"
method = "GET"
query = [# 对应query参数,生成代码后为非必填参数
"search",
"limit",
"page"
]
cache = true # 使用 ETAG 中间件
auth = true
[Edit]
description = "修改XXX"
endpoint = "/api/xxx/{id}" # $id对应路由中的参数,生成代码后为必填参数
method = "PUT"
auth = true # 使用鉴权中间件
body = true # 使用 HTTP 请求 Body Json序列化后传递数组参数
然后使用 ./vendor/bin/easysdk -p "XXX\SDK" -v 8.1
来进行生成SDK的Endpoint类
可以使用 ./vendor/bin/easysdk -h
来查看其他参数的使用帮助。
愉快的使用
然后就可以愉快的使用了🎣