'Multiple endpoints Graphql

Im working on a project that displays a list of .xml and .txt files on a web browser. Using a MERN Graphql stack, is it possible to have two different endpoints for example http://localhost/xml and http://localhost/txt. Most documents say Graphql use a single endpoint ‘/graphql’ hence asking.



Solution 1:[1]

You can fire up two GraphQL servers to serve two endpoints within a single Express app. But in your specific use case, don't; it's an anti-pattern. A GraphQL API is meant to be based on one single root endpoint. Details for all queries should be represented by selection set and/or parameters, not by endpoints as typical for REST API. In your case, a proper GraphQL query should look like this:

 query {
   listFiles(ext: "xml") {  
     name
     modified
   }
 }

Your schema may look like this:

type Query {
  listFiles(ext: String): [File]
}

Then use a listFiles resolver to do the logic to retrieve the list depending on the given parameter.

Solution 2:[2]

You can use middleware for managing custom endpoints in graphql like below with express

import { yourXMLSchema } from "./schemas/yourXMLSchema";
import { yourXMLSchema } from "./schemas/yourXMLSchema";

app.use("/graphql/:customEndpoint", async (res, req) => {
  let schema = {};
  if (req.params.customEndpoint === 'xml') {
    schema = yourXMLSchema;
  } else if (req.params.customEndpoint === 'txt') {
    schema = yourXMLSchema;
  } else {
    throw new Error('Non-supported endpoint');
  }
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Son Nguyen
Solution 2 Vishal Solanki