import express from "express"; import { createHandler } from "graphql-http/lib/use/http"; import { buildSchema } from "graphql"; import { ruruHTML } from "ruru/server"; import { serveStatic } from "ruru/static"; import { generateDefinitions } from "../generateLexiconSchema"; // Initialize Express app const app = express(); const lexiconIds = (await import("../../lexicons.json")).lexicons; // Generate definitions (this is what main.ts does when no --output flag is provided) const { chunks: generatedDefinitions, lexiconCalls } = generateDefinitions(lexiconIds); // Define GraphQL schema using GraphQL-JS const schema = buildSchema( generatedDefinitions.join("\n\n") + ` type Query { lexicon: Lexicon }`, ); const ty = (schema.getQueryType().getFields()["lexicon"].resolve = () => ({})); // Serve static files for (const key of Object.keys(lexiconCalls)) { const segments = key.split("."); const ty = schema.getType( ["Lexicon"].concat(segments.slice(0, -1)).join("_"), ); ty.getFields()[segments.slice(-1)[0]].resolve = lexiconCalls[key]; for (let i = 1; i < segments.length; i++) { const ty = schema.getType( ["Lexicon"].concat(segments.slice(0, i - 1)).join("_"), ); ty.getFields()[segments.slice(0, i).pop()].resolve = () => ({}); } } app.use(express.static("public")); // Serve lexicons.json at /lexicons path app.get("/lexicons", (req, res) => { res.json(Object.keys(lexiconCalls)); }); const handler = createHandler({ schema }); // GraphQL endpoint app.all("/graphql", handler); /** * Setup GraphiQL */ const config = { staticPath: "/ruru-static/", endpoint: "/graphql" }; // Serve Ruru HTML app.get("/graphiql", (req, res) => { res.format({ html: () => res.status(200).send(ruruHTML(config)), default: () => res.status(406).send("Not Acceptable"), }); }); // Serve static files app.use(serveStatic(config.staticPath)); // Start the HTTP server const PORT = process.env.PORT || 4000; const httpServer = app.listen(PORT, () => { console.log(`Server ready at http://localhost:${PORT}`); console.log(`GraphQL endpoint: http://localhost:${PORT}/graphql`); console.log(`GraphiQL endpoint: http://localhost:${PORT}/graphiql`); }); // Handle server shutdown gracefully process.on("SIGINT", () => { httpServer.close(() => { console.log("Server closed"); }); });