How to paste array of objects into GraphQL Apollo cache? - graphql

I have an array of countries received from Apollo backend without an ID field.
export const QUERY_GET_DELIVERY_COUNTRIES = gql`
query getDeliveryCountries {
deliveryCountries {
order
name
daysToDelivery
zoneId
iso
customsInfo
}
}
`
Schema of these objects:
{
customsInfo: null
daysToDelivery: 6
iso: "UA"
name: "Ukraine"
order: 70
zoneId: 8
__typename: "DeliveryCountry"
}
In nested components I read these objects from client.readQuery.
What I want is to insert it to localStorage, read it initially and write this data to Apollo Client Cache.
What I've already tried to do:
useEffect(() => {
const deliveryCountries = JSON.parse(localStorage.getItem('deliveryCountries') || '[]')
if(!deliveryCountries || !deliveryCountries.length) {
getCountriesLazy()
} else {
deliveryCountries.map((c: DeliveryCountry) => {
client.writeQuery({
query: QUERY_GET_DELIVERY_COUNTRIES,
data: {
deliveryCountries: {
__typename: "DeliveryCountry",
order: c.order,
name: c.name,
daysToDelivery: c.daysToDelivery,
zoneId: c.zoneId,
iso: c.iso,
customsInfo: c.customsInfo
}
}
})
})
}
}, [])
But after execution the code above I have only one object in countries cache. How to write all objects without having an explicit ID, how can I do it? Or maybe I'm doing something wrong?

Lol. I just had to put the array into necessary field without iterating. writeQuery replaces all the data and not add any "to the end".
client.writeQuery({
query: QUERY_GET_DELIVERY_COUNTRIES,
data: {
deliveryCountries: deliveryCountries
}
})

Related

Apollo Client 3: how to cache a mutation result into a nested collection? (collection within a collection)

In my Apollo Client 3 app, I am doing a mutation and want to cache the result into a collection which is nested within an item of a collection.
Specifically, I am creating a comment within a list of comments, each list within a post, each post within a list of posts. My app's data hierarchy looks like:
user 1
profile 1
post 1
comment 1.1
comment 1.2
post 2
comment 2.1
comment 2.2
< write mutation result here >
post 3
comment 3.1
comment 3.2
comment 3.3
...
In this situation, how would I best cache a created comment into its parent post's comment-collection? I am looking at the useMutation hook's update or modify config, but am not too sure.
For additional context, here is query that corresponds to the above data hierarchy:
query getUserPosts($userParams: GetUserParams!$postsPaginationParams: CursorPaginationParams!) {
user(params: $userParams) {
id
profile {
id
# ...
ownedPosts(pagination: $postsPaginationParams) {
items {
id
# ...
featuredComments {
id
primaryText
creationTimestamp
owner {
id
name
}
}
}
pagination {
# ...
}
}
}
}
}
And here is my mutation:
input CreateCommentParams {
ownerId: String!
postId: String!
primaryText: String!
}
mutation createComment($params: CreateCommentParams!) {
createComment(params: $params) {
id
owner {
id
name
}
primaryText
creationTimestamp
}
}
And here is what the useMutation is so far:
useMutation(CREATE_COMMENT_MUTATION, {
// ...
update: (cache, { data }) => {
if (data) {
const cacheId = cache.identify(data.createComment);
cache.modify({
fields: {
// ...how to update the comments array of the specific post?
}
})
}
},
})
You need to find the Post you are updating and update its featuredComments field like so:
useMutation(CREATE_COMMENT_MUTATION, {
// ...
update: (cache, { data }) => {
cache.modify({
id: cache.identify({
__typename: 'Post', // Assuming your this is the _typename of your Post type in your schema
id: postId,
}),
fields: {
featuredComments: (previous, { toReference }) => [...previous, toReference(data.createComment)]
},
}),
}),
})

graphql-codegen + typescript-svelte-apollo - Refetch not working?

