金山 / persist-rest
\Kingsoft\Persist 类的 REST 接口
2.9.0
2024-09-09 12:08 UTC
Requires
- kingsoft/db: ^2.7
- kingsoft/http: ^3.7.10
- kingsoft/persist: ^3.0
- psr/log: ^3.0
README
此包使用 \Kingsoft\Http, \Kingsoft\PersistDb 来公开 PersistDb discover.php
发现的所有表和视图,以及那些添加到 allowedEndPoints
列表中的视图。如果不在该列表中,API 将返回 404
。因此其他数据是安全的。表或视图可以通过 GET、POST、PUT、DELETE 请求访问,但也可以使用 allowedMethods
进行限制。请求遵循 rfc9205 标准,并有一些扩展。
- POST
https://example.com/resource
将创建一个包含在 json 有效负载中指定值的新的记录。如果记录的 autoincrment 为 true,则创建并返回一个新的 ID(C) - GET
https://example.com/resource
获取受maxresults
限制的所有资源的列表(R) - GET
https://example.com/resource[n,c]
获取从位置n
开始的资源列表,限制为c
。响应将包括分页链接。(R) - GET
https://example.com/resurce/<id>
获取指定id
的记录(R) - GET
https://example.com/resurce?<key>=<value>
获取所有属性key
=value
的资源。使用&
组合多个(R) - GET
https://example.com/resurce?<key>=!<value>
获取所有属性key
!=value
的资源。(R) - GET
https://example.com/resurce?<key>=U<value1>,<value2>
获取所有属性key
IN (value1
,value2
) 的资源。其他运算符也是可用的。请参阅 \Kingsoft\Persist 了解这些(R) - PUT
https://example.com/resource/<id>
将在 json 有效负载中设置新的值(U) - DELETE
https://example.com/resource/<id>
删除指定id
的资源(D)
因此,该接口为所有公开的资源(表、视图)创建了一个完整的 CRUD 接口。然而,请注意,视图通常不能更新。因此,请确保您的视图包含主底层表的关键字。我还没有找到检索底层表(MySQL、MariaDB)的方法,因此目前无法自动化此操作。GET 结果存储在 json 响应中的 resources
对象中,同时包含链接和其他消息,以创建半级 3。
通过观察 OPTION 方法并返回适当的提示来处理预检。
示例用法
use Kingsoft\Http\{StatusCode, Response}; use Kingsoft\PersistRest\{PersistRest, PersistRequest}; try { $request = new PersistRequest( ['Test', 'TestView'], "GET, POST", "client.example.com", ); $request->setLogger( LOG ); $api = new PersistRest( $request, LOG ); $api->handleRequest(); } catch ( Exception $e ) { Response::sendError( $e->getMessage(), StatusCode::InternalServerError->value ); }
当然,可以从配置文件中读取构造函数参数。
添加 allowedendpoints
Kingsoft persist-db
要使用 Kingsoft\Persist-db
创建允许的端点,请使用 http://example.com/vendor/kingsoft/persist-db/src/discover/
生成它们,然后按照以下步骤操作
- 将 allowedendpoints 设置复制到 ini 文件中,并将 psr-4 部分
- 复制到
composer.json
中。之后,请确保使用以下命令重新加载自动加载器
composer dump-autoload
并且为了使用美观的 URL,需要 htpasswd
<FilesMatch "\.(?:ini|htaccess)$"> Order allow,deny Deny from all </FilesMatch> RewriteEngine On RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d RewriteRule ^ - [L] RewriteRule ^ /api/index.php