vue-apollo share query definition between components

Viewed 392

I just started with vue-apollo and I wonder how to optimize some usage of apollo queries. I have some components which are using the exact same apollo query.

The query itself can be in a separate file as it is just a constant:

export const accountByPath = gql`
    query accountByPath($path: String!) {
        account: accountByPath(path: $path) {
            id
            name
        }
    }`
;

It can be used inside my component easily:

<script>
    export default {
        props: ['path'],
        apollo: {
            account: {
                query: accountByPath,
                variables() {
                        return {path: this.path}
                },
                subscribeToMore: {
                    document: updateAccountSubscription,
                    variables() {
                        return {
                            path: this.path,
                        }
                    },
                }
            }
        }
    }
</script>

I don't want to repeat this definition in each component which is using it. But how do I move the complete apollo definition? Naively I was first trying to extract the definition into a function, but this doesn't work:

<script>
   function getQuery(path) {
        return {
            query: accountByPath,
            variables() {
                return {path: path}
            },
            subscribeToMore: {
                document: updateAccountSubscription,
                variables() {
                    return {
                        path: path,
                    }
                },
            }
        }
    };

    export default {
        props: ['path'],
        apollo: {
            account: () => getQuery(this.path)
        }
    }

</script> 

So, how can I reuse the same query definition including variables and subscription?

1 Answers

Ah, I managed it minutes after asking the question.

<script>
   const getQuery = function accountQuery() {
        return {
            query: accountByPath,
            variables() {
                return {path: this.path}
            },
            subscribeToMore: {
                document: updateAccountSubscription,
                variables() {
                    return {
                        path: this.path,
                    }
                },
            }
        }
    };

    export default {
        props: ['path'],
        apollo: {
            account: getQuery
        }
    }

</script> 

The getQuery constant can be moved into a different file of course. So the insight for me was just to use "this" inside the constant function definition rather than using it as a parameter

Related