因子/fe-json-api-utilities

因子 E JSON 工具

安装量: 1,768

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 1

分支: 0

类型:typo3-cms-extension

v1.4.2 2024-03-25 12:16 UTC

This package is auto-updated.

Last update: 2024-09-25 13:21:04 UTC


README

目的

这个 TYPO3 扩展帮助扩展开发者设置简单的基于 JSON 的 API。它提供了一些辅助方法和类,可以

  • 解析 JSON 请求数据
  • 构建、丰富并发送 JSON 响应
  • 将 TYPO3 特定模型和对象存储转换为结构化数组

动机

我们最近的一些项目需要在前端框架(如 Vue)中实现的小部件和组件。为了有效地利用这些前端组件,通常需要通过 JSON 请求和响应与 TYPO3 后端进行通信。

由于这些通常是高度独立的组件,不需要完全成熟的(无头)API,因此像 TYPO3 headless 或 t3api 这样的扩展非常引人注目,但在我们的使用场景中可能会过于冗余。因此,我们决定采用这个轻量级、自维护的解决方案。

用法

JSON 请求

如果您想处理请求中的 POST 数据,请创建一个新实例,并确保使用 parseJsonBody()getDecodedData() 方法。用法非常基础 - 在 Extbase 控制器上下文中的示例

use Faktore\FeJsonApiUtilities\Utility\JsonRequestUtility;

class EventsJsonApiController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    protected JsonRequestUtility $jsonRequestUtility;
    
    // constructor with dependency injection
    public function __construct(JsonRequestUtility $jsonRequestUtility)
    {
        $this->jsonRequestUtility = $jsonRequestUtility;
    }
    
    public function searchAction(): ResponseInterface
    {
        // initialize the request utility
        $this->jsonRequestUtility->initialize();
        
        // get JSON POST data and store it in an array
        $postData = $this->jsonRequestUtility->parseJsonBody()->getDecodedData();
        
        // ... implement your handling of data
    }
}

$postData = $this->jsonRequestUtility->parseJsonBody()->getDecodedData();

JSON 响应

可以使用 JsonResponseUtility 构建响应。您可以在该对象中添加响应数据(以数组格式)、跟踪错误和成功状态。

use Faktore\FeJsonApiUtilities\Utility\JsonResponseUtility;

class EventsJsonApiController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
    protected JsonResponseUtility $jsonResponseUtility;
    
    // constructor with dependency injection
    public function __construct(JsonResponseUtility $jsonResponseUtility)
    {
        $this->jsonResponseUtility = $jsonResponseUtility;
    }
    
    public function searchAction(): ResponseInterface
    {
        // ... implement your handling of data
        
        // for example get events for a calendar using a repository
        // $events = $this->eventRepository->findByDemand($filterDemand);
        
        // convert your result to array first.
        // Implementing the convertToArray method will be your responsibility.
        // The ConvertUtilities provide a lot of useful functions to help with that.
        $events = $this->convertToArray($events);

        if ($events) {
            // assign data to the response
            $this->jsonResponseUtility->assignData('events', $output);
            // keep track of success status for the response
            $this->jsonResponseUtility->setSuccess(true);
        } else {
            // add an error
            $this->jsonResponseUtility->addError('no events found');
            // keep track of success status for the response
            $this->jsonResponseUtility->setSuccess(false);
        }
        
        // ... do more checks and validations to add errors if necessary.
        
        // Lastly, make sure to return a PSR-compliant response. The JsonResponse works just fine in Controller context.
        return $this->jsonResponse(
            $this->jsonResponseUtility->getOutput()
        )->withStatus(200);
    }
}

对象与属性转换工具

这里有一个 ConvertUtility 类,可以为您做很多魔法。

扁平化 FAL 对象或 FAL 存储库

使用 ConvertUtility::flattenFileStorage($imageFileStorage, $properties, $useAbsoluteUrl)

请注意,除了提供的属性外,存储库中的每个文件都会始终产生键 'publicUrl'

1.4.0 新特性:为 flattenFileStorage 添加了第三个可选参数。如果为真,则 'publicUrl' 将被转换为绝对路径。

use Faktore\FeJsonApiUtilities\Utility\ConvertUtility;

// ...

$result = [
    'title' => $event->getTitle() ?? '',
    // get FAL storages flattened
    'images' => ConvertUtility::flattenFileStorage(
            $event->getImages(),
            ['title', 'description', 'alternative'],
            true
        ) ?? '',
]; 

/* will return:
 * [
 *   'title' => 'foo'
 *   'images' => [
 *     0 => [
 *       'title' => bar,
 *       'publicUrl' => 'https://my.domain.com/puppies.jpg'
 *   ]
 * ]
 */

扁平化对象存储库

这将利用属性映射器来访问对象的可获取属性

use Faktore\FeJsonApiUtilities\Utility\ConvertUtility;

// ...

$result = ConvertUtility::flattenObjectStorage(
            $this->getCategories(),
            ['title', 'uid']
        );
        
/* $result will contain:
 * [
 *   0 => [
 *     'title' => 'foo',
 *     'uid' => 1234,
 *   ],
 *   1 => [
 *     'title' => 'bar',
 *     'uid' => 5678,
 *   ]
 * ]
 */

其他

还有一些其他工具方法可以将您的 extbase 模型转换为数组。请随意探索!

免责声明

这个实用库的功能非常有限,并不提供完整的 API。在实际的 TYPO3 应用中使用它仍需要对请求和响应的处理进行一些工作。

重要:自行承担风险。可能存在错误。请记住在自己的代码中处理安全问题。