(Edited)
Refetching with the generated query type seems to work different from the refetch function in Apollo Client useQuery. I don't understand how to phrase it - can anyone provide an example?
I'm realizing the problem is probably either my refetch is not properly phrased, or maybe the store is only hitting the cached query. I've been going over my code for days and I can't figure out what it could be. I've tried await blocks too.
The refetch worked with svelte-apollo, but i'm trying to eliminate that dependency. I've also tried Apollo Client's useQuery, but the whole point of graphql-codegen with typescript-svelte-apollo is to use the generated typescript wrapper for the query.
When I assign the generated query to a reactive constant in my Svelte front-end code,
$: observations = getObservations({ variables: { filter } });
the query does not refetch when i update the query variables, as I would expect.
This is how my svelte template is using the query. The filter object changes based on a form user input. I've tried this with an await block too.
<script lang="ts">
import { getObservations } from '$lib/generated';
$: observations = getObservations({ variables: { filter } });
function handleFilter(event) {
filter = event.detail;
}
</script>
{#if $observations.loading}
Loading...
{:else if $observations.error}
{$observations.error}
{:else if $observations.data}
{#each $observations.data['observations']['edges'] as edge}
<Item node={edge['node']} />
{/each}
{/if}
Since this plugin allows to use the query directly, without Apollo's useQuery, i'm not sure how to phrase a refetch.
If i do $observations.refetch(); inside handleFilter(e), i get an error
Property 'refetch' does not exist on type 'Readable<ApolloQueryResult<GetObservationsQuery> & { query: ObservableQuery<GetObservationsQuery, Exact<{ filter?: FilterObservationsInput; }>>; }>'.ts(2339)
There's nothing fancy in my config. Am I doing something wrong here?
schema: src/graphql/schema.graphql
documents:
- src/graphql/queries.graphql
- src/graphql/mutations.graphql
generates:
src/lib/generated.ts:
plugins:
- typescript
- typescript-operations
- graphql-codegen-svelte-apollo
config:
clientPath: src/lib/shared/client
# asyncQuery: true
scalars:
ISO8601Date: Date
ISO8601DateTime: Date
Here's the client:
export default new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
observations: relayStylePagination(),
},
},
},
})
});
The generated query:
export const getObservations = (
options: Omit<
WatchQueryOptions<GetObservationsQueryVariables>,
"query"
>
): Readable<
ApolloQueryResult<GetObservationsQuery> & {
query: ObservableQuery<
GetObservationsQuery,
GetObservationsQueryVariables
>;
}
> => {
const q = client.watchQuery({
query: GetObservationsDoc,
...options,
});
var result = readable<
ApolloQueryResult<GetObservationsQuery> & {
query: ObservableQuery<
GetObservationsQuery,
GetObservationsQueryVariables
>;
}
>(
{ data: {} as any, loading: true, error: undefined, networkStatus: 1, query: q },
(set) => {
q.subscribe((v: any) => {
set({ ...v, query: q });
});
}
);
return result;
}
Here's the query document that it's built from:
query getObservations($filter: FilterObservationsInput) {
observations(filter: $filter) {
pageInfo {
startCursor
endCursor
hasNextPage
hasPreviousPage
}
edges {
cursor
node {
id
createdAt
updatedAt
when
where
imgSrcThumb
imgSrcSm
imgSrcMed
thumbImage {
width
height
}
name {
formatName
author
}
user {
name
login
}
rssLog {
detail
}
}
}
}
}

joining schemas from remote server by batching same types

I am new to apollo server and I am trying really hard to understand how to make remote schemas one huge scheme, I was able to join the schemas and can now query the data, however, I cannot seem to be able to link/resolve the type, my two micro services uses the same type name for those type that are same everywhere with the pk being common in all of them only that one has only the pk and another one has some extra fields,
my shop schema looks like this
type UserType implements Node {
id: ID!
shops: [ShopType]
pk: Int
}
and what really matters is the pk in this case because it is suppose to join with my auth schema which looks like this
type UserType implements Node {
id: ID!
username: String
email: String
pk: Int
}
with so many other fields, I would like to be able to join the data fields of the two in appolo server since that is where I am merging my two schemas so that when ever I query
{
shops {
shopOwner {
username
email
}
}
}
then even though the username and email are not in the first schema, then it can resolve those fields by pk from the auth schema
I have used something like this
const createNewSchema = async () => {
const schemas = await createRemoteExecutableSchemas();
return mergeSchemas({
schemas,
});
};
to join my schemas so how do I even make the two work together as I desire? thanks so much in advance
I was able to make it work, I used stitchschemas and it looked like this
const createNewSchema = async () => {
const schemas = await createRemoteExecutableSchemas();
return stitchSchemas({
subschemas: [
{
schema: schemas['shop'],
merge: {
UserType: {
entryPoints: [
{
fieldName: 'shopOwnerById',
selectionSet: '{ pk }',
args: originalObject => ({ pk: originalObject.pk }),
},
{
fieldName: 'shopById',
selectionSet: '{ pk }',
args: originalObject => ({ pk: originalObject.pk }),
}
]
},
},
}, {
schema: schemas['auth'],
merge: {
UserType: {
entryPoints: [
{
fieldName: 'userById',
selectionSet: '{ pk }',
args: originalObject => ({ pk: originalObject.pk }),
},
]
}
}
}
],
mergeTypes: true,
});
};
in my case just not to confuse anyone I made the schemas to be dictionary where each was names by the API it was linking to. also hade to make sure that I made queries for all the fieldName's in my respective enpoints. thanks for taking a looks the guid here https://www.graphql-tools.com/docs/stitch-type-merging helped alot

