通过 user_id 获取 Lighthouse GraphQL 数据所有权

我有一个允许多个用户的应用程序。每个用户之间完全隔离;这意味着数据库中所有非用户的内容都有一个user_id列,并且只有登录用户才可以查看、更新或删除它们。此外,用户不能使用其他人的 user_id 创建行。


有没有内置的方法可以用 Lumen/Lighthouse 来解决这个问题?这是我所做的,它有效,但我想知道我是否重新发明了轮子:


每个模型都有一个user关系,如下所示:

public function user(): BelongsTo

{

    return $this->belongsTo(User::class);

}

我在这些模型中添加了一个HasOwnerTrait,其中包含以下内容:

public static function boot()

{

    parent::boot();


    static::creating(function (Model $model) {

        $model->user_id = Auth::user()->id;

    });


    static::saving(function (Model $model) {

        if ($model->user_id !== Auth::user()->id) {

            $exception = new ModelNotFoundException();

            $exception->setModel(self::class, $model->id);

            throw $exception;

        }

    });


    static::deleting(function (Model $model) {

        if ($model->user_id !== Auth::user()->id) {

            $exception = new ModelNotFoundException();

            $exception->setModel(self::class, $model->id);

            throw $exception;

        }

    });

}


public function scopeIsOwner($query)

{

    return $query->where('user_id', Auth::user()->id);

}

最后,在我的模式定义中:

type Query {

    recipes: [Recipe!]! @all(scopes: ["isOwner"])

}


type Mutation {

    createRecipe(input: CreateRecipeInput! @spread): Recipe @create

    updateRecipe(id: ID!, input: UpdateRecipeInput! @spread): Recipe @update

    deleteRecipe(id: ID!): Recipe @delete

}

同样,这是可行的,但是是否需要像这样临时使用,或者是否有更好的方法?


猛跑小猪
浏览 68回答 1
1回答

拉风的咖菲猫

我认为你的解决方案很好,它节省了编写一大堆样板文件。一些小建议:boot您可以将方法重命名为 ,从而使您的特征成为可引导特征,由框架自动调用bootHasOwnerTrait。也许可以考虑isOwner默认将作用域设置为活动状态。在 Laravel 中,这被容易混淆地称为全局作用域。这允许您省略显式命名范围,但如果您有一些不应应用的查询(例如统计信息),您仍然可以省略它。
打开App,查看更多内容
随时随地看视频慕课网APP