【问题标题】:Pass logged user argument to @scope directivePass logged user argument to @scope directive
【发布时间】:2023-02-23 04:54:39
【问题描述】:

我需要通过将当前用户提供给 scopeAvailableForUser 来获取类型(以获取记录的用户的订单)。

所以我做了以下

extend type Query {
    wallet(
        user: User = me @scope(name: "availableToUser")
    ): [DigitalProduct!]  @all
}

但它不起作用,它正在返回

"errors": [
    {
        "message": "Unknown type: User.",
        "extensions": {
            "category": "graphql"
        }
    }
]

那么,我怎样才能为用户提供范围指令呢?

【问题讨论】:

  • 你有没有解决这个问题?你能分享你的吗,我们可以将其标记为已回答。

标签: laravel-lighthouse


【解决方案1】:

您可以使用 belongsTo 之类的关系并将其嵌套在 User 类型上,因为链接到用户的 DigitalProduct 应该与 belongsTo 和 hasMany 有关系,我认为。

extend type User {
  wallet: [DigitalProduct!]! @hasMany
}

如果编写一个 API,一个公共用户和一个为像我或 currentUser 这样的查询返回的私有用户是很好的。多个类型可以使用@model(class: "AppModelsUser") 指向同一个模型

所以我有一个在关系中使用的 PublicUser 类型,然后为了查看授权用户(登录用户)记录,我使用真实的用户类型。这让我可以保护它,以便 1 个用户无法看到另一个用户更“私人”的关系/数据。

还有 @inject 可用于从上下文中获取用户 ID。

将上下文对象中的值注入到参数中。 https://lighthouse-php.com/master/api-reference/directives.html#inject

你可能会像这样使用它。 注意:注入会覆盖任何用户提供的值。

extend type Query {
  wallet(user_id: Int! @whereKey) @all @inject(context: "user.id", name: "user_id")

但是,这不一定使用范围。

我想弄清楚如何从用户那里放置变量。

文档说

scope 方法将接收客户端给定的参数值作为第二个参数。 https://lighthouse-php.com/master/api-reference/directives.html#scope

因此,如果作用域有一个 user_id 参数,它可能会相应地与 inject 一起传递它?


在我的用例中,我想将用户定义的值传递给范围。 在这种情况下不是登录用户,因为我为此使用了关系。 但是当我搜索时出现了这个问题。

我正在使用 Spatie/Tags 包。

use IlluminateDatabaseEloquentBuilder;
use IlluminateDatabaseEloquentModel;

class Tag extends Model
{
// ...
    public function scopeWithType(Builder $query, string $type = null): Builder
    {
        if (is_null($type)) {
            return $query;
        }

        return $query->where('type', $type)->ordered();
    }

    public function scopeContaining(Builder $query, string $name, $locale = null): Builder
    {
        $locale = $locale ?? static::getLocale();

        return $query->whereRaw('lower(' . $this->getQuery()->getGrammar()->wrap('name->' . $locale) . ') like ?', ['%' . mb_strtolower($name) . '%']);
    }
// ...
}

所以像这样的模式是有效的。

# noinspection GraphQLUnresolvedReference,GraphQLMissingType
union HasTags = Restaurant | Dish | Grub

type Tag @model(class: "Spatie\Tags\Tag") {
    id: ID!
    name: String!
    slug: String!
    type: String!
    order_column: Int!
    created_at: DateTime!
    updated_at: DateTime!
}

extend type Query {
    "Find a Tag by id."
    tag(id: ID! @eq): Tag! @find

    "Find a tag containing a given name for a given type."
    tags(name: String! @scope(name: "containing"), type: String! @scope(name: "withType"), limit: Int = 10 @limit): [Tag!]! @all @orderBy(column: "order_column")
}

【讨论】:

    猜你喜欢
    • 2022-02-24
    • 2022-12-01
    • 2022-11-20
    • 2020-09-06
    • 2015-03-24
    • 2022-12-26
    • 1970-01-01
    • 2023-01-29
    • 2022-01-12
    相关资源
    最近更新 更多