Apollo client ignoring argument for GQL REST query - graphql

I have a query that is defined like this:
export const getProjectCosts = gql`
query GetProjectCosts($projectId: Int) {
ProjectCostList #rest(type: "ProjectCostList", path: "ProjectCosts/{args.projectId}") {
id
projectId
cost
description
costType
budgetYear
createdByUser
createdDate
}
}
`;
export const useGetProjectCostsListQuery = (baseOptions?: QueryHookOptions<ProjectCostList>) => {
const options = { ...baseOptions };
return useQuery<ProjectCostList>(getProjectCosts, options);
};
I call it like this:
const {
loading: projectCostLoading,
error: projectCostError,
data: projectCostData,
} = useGetProjectCostsListQuery({
variables: {
projectId: args.defaultValues.id,
},
});
I have verified in the debugger that the argument is sent correctly.
However, in the browser I see a warning:
Warning: RestLink caught an error while unpacking ProjectCosts/{args.projectId}|args.projectId This tends to happen if you forgot to pass a parameter needed for creating an #rest(path, or if RestLink was configured to deeply unpack a path parameter that wasn't provided. This message will only log once per detected instance. Trouble-shooting hint: check #rest(path: and the variables provided to this query.
(anonymous) # restLink.ts:567
And a request is sent to api/ProjectCosts/ instead of api/ProjectCosts/1234, which not surprisingly fails with a HTTP 404 error.
Is this a bug or am I doing something wrong?
I found this issue on Github, which looks very similar to what I'm experiencing.
We're using a custom .NET backend.
If it's a bug, is there a workaround?

