.ts
TypeScript
(application/typescript)
// 3rd-party
import type { ViewContext } from "@ethicdevs/fastify-stream-react-views";
import type { FastifyReply, FastifyRequest } from "fastify";
// app
import type { CommonViewProps } from "../../types";
import { Const } from "../../const";

export const makeRequestHandler = {
  getter: () => {
    return (request: FastifyRequest, reply: FastifyReply) => {
      const { sectionSlug, pageSlug } = request.params as {
        sectionSlug?: string;
        pageSlug?: string;
      };

      return <T extends Record<string, unknown>>(
        viewName: string,
        props?: T & CommonViewProps,
        viewCtx?: ViewContext
      ) => {
        const viewProps: T & { commonProps: CommonViewProps } = {
          ...props,
          commonProps: {
            authenticated: request.session.data.authenticated,
            title: props?.title,
            currentSectionSlug: sectionSlug,
            currentPageSlug: pageSlug,
            themeScheme:
              (request.cookies?.["theme_scheme"]?.split(".")?.[0] ||
                Const.DEFAULT_THEME_SCHEME) === "light"
                ? "light"
                : "dark",
          },
        } as T & { commonProps: CommonViewProps };

        return reply.streamReactView(viewName, viewProps as any, viewCtx);
      };
    };
  },
};