attus/jsonapi_response

基于自定义数据的JSON:API响应

安装: 200

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

类型:drupal-module

2.4.0 2024-06-21 08:37 UTC

This package is auto-updated.

Last update: 2024-09-21 09:12:06 UTC


README

这是一个用于自定义JSON:API实体响应的Drupal 10模块。

Maintenance GitHub license GitHub release GitHub issues

用法

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\jsonapi_response\JsonapiEntityResponseInterface;

class MyController extends ControllerBase {

  private     $_jsonapiResponseEntity;

  public function __construct(JsonapiEntityResponseInterface $jsonapiResponseEntity) {
    $this->_jsonapiResponseEntity = $jsonapiResponseEntity;
  }
  
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('jsonapi_response.entity'),
    );
  }

  /**
   * A single entity in JSON:API Format
   */
  public function getMyEntity(): CacheableResponseInterface
  {
    $entity = $this->getEntityForResponse();
    $response = $this->_jsonapiResponseEntity->entityIndividualResponse($entity);
    $cache = new CacheableMetadata();
    $cache->setCacheMaxAge(0);
    $response->addCacheableDependency($cache);
    return $response;
  }

  /**
   * An entity collection in JSON:API Format
   */
  public function getMyEntityCollection(): CacheableResponseInterface
  {
    $entities = $this->getEntitiesForResponse();
    return $this->_jsonapiResponseEntity->entityCollectionResponse($entities);
  }
 
  /**
   * An entity collection in JSON:API Format with includes
   */
  public function getMyEntityCollectionWithIncludes(): CacheableResponseInterface
  {
    $entities = $this->getEntitiesForResponse();
    return $this->_jsonapiResponseEntity->entityCollectionResponse($entities, [$fieldName1, $fieldName2]);
  }

}

您可以自由使用此模块,没有任何限制,但没有任何保证。