Can you request a literal value in graphql? - graphql

I'm trying to figure out how to mock requests when the client is ahead of the server. I'd like to be able to just request literals so that I can go back and change them later, is there a way to do something like this?
query myQuery {
type {
fieldName: 42
}
}

Yes, it is quite easy to set up mock responses if you have at least the server boilerplate code set up. If you are using Apollo, there are built in tools to facilitate mocks.
https://www.apollographql.com/docs/graphql-tools/mocking.html
From the docs:
The strongly-typed nature of a GraphQL API lends itself extremely well
to mocking. This is an important part of a GraphQL-First development
process, because it enables frontend developers to build out UI
components and features without having to wait for a backend
implementation.
Here is an example from the docs:
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { graphql } from 'graphql';
// Fill this in with the schema string
const schemaString = `...`;
// Make a GraphQL schema with no resolvers
const schema = makeExecutableSchema({ typeDefs: schemaString });
// Add mocks, modifies schema in place
addMockFunctionsToSchema({ schema });
const query = `
query tasksForUser {
user(id: 6) { id, name }
}
`;
graphql(schema, query).then((result) => console.log('Got result', result));
This mocking logic simply looks at your schema and makes sure to
return a string where your schema has a string, a number for a number,
etc. So you can already get the right shape of result. But if you want
to use the mocks to do sophisticated testing, you will likely want to
customize them to your particular data model.

Related

Apollo conditional data sources & initialization lifecycle

I have a specific use case where a user’s data sources are conditional - e.g based on the data sources saved in the database for every specific user.
This also means every data source has unique credentials for every user, which is fine for RESTDataSource because I can use the willSendRequest to set the Authentication headers before each request.
However, I have custom data sources that have proprietary clients (for example JSForce for Salesforce) - and they have their own fetch mechanism.
As of now - I have a custom transformer directive that fetches the tokens from the database and adds it into the context - however, the directive is ran before the dataSource.initialize() method - so that I can’t use the credentials there because the context still doesn’t have it.
I also don’t want to initialize all data sources for every user even if he doesn’t use said data source in this request - but the dataSources() function doesn’t accept any parameter and is not contextual.
Bottom line is - is it possible to pass data sources conditionally based even on the Express request? When is the right time to pass the tokens and credentials to the dataSource? Maybe add my own custom init function and call it from the directive?
So you have options. Here are 2 choices:
1. Just add your dataSources
If you just initialize all dataSources, internally it can check to see if the user has access. You could have a getClient function that resolves on the client or throws an UnauthorizedError, depending.
2. Don't just add your dataSources
So if you really don't want to initialize the dataSources at ALL, you can absolutely do this by adding the "dataSources" yourself, just like Apollo does it.
const server = new ApolloServer({
// this example uses apollo-server-express
context: async ({ req, res }) => {
const accessToken = req.headers?.authorization?.split(' ')[1] || ''
const user = accessToken && buildUser(accessToken)
const context = { user }
// You can't use the name "dataSources" in your config because ApolloServer will puke, so I called them "services"
await addServices(context)
return context
}
})
const addServices = async (context) => {
const { user } = context;
const services = {
userAPI: new UserAPI(),
postAPI: new PostAPI(),
}
if (user.isAdmin) {
services.adminAPI = new AdminAPI()
}
const initializers = [];
for (const service of Object.values(services)) {
if (service.initialize) {
initializers.push(
service.initialize({
context,
cache: null, // or add your own cache
})
);
}
}
await Promise.all(initializers);
/**
* this is where you have to deviate from Apollo.
* You can't use the name "dataSources" in your config because ApolloServer will puke
* with the error 'Please use the dataSources config option instead of putting dataSources on the context yourself.'
*/
context.services = services;
}
Some notes:
1. You can't call them "dataSources"
If you return a property called "dataSources" on your context object, Apollo will not like it very much [meaning it throws an Error]. In my example, I used the name "services", but you can do whatever you want... except "dataSources".
With the above code, in your resolvers, just reference context.services.whatever instead.
2. This is what Apollo does
This pattern is copied directly from what Apollo already does for dataSources [source]
3. I recommend you still treat them as DataSources
I recommend you stick to the DataSources pattern and that your "services" all extend DataSource. It's going to be easier for everyone involved.
4. Type safety
If you're using TypeScript or something, you're going to lose a bit of type safety, since the context.services is either going to be one shape or another. Even if you're not, if you're not careful, you may end up throwing "Cannot read property users of undefined" errors instead of "Unauthorized" errors. You might be better off creating "dummy services" that reflect the same object shape but just throw Unauthorized.

