webstack/api-platform-global-search-bundle

用于添加 uuid 过滤器或对 Doctrine ORM 进行搜索和全局搜索支持的 Bundle

v3.1.2 2023-03-07 09:28 UTC

This package is auto-updated.

Last update: 2024-08-29 05:23:41 UTC


README

TODO: API Platform 是什么?我们如何扩展它?

安装

composer require webstack/api-platform-extensions-bundle:[version]

配置

安装插件后,您需要将一些配置文件添加到您的项目中

  • config/packages/webstack_api_platform_extensions.yaml
webstack_api_platform_extensions:
  identifier_class: App\Entity\%UserEntity%
  • config/routes/api_platform.yaml
app_extra:
  resource: '@WebstackApiPlatformExtensionsBundle/Resources/config/routing/routing.xml'
  prefix: /api

过滤器

此 Bundle 添加了以下过滤器

GlobalSearchFilter (api_platform.doctrine.orm.global_search_filter)

递归地搜索指定列(或全部列,有些吓人)的实体,该实体的端点已激活。

将过滤器配置为服务(config/services/api_platform/search/[$domain/]$entity.yaml

services:
  api.resource.region.global.search_filter:
    parent: 'api_platform.doctrine.orm.global_search_filter'
    arguments: [ {
      'name': 'partial',
      'depot.description': 'partial',
    } ]
    tags: [ { name: 'api_platform.filter', id: 'api.region.global_search_filter' } ]
    autowire: false
    autoconfigure: false

并将其应用到适当的资源上

App\Entity\Transport\Region:
  attributes:
    route_prefix: /transport
    filters:
      - 'api.region.global_search_filter'

现在当用户通过 ?_global_search=foo 调用 API 时,查询将类似于以下内容

SELECT 
    r.*
FROM 
    region r
LEFT JOIN
    depot d
ON
    d.id = r.depot_id
WHERE
    r.name LIKE '%foo%' 
    OR d.description LIKE '%foo%'

AliasSearchFilter (api_platform.doctrine.orm.alias_search_filter)

与常规搜索过滤器类似,但允许您在 URL 中重命名或别名(嵌套)属性。将属性和别名作为单独的 DI 参数传递

services:
  api.some_entity.deeply_nested_prop_filter:
    parent: 'api_platform.doctrine.orm.alias_search_filter'
    arguments:
      $properties:
        deeply.nested.property: 'exact'
      $aliases:
        myProp: 'deeply.nested.property'
    tags: [ { name: 'api_platform.filter' } ]

并将其应用到适当的资源上

App\Entity\SomeEntity:
  attributes:
    route_prefix: /some
    filters:
      - 'api.some_entity.deeply_nested_prop_filter'

现在要使用默认的 SearchFilter 命中此过滤器,URL 将是

/some?deeply.nested.property=foo

此别名搜索过滤器添加了一个新的查询字符串参数,并将其映射到配置的别名

/some?myProp=foo

OrSearchFilter (api_platform.doctrine.orm.or_search_filter)

TODO

UuidFilter (api_platform.doctrine.orm.uuid_filter)

用于通过 UUID 查找嵌套实体,因为 API Platform 不支持此功能(见 api-platform/core#3774,已回滚,因为它破坏了日期搜索)。

服务配置

services:
  api.resource.transport_position.vehicle_filter:
    parent: 'api_platform.doctrine.orm.uuid_filter'
    arguments: [ {
      vehicle.id: 'exact'
    } ]
    tags: [ { name: 'api_platform.filter', id: 'api.transport_position.vehicle_filter' } ]
    autowire: false
    autoconfigure: false
    public: false

API Platform 实体配置

App\Entity\Transport\Position:
  collectionOperations:
    get:
      filters:
        - 'api.transport_position.vehicle_filter'

现在 API 调用者可以使用 GET .../transport_positions?vehicle.id=$uuid 进行筛选。

路由

此 Bundle 引入了以下路由

/me

获取调用者的信息。包括 SwaggerDecorator 以生成有关此端点的 OpenAPI 文档。