DEV Community

Jace Warren
Jace Warren

Posted on

What are some file structure best practices for apollo server?

What are people finding as a best practice for folder structure in your apollo server?

E.g. I'm wondering if it would be a good idea to structure things like so:

src/
    enum/
    input/
    interface/
    mock/
    mutation/
    query/
    resolver/
    scalar/
    subscription/
    type/
    server.ts
Enter fullscreen mode Exit fullscreen mode

Then I was thinking I could merge everything together like so:

import http from "http";
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { makeExecutableSchema } from "graphql-tools";
import { mergeResolvers, mergeTypes } from "merge-graphql-schemas";
import path from "path";
import glob from "glob";
import fs from "fs";

(async () => {
  //   TypeDefs
  const typeDefs = glob
    .sync(path.join(__dirname, "./**/*.graphql"))
    .map(f => fs.readFileSync(f, { encoding: "utf8" }));

  // Resolvers
  const resolvers = await Promise.all(
    glob
      .sync(path.join(__dirname, "./**/*.resolver.ts"))
      .map(async f => (await import(f)).resolver)
  );

  //   Mocks
  const mocks = await Promise.all(
    glob
      .sync(path.join(__dirname, "./**/*.mock.ts"))
      .map(async f => (await import(f)).mock)
  );

  const schema = makeExecutableSchema({
    resolvers: mergeResolvers(resolvers),
    resolverValidationOptions: {
      requireResolversForResolveType: false
    },
    typeDefs: mergeTypes(typeDefs)
  });

  const PORT = 4000;
  const app = express();
  const server = new ApolloServer({
    mocks: Object.assign({}, ...mocks),
    schema
  });
  server.applyMiddleware({ app });

  const httpServer = http.createServer(app);
  server.installSubscriptionHandlers(httpServer);

  httpServer.listen(PORT, () => {
    console.log(
      `πŸš€ Server ready at http://localhost:${PORT}${server.graphqlPath}`
    );
    console.log(
      `πŸš€ Subscriptions ready at ws://localhost:${PORT}${
        server.subscriptionsPath
      }`
    );
  });
})();
Enter fullscreen mode Exit fullscreen mode

What do you think?

Top comments (3)

Collapse
 
marcus-sa profile image
Marcus S. Abildskov • Edited

I'd say the best architecture is using Nest with their GraphQL plugin

Collapse
 
nelsonblack profile image
Nelson Bwogora

i second this , been using it , quite a savior

Collapse
 
_kkv_ profile image
dundich