【问题标题】:api platform with graphQL support支持 graphQL 的 api 平台
【发布时间】:2022-01-13 20:45:01
【问题描述】:

刚刚开始使用启用了 graphQl 支持的 api 平台。如果我对 graphQl 的理解正确,我不需要像使用 REST 那样创建路由,端点是从模型模式在前端创建的。

但是如果我有一个包含一些逻辑的方法并且我需要运行该代码怎么办?如果我没有路线,我将无法执行。我还能做什么?

提前感谢您的回答。 Br

【问题讨论】:

  • 根据thisthis 基本上是因为它们将其限制为对单数和集合的基本CRUD 操作。我认为唯一的答案是为这些创建一个 REST 端点。

标签: php api symfony api-platform.com


【解决方案1】:

您可以通过使用 custom queries 获取数据或使用 custom mutations 以 REST 术语发布/放置/删除数据来解决这个问题。

你的问题暗示你想要一个自定义突变,根据文档,这将像这样工作:

创建您的解析器:

<?php

namespace App\Resolver;

use ApiPlatform\Core\GraphQl\Resolver\MutationResolverInterface;
use App\Model\Book;

final class BookMutationResolver implements MutationResolverInterface
{
    /**
     * @param Book|null $item
     *
     * @return Book
     */
    public function __invoke($item, array $context)
    {
        // Mutation input arguments are in $context['args']['input'].

        // Do something with the book.
        // Or fetch the book if it has not been retrieved.

        // The returned item will pe persisted.
        return $item;
    }
}

然后使用这个自定义突变如下:

<?php

namespace App\Model;

use ApiPlatform\Core\Annotation\ApiResource;
use App\Resolver\BookMutationResolver;

#[ApiResource(
    graphql: [
        // Auto-generated queries and mutations
        'item_query',
        'collection_query',
        'create',
        'update',
        'delete',

        'mutation' => [
            'mutation' => BookMutationResolver::class
        ],
        'withCustomArgsMutation' => [
            'mutation' => BookMutationResolver::class,
            'args' => [
                'sendMail' => ['type' => 'Boolean!', 'description'=> 'Send a mail?' ]
            ]
        ],
        'disabledStagesMutation' => [
            'mutation' => BookMutationResolver::class,
            'deserialize' => false,
            'write' => false
        ]
    ]
)]
class Book
{
    // ...
}

【讨论】:

    猜你喜欢
    • 2013-04-11
    • 2013-08-02
    • 2017-06-05
    • 2016-10-18
    • 2010-09-11
    • 2018-11-18
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多