Reputation: 2624
updated on Oct. 2 with more clarifications and example
I am building a NestJS API (not Next.js for React server-side rendering). To help with adoption, I am thinking of offering both GraphQL and traditional REST endpoints, but the effort would be GraphQL first. Ideally, I would develop GraphQL first, and REST essentially just make GraphQL query call internally without any redirection.
For example, let's say there is an endpoint of listing all the classes offered by the year, the equivalent GraphQL endpoint would be like
{
classes( year: 2021 ) {
courseId,
name,
teacher {
firstName,
lastName,
},
credit,
prerequisite {
courseId,
name,
}
}
}
Our API would also expose REST endpoint /api/classes?year=2021
, and instead of replicating the same logic what GraphQL resolves would have done in the controller, ideally the controller would just put together a GraphQL query and throw it right back to the NestJS instance so all the http headers etc would be preserved.
Wondering how I can achieve that.
In
Upvotes: 4
Views: 3159
Reputation: 168
This appears to be a simple http request to a local url. To aid with gql I'd use something like graphql-request.
You should be able to preconfigure your http client with a url before injection to the controller, which would help (for example) with different env configurations.
Upvotes: 0
Reputation: 320
NestJS has little to do with what you are trying to achieve since it is ultimately on for server-side rendering of a React application. Your request concerns only the API side of it which you can (and probably should in my humble opinion) build independently.
Assuming your server will be JS based, it will in the end use graphql.js has this is the reference implementation that all server use.
This allows you to call the graphql()
function with the schema, resolvers and query to get your result.
If you use servers like Apollo, they usually offer an API on top of it to execute queries direction. For Apollo, I believe you could use server.executeOperation
.
The idea in the end if you need to create a singleton of your schema/server which you can then import in the controller of your rest route and use it to make GraphQL requests. If using express that could look like:
const apollo = new ApolloServer({
schema,
});
export default apollo;
import server from './apollo';
const router = express.Router();
router.get('/some/path', async (req: Request, res: Response) => {
const result = await server.executeOperation({
query: '{ some { id }}',
});
res.json(result);
});
Upvotes: -3