jiwei/easy-http-sdk

http client sdk generation.

0.2.1 2023-03-06 09:17 UTC

This package is auto-updated.

Last update: 2024-04-09 04:35:26 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 来查看其他参数的使用帮助。

愉快的使用

然后就可以愉快的使用了🎣