Use RTK Query with Graphql

So far I understand I need to build my own baseQuery. I could write graphql queries and mutations like in example here https://rtk-query-docs.netlify.app/examples/react-with-graphql, will I get full type safety for queries and mutations if I add types to query.builder like this builder.query<Device, void> or I must use something like this https://www.graphql-code-generator.com/docs/plugins/typescript-graphql-request#simple-request-middleware. In latter case how should my baseQuery look if I use generated hook for graphql-request library.
Here is example of hook from 2:
import { GraphQLClient } from 'graphql-request';
import { getSdk } from './sdk'; // THIS FILE IS THE GENERATED FILE
async function main() {
const client = new GraphQLClient('https://countries.trevorblades.com/');
const sdk = getSdk(client);
const { continents } = await sdk.continents(); // This is fully typed, based on the query
console.log(`GraphQL data:`, continents);
}
I am thinking something like:
import {getSdk} from './sdk'
const client = new GraphQLClient('https://countries.trevorblades.com/');
const graphqlBaseQuery = (someGeneratedQueryOrMutation, client) => {
const something = someGeneratedQueryOrMutation(client);
const { continents } = await something.continents();
return { data: continents };
};
Code does not really make sence but I hope you see where I am going with this. Thanks :)
Edit: By now there is a Grahql Codegen plugin available at https://www.graphql-code-generator.com/docs/plugins/typescript-rtk-query
Actually I started writing a plugin for the code generator a few days ago.
You can see the generated result here:
https://github.com/phryneas/graphql-code-generator/blob/5f9a2eefd81538782b791e0cc5df633935164a89/dev-test/githunt/types.rtk-query.ts#L406-L427
This would require you to create an api with a baseQuery using a graphql library of your choice like this.
A configuration would look like this
./dev-test/githunt/types.rtk-query.ts:
schema: ./dev-test/githunt/schema.json
documents: ./dev-test/githunt/**/*.graphql
plugins:
- typescript
- typescript-operations
- typescript-rtk-query
config:
importBaseApiFrom: '../../packages/plugins/typescript/rtk-query/tests/baseApi'
exportHooks: true
And I think for bundle-splitting purposes it would also work with the near-operation-file preset.
All that is not upstream yet - I will try to get that ready this weekend but don't know how much time it would take to actually get it in.
You could check the repo out, do a local build and install it with something like yalc though.
For a more basic approach without code generation you could look at this example or for an a bit more advanced setup (but also without full code generation, more integrated with existing tooling) you could look at this PR

Apollo GraphQL - How do I use an RxJS Subject as a variable with Apollo Client?

