William Nemenchainitial commit
86fb32e9/11/2022, 1:13:39 AM
~app/server.ts
.ts
TypeScript
(application/typescript)
// 1st-party
import { InMemoryCacheAdapter } from "@ethicdevs/fastify-stream-react-views";
import {
  AppServer,
  makeAppServer,
  startAppServer,
  stopAppServerAndExit,
} from "@ethicdevs/react-monolith";
// 3rd-party
import fastifyCookie, { CookieSerializeOptions } from "@fastify/cookie";
import fastifyServeStatic from "fastify-static";
// app
import * as Paths from "../paths";
import { Const } from "./const";
import { Env } from "./env";
import { version as appVersion } from "../package.json";
import {
  getEnv,
  localAppDomainPreHandler,
  makeRequestHandler,
} from "./utils/server";

const HOST = process.env.HOST || "localhost";
const PORT = process.env.PORT || 4100;

let server: null | AppServer = null;

async function main(): Promise<AppServer> {
  const env = getEnv();
  const depsBaseUrl = `/${Paths.PUBLIC_FOLDER_NAME}/${Paths.ASSET_DEPS_FOLDER_NAME}`;
  const publicBaseUrl = `/${Paths.PUBLIC_FOLDER_NAME}`;

  const cookiesOpts: CookieSerializeOptions = {
    domain: `.${Env.DEPLOYMENT_DOMAIN}`,
    httpOnly: true,
    path: "/",
    secure: false,
    sameSite: "lax",
    signed: true,
  };

  server = await makeAppServer(HOST, PORT, {
    appName: Const.APP_NAME,
    appVersion,
    env,
    a11y: {
      localeDirection: "ltr",
    },
    assets: {
      depsFolder: Paths.ASSET_DEPS_FOLDER_NAME,
      importPrefix: publicBaseUrl,
    },
    cacheAdapter: new InMemoryCacheAdapter({
      maxSize: Const.SSR_CACHE_MAX_SIZE_BYTES,
    }),
    featureFlags: {
      withIncrementalBuild: true,
      withImportsMap: true,
      withInstantRouter: true,
      withStyledSSR: true,
      withTreeShaking: true,
    },
    paths: {
      assetsOutFolder: Paths.PUBLIC_FOLDER,
      distFolder: Paths.DIST_FOLDER,
      islandsFolder: Paths.ISLANDS_FOLDER,
      rootFolder: Paths.ROOT_FOLDER,
      routesFile: Paths.ROUTES_FILE,
      viewsFolder: Paths.VIEWS_FOLDER,
    },
    externalDependencies: {
      "cross-fetch": "CrossFetch",
      "markdown-to-jsx": "MarkdownToJSX",
    },
    baseHeadTags: [
      {
        kind: "meta",
        name: "og:site_name",
        content: Const.APP_NAME,
      },
    ],
    baseScriptTags: [
      {
        async: true,
        id: "es-importmap-shim",
        src: `${depsBaseUrl}/es-module-shims.production.min.js`,
        type: "application/javascript",
      },
      /*{
        async: true,
        defer: false,
        id: "importmap-service-worker-register",
        src: `/register-imsw.js`,
        type: "module",
      },*/
    ],
    setupServerBeforeRoutes(s) {
      s.addHook("preHandler", localAppDomainPreHandler);

      s.register(fastifyServeStatic, {
        root: Paths.PUBLIC_FOLDER,
        prefix: publicBaseUrl,
      });

      s.register(fastifyCookie, {
        secret: Env.COOKIE_SECRET,
        parseOptions: cookiesOpts,
      });

      s.decorateReply("makeRequestHandler", makeRequestHandler);
    },
  });

  server.get("/interceptor-imsw.js", {}, async (_, reply) => {
    return reply.sendFile("interceptor-imsw.js");
  });

  server.get("/register-imsw.js", {}, async (_, reply) => {
    return reply.sendFile("register-imsw.js");
  });

  await startAppServer(server);

  return server;
}

// Catch errors that are fatal
["unhandledRejection", "uncaughtException"].forEach((exception) => {
  process.on(exception, async (reason: Error) => {
    await stopAppServerAndExit(server, reason);
  });
});

// Catch standard linux signals to kill a daemon
["SIGQUIT", "SIGTERM", "SIGINT"].forEach((killSignal) => {
  process.on(killSignal, async () => {
    await stopAppServerAndExit(server);
  });
});

// Start the application server
main()
  .then((server) => {
    // safe because it wont start if null
    const { $config, $host, $port } = server.reactMonolith!;
    console.log(
      `[🚀][${$config.env}] App Server ready at http://${$host}:${$port} !`
    );
  })
  .catch(async (err) => {
    const error = err as Error;
    console.error(`[❌] Cannot start App Server. Error: ${error.message}`);
    await stopAppServerAndExit(null, error);
  });