I need to send to a backend some additional variables, which are common to all queries and not directly related to the queries' schema. I've decided to use the context.extensions object to achieve this.
const { data } = await client.query({
query: GET_BY_ID_QUERY,
variables: { id: 111 },
context: {
extensions: {
credentials: {
securityHash: "a1b2c3d4",
},
},
},
});
The problem is, when I specify my variables, the extensions object is ignored. I can only send it if I create a custom Apollo link, which sets the object to operation (comment 4).
Why is this work like this? Is there any explanation how to use the extensions object right? So far, I couldn't find any useful information.
const extensionLink = new ApolloLink((operation: Operation, forward) => {
// 1. This context has the query's context extensions object with variables
const ctx1 = operation.getContext();
operation.setContext((oldCtx: any) => {
// 2. The oldCtx also has the query's context extensions object with variables
return {
...oldCtx,
extensions: {
...oldCtx.extensions,
["random-value-1"]: Math.random(),
},
};
});
// 3. After the setContext execution the operation still doesn't contain the extensions object with variables
// 4. Only when I assign extensions object, the Graphql send its variables to the backend
operation.extensions = ctx1.extensions;
operation.extensions["random-value-2"] = Math.random();
return forward(operation);
});
Here is the demo repository: https://github.com/ivan-banha/apollo-graphql-extensions