Running a server with ApolloServer on my Node environment:
// 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();
ApolloServer
constructor requires typeDefs
as an argument:
// schema.js
const { gql } = require('apollo-server-express');
const typeDefs = gql`
type Query{
hello: String
}
`;
module.exports = typeDefs;
I also need to define the typeDefs in my front-end client for queries:
// 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;
The redundancy of defining the same typeDef in both the Apollo Server schema and client side leaves me unsure about how to optimize this setup.