lighthouse icon indicating copy to clipboard operation
lighthouse copied to clipboard

Add wildcard path for `@inject` directive

Open ghost opened this issue 5 years ago • 1 comments

Considering this example schema

type User {
    id: ID!
    name: String!
    comments: [Comment!]! @hasMany
}

type Post {
    id: ID!
    title: String!
    body: String!
    user: User! @belongsTo
}

type Comment {
    id: ID!
    title: String!
    body: String!
    user: User! @belongsTo
}

input UpdateUserInput {
    comments: UpdateCommentsHasMany
}

input UpdateCommentsHasMany {
    create: [CreateCommentInput!]
}

input CreateCommentInput {
    post_id: ID!
    title: String!
    body: String!
}

type Mutation @guard {
    updateUser(input: UpdateUserInput!): User 
        @update
        @inject(context: "user.id", name: "comments.create.*.user_id")
}

It would be awesome if Lighthouse could inject data in the argument set using wildcard in the dot notation, this would cover the nested mutations in the HasMany case, while ensuring that a comment will be created for the authenticated user or a mutation that uses a list of input types.

Of course, today, I can create something like:

input CreateCommentInput {
    post_id: ID!
    title: String!
    body: String!
}

type Mutation @guard {
    createComment(input: CreateCommentInput!): Comment!
        @create
        @inject(context: "user.id", name: "customer_id")
}

But, well, this way I'm not using the power of nested mutations.

Maybe I'm wrong, but I think the change needed is just use data_fill instead of Illuminate\Support\Arr::add in the Nuwave\Lighthouse\Schema\Directives\InjectDirective class and rewrite the addValue method of Nuwave\Lighthouse\Execution\Arguments\ArgumentSet class to behave like data_fill as actually it is behaving like Illuminate\Support\Arr::add

Or maybe create a new directive and method.

I'm willing to help with a PR when as soon as I have time available.

Lighthouse Version: 4.9 Laravel Version: 6.12.0

ghost avatar Feb 20 '20 13:02 ghost

Thank you for your contribution. You have a totally valid use case.

Powering up @inject in the way you described seems reasonable, i would be willing to incorporate a PR for this.

Another approach to solving that issue would be to default comments/posts to hold the ID of the currently authenticated user when creating them. We are using model events for that. Helps a great deal when most of the models in your application belong to the current user.

spawnia avatar Mar 15 '20 19:03 spawnia