My type-ahead search was working great with REST but I'm converting to GraphQL, which has its challenges.
As the user types a last name into a form field the suggested results display in a data table below. Each letter is handled by the RxJS Subject.
The var searchTerm$ is a type of RXJS observable called a Subject binds to the HTML. The following is called from the OnViewInit lifecycle hook in an Angular app. The search is by the database column last_name.
However, this results in a Bad Request 400 error as the view loads and search doesn't work. I thought maybe this calls for a subscription but everything I find on those is about using web sockets to connect to a remote URL and server. Where do I go from here?
I'm using the Angular Apollo client with Apollo Express but I would be happy with any JS solution and try to figure it out from there. The server side is Nestjs which just wraps Apollo Server.
const lastNameSearch = gql `
query ($input: String!) {
lastNameSearch(input: $input) {
first_name
last_name
user_name
pitch
main_skill_title
skills_comments
member_status
}
}`;
this.apollo
.watchQuery({
query: lastNameSearch,
variables: {
last_name: searchTerm$, // Trying to use the observable here.
},
})
.valueChanges
.subscribe(result => {
console.log('data in lastNameSearch: ', result);
}),
The schema on the server:
lastNameSearch(input: String!): [Member]
The resolver:
#Query()
async lastNameSearch(#Args('input') input: String) {
const response = await this.membersService.lastNameSearch(input);
return await response;
}
Edit:
The error from the Network panel in dev tools. Console message worthless.
{"errors":[{"message":"Variable \"$input\" of required type \"String!\" was not provided.","locations":[{"line":1,"column":8}],"extensions":{"code":"INTERNAL_SERVER_ERROR","exception":{"stacktrace":["GraphQLError: Variable \"$input\" of required type \"String!\" was not provided."," at getVariableValues
And this goes on showing properties and methods in the app for another 300 lines or so.
First, a big thank you to the amazing Daniel Rearden for his help on various questions as I and lots of others on SO learn GraphQL! He has patience!
As Daniel pointed out in comments I had a simple mistake. I'll point it out in the commented code below. However, the big issue was trying to use an observable, subject, or similar method as a variable. Even if the RxJS subject is emitting a string GraphQL will hate trying to use a large object as a var. So I had to use a little reactive programming to solve this.
Setup the observable:
public searchTerm$ = new Subject<string>(); // Binds to the html text box element.
Second, let's set this up in a lifecycle hook where we subscribe to the observable so it will emit letters one at a time as they are typed into an input box.
ngAfterViewInit() {
let nextLetter: string;
// -------- For Last Name Incremental Query --------- //
this.searchTerm$.subscribe(result => {
nextLetter = result; // Setup a normal variable.
this.queryLastName(nextLetter); // Call the GraphQL query below.
});
}
Last step we have the GraphQL query and consuming the returned data object. This works perfect to say type a 'p' into the form and get back from a db all the last names starting with 'p' or 'P'. Type 'r' and the results narrow to last names starting with 'pr', and so on.
private queryLastName(nextLetter) {
const lastNameSearch = gql`
query ($input: String!) {
lastNameSearch(input: $input) {
first_name
last_name
user_name
pitch
main_skill_title
skills_comments
member_status
}
}`;
this.apollo
.watchQuery({
query: lastNameSearch,
variables: {
input: nextLetter, // Notice I had used last_name here instead of input.
},
})
.valueChanges
.subscribe(result => {
// Put the data into some UI in your app, in this case
// an Angular Material data table.
// Notice how we get the data from the returning object.
// The avoids the dreaded "null" error when the shape of the
// returned data doesn't match the query. This put an array
// of objects into the UI.
this.dataSource.data = result.data['lastNameSearch'];
},
);
}

Multiple Queries/Mutation in Apollo 2.1

I need some help using the new Query and Mutation component in Apollo 2.1, especially with multiple queries and mutations.
I have the following problems:
I have a graphql request that depends on a previous graphql result, how can I deal with this?
How do I add two different mutations (in my component I need to do two different actions) in a component that already has a query?
edit 2019/08/24
from the Apollo docs:
The new hooks API for Apollo Client is a simpler way to fetch data in
your React app without the boilerplate of render prop components and
higher-order components (HOC). We recommend using hooks for all new
Apollo code going forward.
original answer:
You are supposed to nest them. See this example:
const NumbersWithData = () => (
<Query query={QueryOne}>
{({ loading: loadingOne, data: { one } }) => (
<Query query={QueryTwo}>
{({ loading: loadingTwo, data: { two }}) => {
if (loadingOne || loadingTwo) return <span>loading...</span>
return <h3>{one} is less than {two}</h3>
}}
</Query>
)}
</Query>
);
To help with keeping the nesting manageable, you could check react-adopt. They have an Apollo ToDo App example, where they combine a Query and multiple Mutations.
For this purpose react-apollo exports a compose function. Using this function you may cleanly use several component enhancers at once. Including multiple graphql(), or even Redux connect() enhancers.
import { Mutation, compose, graphql } from "react-apollo";
class AddTweet extends Component {
....
....
....
}
export default compose(
graphql(GET_AUTHORS, { name: "getAuthors" }),
graphql(ADD_TWEET, { name: "addTweet" }),
connect(...), // incase you are using Redux
)(AddTweet);
An important note is that compose() executes the last enhancer first and works its way backwards through the list of enhancers.
One more thing lets say you were using this.props.data now you will get get undefined. just console.log(this.props) and you will see what is happening to props now. You will be having two properties now getAuthors and addTweet. So now it will be this.props.name-in-compose.name-of-type-in-typeDefs i.e. this.props.getAuthors.getUsers. It took me a bit to figure it out.
In my opinion,
To make a request depends on previous request, you can break that request to children component and pass result of previous request like props to it and do that request.
To use more than one mutation and queries, you can use compose like this
...
#compose(
graphql(GET_FEEDS_QUERY, {name : 'getFeeds'}),
graphql(CREATE_NEW_POST, {name: "createNewPost"}),
graphql(LIKE_POST_MUTATION, { name: "unlikePostMutation"}),
...
)
class HomeScreen extends Component {
...
}
I wrote a Medium Post about how to combine Mutation and Query on the same Component.
Here is a snippet from the post
// other import
import {Query} from “Apollo-graphql”; // new Query Component
import gql from "graphql-tag";
import { graphql } from "react-apollo";
import UserComponent from '../component/UserComponent'; // any component to display query result
const GET_ALL_USER = gql`
{
allUsers: {
firstname,
lastname,
username,
# other information
}
}
`
const UPDATE_USER_STATUS = gql`
mutation UpdateUserStatus($userID: ID!, $status: Int!){
updateUserState(userID: $userID, status: $status){
firstname,
lastname
username
# other information
}
}
`
ExampleComponent extends React.Component{
onEditInformation = async (user) => {
const response = await mutate({
variables: {userID: user}
})
}
render(){
return(
<Query query={GET_ALL_USER}>
{({data: { allUsers }}) => {
return allusers.map(user => {
return (
<UserComponent
user={user}
onEdit={() => this.onEditInformation(user)}
/>
)
})
}}
</Query>
)
}
}
export default graphql(UPDATE_USER_STATUS)(ExampleComponent);
Asides from using compose from react-apollo, another great utility library you can check it out is react-adopt. A great small utility lib that helps you to compose multiple render props type components so you don't have a nested hell patterns.
I have wrote a similar answer that basically covers all your current needs in terms of:
How to consume a previous result from your mapper fn via react-adopt
Combine multiple Query/Mutations from Composed component via react-adopt
Here's the detailed answer you're looking for & hopefully can be helpful to solving your problems :)
Best solution for this
Simply nest graphql function
export default graphql(addBookMutation)(graphql(getAuthorsQuery)(AddBook))
You can refer to this
Apollo concepts

how to wait a graphql query is finished using apollo?

I have the following code :
ngOnInit() {
this.data = this.apollo.query({ query: ResidentQuery }).subscribe(({data, loading}) => {
this.data = data;
this.loading = loading;
});
if (!this.loading) {
// using this.data
}
}
I want data to be loaded before processed themm after the (!this.loading). It is not the case as loading is asynchronous. How I can wait the data is loaded before using them ?
I am making a graphql query using apollo client. ResidentQuery is a string containing the graphql query.
Thank you for your feedbacks !
I'm not sure how angular works, but I know how it works in react and I know the two are similar.
In react, you need to use componentWillReceiveProps() (EDIT: Now Deprecated), for example:
componentWillReceiveProps(newProps){
if(!newProps.query.loading){
this.setState({data: newProps.query.data})
}
}
From the medium article for how angular and react lifecycles are similar
Basically, the props will be bind automatically by Angular, so I
suppose the setter and getter function will be that part, which gives
you a way to generate complex state or variable, like what you can do
in componentWillReceiveProps().

Resources