Store error: the application attempted to write an object with no provided typename but the store already contains an object

After mutation when I am updating the cache, changes are reflected in UI but getting the below error
Invariant Violation: Store error: the application attempted to write an object with no provided typename but the store already contains an object with typename of ItemCodeConnection for the object of id $ROOT_QUERY.itemCodes({"filter":{"number":10000001}}). The selectionSet that was trying to be written is:
{"kind":"Field","name":{"kind":"Name","value":"itemCodes"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"Variable","name":{"kind":"Name","value":"filter"}}}],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"itemCodes"},"arguments":[],"directives":[],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"itemCodeTile"},"directives":[]},{"kind":"Field","name":{"kind":"Name","value":"__typename"}}]}},{"kind":"Field","name":{"kind":"Name","value":"__typename"}}]}}
GraphQL query:
const CREATE_ITEM_CODE_SPEC = gql`
mutation createItemCodeSpec($input: createItemCodeSpecInput) {
createItemCodeSpecification(input: $input){
__typename
id
itemCode {
number
}
product
spec_class
grade
}
}
`
const GET_ITEM_CODE = gql`
query itemCode($filter: filterInput){
itemCodes(filter: $filter){
itemCodes {
number
type
description
group
item_code_spec {
id
itemCode {
number
}
product
spec_class
grade
}
created_on
created_by
changed_on
changed_by
}
}
}
`
Below is the mutation:
const [mutation, { data, loading, error}] = useMutation(
CREATE_ITEM_CODE_SPEC,
{
update(cache, { data: { createItemCodeSpecification } }){
const currentData = cache.readQuery({
query: GET_ITEM_CODE,
variables: { filter : {number:itemCode} }
})
cache.writeQuery({
query: GET_ITEM_CODE,
variables: { filter : {number:itemCode} },
data: {
...currentData,
itemCodes: {
itemCodes: currentData.itemCodes.itemCodes.map((itemCode, index) => {
return {
...itemCode,
item_code_spec: index === 0? [
...itemCode.item_code_spec,
createItemCodeSpecification
] : itemCode.item_code_spec
}
})
}
}
})
}
}
);
You simply need to add "id" for each subsection of your query. Adding "id" for "itemCodes" in your GET_ITEM_CODE query might solve your problem.
You have fields missing in your response mutation.
Basically, you should make your mutation results have all of the data necessary to update the queries previously fetched.
That’s also why is a best practice to use fragments to share fields among all queries and mutations that are related.
To make it work both query and mutation should have exactly the same fields.
Have a look here to see more in depth how cache updates work:
https://medium.com/free-code-camp/how-to-update-the-apollo-clients-cache-after-a-mutation-79a0df79b840

How to update apollo cache after mutation (query with filter)

I am pretty new to GraphQL. I am using graph.cool in a Vue.js project with apollo.
I am using right now the in-memory cache.
I had previously a simple 'allPosts' query.
And after creating a new one, I used the update() hook and readQuery() + writeQuery()
However I want that logged in users can only see their posts. So I modified the query with a filter.
query userStreams ($ownerId: ID!) {
allStreams(filter: {
owner: {
id: $ownerId
}
}) {
id
name
url
progress
duration
watched
owner {
id
}
}
}
My thought was, that I only need to pass in the userid variable. However this is not working. I am always getting
Error: Can't find field allStreams({"filter":{"owner":{}}}) on object (ROOT_QUERY) undefined.
this.$apollo.mutate({
mutation: CREATE_STREAM,
variables: {
name,
url,
ownerId
},
update: (store, { data: { createStream } }) => {
const data = store.readQuery({
query: USERSTREAMS,
variables: {
id: ownerId
}
})
data.allStreams.push(createStream)
store.writeQuery({
query: USER_STREAMS,
variables: {
id: ownerId
},
data
})
}
})
When you use readQuery or writeQuery, you should use the same variable name. So replace
variables: { id: ownerId }
With
variables: { ownerId }
Also, the reason you are getting an exception is that readQuery throws an exception if the data is not in the store. That happens before the first time you use writeQuery (or get the data with some other query).
You could write some default values to the store before calling this mutation.
You could also use readFragment that returns null instead of throwing an exception. But that would require more changes to your code.

Resources