The problem was that the parameter has to be declared twice.
This is the solution:
export const getProjectCosts = gql`
query GetProjectCosts($projectId: Int!) {
ProjectCostList(projectId: $projectId) #rest(type: "ProjectCostList", path: "ProjectCosts/{args.projectId}") {

Related

MSW do not intercept GraphQL requests

I've tried every possible solution described on the internet, but nothing seems to help.
I created a mock server and am trying to intercept a GraphQL call:
./setup/setup-server.ts
const handlers = [
graphql.query<GetOperation, GetOperationVariables>(
'GetOperation'
(req, res, ctx) => {
// Nothing showing in console
console.log(req.variables);
return res(
ctx.data({
operation: [] // mocked operation
})
);
}
),
]
./graphql/use-get-operation.ts
export const GET_OPERATION_BY_ID_DEFAULT = gql`
query GetOperation($idOrContractNumber: String!) {
operation(input: { idOrContractNumber: $idOrContractNumber }) {
id
modality
totaltaxes
exchangeRate
}
}
`;
The call is not intercepted.
I've already tried:
Import jest-fetch-mock in the configuration file;
Start the server in setupFiles.js (as exemplified in the documentation);
Start the server in the file directly in the test;
Use regex instead of string in the operation name;
Nothing seems to work.
I tried to create both queries and mutations and it didn't work.
MSW version used: 0.33.0

GraphQL Nexus Schema (nexusjs) doesn't compile with scalar types

I am trying to follow the documentation on the Nexus-Schema (nexusjs) website for adding scalar types to my GraphQL application.
I have tried adding many of the different implementations to my src/types/Types.ts file using the samples provided in the documentation and the interactive examples. My attempts include:
Without a 3rd party libraries:
const DateScalar = scalarType({
name: 'Date',
asNexusMethod: 'date',
description: 'Date custom scalar type',
parseValue(value) {
return new Date(value)
},
serialize(value) {
return value.getTime()
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return new Date(ast.value)
}
return null
},
})
With graphql-iso-date 3rd party library:
import { GraphQLDate } from 'graphql-iso-date'
export const DateTime = GraphQLDate
With graphql-scalars 3rd party library (as shown in the ghost example):
export const GQLDate = decorateType(GraphQLDate, {
rootTyping: 'Date',
asNexusMethod: 'date',
})
I am using this new scalar type in an object definition like the following:
const SomeObject = objectType({
name: 'SomeObject',
definition(t) {
t.date('createdAt') // t.date() is supposed to be available because of `asNexusMethod`
},
})
In all cases, these types are exported from the types file and imported into the makeSchema's types property.
import * as types from './types/Types'
console.log("Found types", types)
export const apollo = new ApolloServer({
schema: makeSchema({
types,
...
context:()=>(
...
})
})
The console.log statement above does show that consts declared in the types file are in scope:
Found types {
GQLDate: Date,
...
}
If I run the app in development mode, everything boots up and runs fine.
ts-node-dev --transpile-only ./src/app.ts
However, I encounter errors whenever I try to compile the app to deploy to a server
ts-node ./src/app.ts && tsc
Note: This error occurs occurs running just ts-node ./src/app.ts before it gets to tsc
The errors that shown during the build process are the following:
/Users/user/checkouts/project/node_modules/ts-node/src/index.ts:500
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: тип Unable to compile TypeScript:
src/types/SomeObject.ts:11:7 - error TS2339: Property 'date' does not exist on type 'ObjectDefinitionBlock<"SomeObject">'.
11 t.date('createdAt')
Does anyone have any ideas on either:
a) How can I work around this error? While long-term solutions are ideal, temporary solutions would also be appreciated.
b) Any steps I could follow to debug this error? Or ideas on how get additional information to assist with debugging?
Any assistance would be very much welcomed. Thanks!
The issue seems to be resolved when --transpile-only flag is added to the nexus:reflect command.
This means the reflection command gets updated to:
ts-node --transpile-only ./src/app.ts
and the build comand gets updated to:
env-cmd -f ./config/.env ts-node --transpile-only ./src/app.ts --nexusTypegen && tsc
A github issue has also been created which can be reviewed here: https://github.com/graphql-nexus/schema/issues/690

Says Jasmine spy is not being called, but I can see that its being called

I can't figure out why Jasmine is claiming that the function I'm spying on isn't being called, especially since it is logging in buildLinksObj when called through and not calling when I remove .and.callThrough() I feel like I've written similar code a bunch of times before without any problem. I'm using Jasmine 2.9
The error message I'm getting is:
1) addToLinks should call buildLinksObj if its given an object with children
it should add the personalized links to PageApp.meta.analytics.links
Expected spy buildLinksObj to have been called.
at UserContext.<anonymous> (http://localhost:9877webpack:///tests/specs/common/FetchPersonalContent.spec.js:854:0 <- tests/app-mcom.js:104553:48)
Here's the except of my code:
FetchPersonalContent.js
const buildLinksObj = (responseObj = {}, targetObj, PageApp) => {
console.log('it logs in buildLinksObj') // This is logging!
}
const addToLinks = (responseArr, personalizedLinks) => {
responseArr.forEach((media) => {
const type = media.type;
const typeObj = media[type];
buildLinksObj(typeObj, personalizedLinks, PageApp);
if (typeObj && typeObj.children) {
console.log('has children!')
console.log('typeObj.children is: ', typeObj.children);
typeObj.children.forEach((child) => {
console.log('has a child')
buildLinksObj(child, personalizedLinks, PageApp);
console.log('buildLinksObj was definitely called. what the heck?')
});
}
});
}
export {buildLinksObj, addToLinks, FetchPersonalContent as default,
};
FetchPersonalContent.spec.js
import * as FetchPersonalContent from '../../../src/FetchPersonalContent'; // my path is definitely correct
describe('it should add the personalized links to PageApp.meta.analytics.links', () => {
it('addToLinks should call buildLinksObj if its given an object with children ', () => {
spyOn(FetchPersonalContent, 'buildLinksObj').and.callThrough();
FetchPersonalContent.addToLinks([{
"personalId": 30718,
"type": "carousel",
"carousel": {}
}], {});
expect(FetchPersonalContent.buildLinksObj).toHaveBeenCalled();
});
});
I'd really appreciate any help!
I have a feeling FetchPersonalContent.buildLinksObj in the spec file is not pointing to the same instance as buildLinksObj in the FetchPersonalContent.js file.
Why is export {FetchPersonalContent as default} required? I am assuming you have shared the complete content of FetchPersonalContent.js in your question.
Possible solutions:
You can try removing FetchPersonalContent from the export statement.
Or
Instead of
export {buildLinksObj, addToLinks, FetchPersonalContent as default,
};
You can directly export the constants in FetchPersonalContent.js file.

How to unit test graphql query/mutation error with Mocha and Chai?

Since graphql error is not an standard Error. It's a GraphQLError
I can't figure out how to write unit test when graphql query/mutation throw an exception.
Here is my try:
it('should throw an error when lack of "id" argument for user query', async () => {
const body = {
query: `
query user{
user {
id
name
}
}
`
};
try {
const actualValue = await rp(body);
} catch (err) {
logger.error(err);
}
// logger.info(actualValue);
expect(1).to.be.equal(1);
// expect(actualValue).to.throw()
});
I found some tests in graphql.js repo. https://github.com/graphql/graphql-js/blob/master/src/tests/starWarsQuery-test.js#L393
But I think the way they test the query/mutation error is not correct.
They just do a deep equal with the error. But before running the test suites, how do I know the error data structure like locations: [{ line: 5, column: 13 }],? Maybe I should use snapshot testing so that I don't need to know the error data structure?
Check this package https://github.com/EasyGraphQL/easygraphql-tester there is an example with mocha and chai on the documentation

Why is my graphql Higher Order Component fire the options 11 times with the Apollo Client?

I'm using apollo client in an exponent react native app and have noticed that the graphql options method gets run 11 times, why is that? Is that an error or a performance problem? Is that normal? Is it running the query 11 times as well?
...
#graphql(getEventGql,{
options: ({route}) => {
console.log('why does this log 11 times', route.params);
return {
variables: {
eventId: route.params.eventId,
}
}
},
})
#graphql(joinEventGql)
#connect((state) => ({ user: state.user }))
export default class EventDetailScreen extends Component {
...
Looking at the sample from the documentation http://dev.apollodata.com/react/queries.html
Typically, variables to the query will be configured by the props of
the wrapper component; where ever the component is used in your
application, the caller would pass arguments. So options can be a
function that takes the props of the outer component (ownProps by
convention):
// The caller could do something like:
<ProfileWithData avatarSize={300} />
// And our HOC could look like:
const ProfileWithData = graphql(CurrentUserForLayout, {
options: ({ avatarSize }) => ({ variables: { avatarSize } }),
})(Profile);
By default, graphql will attempt to pick up any missing variables from
the query from ownProps. So in our example above, we could have used
the simpler ProfileWithData = graphql(CurrentUserForLayout)(Profile);.
However, if you need to change the name of a variable, or compute the
value (or just want to be more explicit about things), the options
function is the place to do it.

Resources