我正在使用 JSON:API 规范在 Laravel 中实现 API。
其中我有一个资源,我们称之为池塘,与另一个资源具有多对多关系,我们称之为鸭子。
根据 JSON:API 规范,为了删除这种关系,我应该使用 DELETE /ponds/{id}/relationships/ducks端点,并请求以下正文:
{
"data": [
{ "type": "ducks", "id": "123" },
{ "type": "ducks", "id": "987" }
]
}
Run Code Online (Sandbox Code Playgroud)
这是由 PondRemoveDucksRequest 处理的,如下所示:
<?php
...
class PondRemoveDucksRequest extends FormRequest
{
public function authorize()
{
return $this->allDucksAreRemovableByUser();
}
public function rules()
{
return [
"data.*.type" => "required|in:ducks",
"data.*.id" => "required|string|min:1"
];
}
protected function allDucksAreRemovableByUser(): bool
{
// Here goes the somewhat complex logic determining if the user is authorized
// …Run Code Online (Sandbox Code Playgroud) 在我的vanilla js项目中,我有一系列承诺:
API.POST({link to login endpoint}, "email=foo&pass=bar")
.then(() => User.initiate(API))
.then(() => console.log(User.name || 'wat'));
Run Code Online (Sandbox Code Playgroud)
除了请求类型之外,API对象的POST和GET方法看起来都相同:
GET (url, params = null) {
console.log("GET start");
return new Promise((resolve,reject) => {
this._request('GET', url, params)
.then(result => resolve(result));
});
}
POST (url, params = null) {
return new Promise((resolve,reject) => {
this._request('POST', url, params)
.then(result => resolve(result));
});
}
Run Code Online (Sandbox Code Playgroud)
...以及负责发送请求的_request方法:
_request (type, url, params = null) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open(type,url,true);
xhr.withCredentials …Run Code Online (Sandbox Code Playgroud)