接口与数据 流
In the previous article, we learned how Flarum uses models to interact with data. 在这里,我们将学习如何将数据从数据库到 JSON:API 再到前端,然后再返回。
To use the built-in REST API as part of an integration, see Consuming the REST API.
API请求生命周期
在我们详细了解如何扩展 Flarum 的数据 API 之前,值得考虑一个典型的 API 请求的生命周期:
- HTTP请求已发送到 Flarum 的 API。通常情况下,这将来自 Flarum 前端,但外部程序也可以与 API 互动。 Flarum's API mostly follows the JSON:API specification, so accordingly, requests should follow said specification.
- The request is run through middleware, and routed to the proper API resource endpoint. 每个 API 资源都有一个唯一的类型,并且有一组端点。你可以在以下章节中阅读更多关于这些问题的内容。
- Any modifications done by extensions to the API Resource endpoints via the
ApiResourceextender are applied. 这可能需要更改排序,添加包括加载关系,或在默认实现运行之前或之后执行一些逻辑。 - 端点的动作被调用,产生了一些原始数据,返回给客户端。通常,这些数据将采取 Laravel Eloquent 模型收集或实例的形式,已从数据库中检索。尽管如此,只要 API 资源能够处理它,数据就可能是任何东西。有内置可复用的 CRUD 端点,但也可以实现自定义端点。
- Any modifications made through the
ApiResourceextender to the API resource's fields will be applied. 这些操作可以包括:添加新的属性或关联关系以供序列化、移除现有的属性或关联关系,或更改字段值的计算方式。 - 字段(属性和关联关系)经过序列化处理,将数据从后端数据库友好的格式转换为前端所期望的 JSON:API 格式。
- 序列化后的数据以 JSON 响应形式返回给前端。
- 如果请求是通过 Flarum 前端的
Store发出的,返回的数据 (包括任何相关对象) 将作为 frontend models 存储在前端存储中。
API 资源
我们学会了如何使用模型与数据进行互动,但我们仍然需要从后端到前端获得这种数据。我们通过为模型编写一个 API 资源,定 义模型的字段(属性和关系)、资源 API 的端点,以及一些可选的额外逻辑,如可见度范围、排序选项等。我们将在下面几节中了解到这一点。
CRUD endpoints are provided by Flarum, so you can simply add them to your API resource's endpoints() method. 它们是:
Index: Listing many instances of a model (possibly including searching/filtering)Show: Getting a single model instanceCreate: Creating a model instanceUpdate: Updating a model instanceDelete: Deleting a single model instance
Flarum uses a forked version of Toby Zerner's json-api-server. 因此,其中记录的部分内容适用于 Flarum,但并非所有内容都完全相同。
您可以使用 CLI 自动创建您的 API 资源:
$ flarum-cli make backend api-resource
Example: if you had a Label model, the LabelResource you would create could look something like this:
namespace Acme\Api;
use Acme\Label;
use Flarum\Api\Context;
use Flarum\Api\Endpoint;
use Flarum\Api\Resource\AbstractDatabaseResource;
use Flarum\Api\Schema;
/** @extends AbstractDatabaseResource<Label> */
class LabelResource extends AbstractDatabaseResource
{
public function type(): string
{
return 'labels';
}
public function model(): string
{
return Label::class;
}
public function scope(Builder $query, Context $context): void
{
$query->whereVisibleTo($context->getActor());
}
public function endpoints(): array
{
return [
Endpoint\Show::make(),
Endpoint\Create::make()
->authenticated()
->can('createLabel'),
Endpoint\Update::make()
->authenticated()
->can('edit'),
Endpoint\Delete::make()
->authenticated()
->can('delete'),
Endpoint\Index::make()
->defaultInclude(['parent']),
];
}
/*
* This is only for endpoint processing and serialization.
* You still have to create a database migration to add the table/columns.
*/
public function fields(): array
{
return [
Schema\Str::make('name')
->requiredOnCreate()
->writable(),
Schema\Str::make('description')
->writable()
->maxLength(700)
->nullable(),
Schema\Str::make('slug')
->requiredOnCreate()
->writable()
->unique('labels', 'slug', true)
->regex('/^[^\/\\ ]*$/i'),
Schema\Str::make('color')
->writable()
->nullable()
->rule('hex_color'),
Schema\Str::make('icon')
->writable()
->nullable(),
Schema\Boolean::make('isActive')
->writable(),
Schema\DateTime::make('createdAt'),
Schema\Boolean::make('canAddToDiscussion')
->get(fn (Tag $tag, FlarumContext $context) => $context->getActor()->can('addToDiscussion', $tag)),
Schema\Relationship\ToOne::make('user')
->type('users')
->includable(),
Schema\Relationship\ToOne::make('parent')
->type('labels')
->includable(),
Schema\Relationship\ToMany::make('children')
->type('labels')
->includable(),
];
}
public function sorts(): array
{
return [
SortColumn::make('createdAt'),
];
}
}
资源定义
The API resource class must extend the Flarum\Api\Resource\AbstractDatabaseResource class when interacting with Eloquent models, and Flarum\Api\Resource\AbstractResource when not. The type method should return a unique string that identifies the resource type. In the case of a database resource, the model method must return the class name of the model (::class property).
use Flarum\Api\Resource\AbstractDatabaseResource;
class LabelResource extends AbstractDatabaseResource
{
public function type(): string
{
return 'labels';
}
public function model(): string
{
return Label::class;
}
}
use Flarum\Api\Resource\AbstractResource;
class CustomResource extends AbstractResource
{
public function type(): string
{
return 'custom';
}
public function getId(object $model, Context $context): string
{
return // return the model ID.
}
public function find(string $id, Context $context): ?object
{
// return the model instance.
}
}