I'm using ApolloServer on my Node env to run a server:
// App.js
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const resolvers = require('./resolvers.js');
const typeDefs = require('./schema');
const apolloServer = new ApolloServer({
resolvers,
typeDefs,
});
async function startServer() {
await apolloServer.start();
const app = express();
apolloServer.applyMiddleware({ app });
app.listen(4000, function () {
console.log(` Server ready at http://localhost:4000${apolloServer.graphqlPath}`)
});
}
startServer();
The ApolloServer constructor takes a typeDefs argument:
// schema.js
const { gql } = require('apollo-server-express');
const typeDefs = gql`
type Query{
hello: String
}
`;
module.exports = typeDefs;
But in my front-end client I also need to define the typeDefs to use in a query:
// MyComponent
import { useQuery } from '@apollo/client';
import { FC } from 'react';
import './MyComponent.css';
import typedefs from '../../server/typedefs'
interface MyComponentProps {}
const MyComponent: FC<MyComponentProps> = () => {
const { data: hello, loading: isLoading } = useQuery(typedefs.Hello);
if (isLoading) {
return (
<div>Loading...</div>
)
}
return (
<div className="MyComponent">
data: {hello.hello}
</div>
)
}
export default MyComponent
// typeDefs.ts
import {gql} from '@apollo/client';
const Hello = gql`
query {
hello
}
`;
const queries = { Hello };
export default queries;
As you can see I define a typedef in both my Apollo Server schema and in my client typedef. This feel redundant but I'm unsure on how to improve it.