1 | initial version |
To reuse types generated by graphql-codegen, typescript-operations, and typescript-vue-urql as fragments in Vue, you can follow these steps:
fragment
keyword:fragment UserFragment on User {
name
email
...
}
fragment-matcher
plugin:$ npx graphql-codegen --config codegen.yml
schema: http://localhost:3000/api/graphql
documents: path/to/*.graphql
plugins:
- typescript
- typescript-operations
- typescript-vue-urql
- fragment-matcher:
typePrefix: "FragmentTypes."
src: path/to/fragment-types.ts
import { UserFragmentFragment } from '@/path/to/fragment-types.ts';
<template>
<div>
<ul>
<li v-for="user in users" :key="user.id">
{{ user.name }} - {{ user.email }}
</li>
</ul>
</div>
</template>
<script lang="ts">
import { useQuery, gql } from '@vue/apollo-composable';
import { UserFragmentFragment } from '@/path/to/fragment-types.ts';
const USERS_QUERY = gql`
query {
users {
...UserFragment # <-- using the UserFragment as a fragment
}
}
${UserFragmentFragment}
`;
export default {
setup() {
const { result } = useQuery(USERS_QUERY);
return {
users: result.value?.data?.users || [],
};
},
};
</script>
<template>
<div>
<button @click="updateUser(user.id)">Update User</button>
</div>
</template>
<script lang="ts">
import { useMutation, gql } from '@vue/apollo-composable';
import { UserFragmentFragment } from '@/path/to/fragment-types.ts';
const UPDATE_USER_MUTATION = gql`
mutation($id: ID!, $data: UserInput!) {
updateUser(id: $id, data: $data) {
...UserFragment # <-- using the UserFragment as a fragment
}
}
${UserFragmentFragment}
`;
export default {
props: {
user: {
type: Object,
required: true,
},
},
setup(props) {
const { mutate } = useMutation(UPDATE_USER_MUTATION);
const updateUser = async (id: string) => {
const data = { /* ... */ };
await mutate({ id, data });
};
return {
updateUser,
};
},
};
</script>