Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

2.6 KB
Raw Blame
import { initTRPC } from "@trpc/server";
import type { AppContext } from "./context.server";
import {
  createApiCompatibilityPayload,
  getApiCompatibilityPayload,
} from "../api-compatibility";

const getWebstudioErrorCode = (cause: unknown) => {
  if (typeof cause !== "object" || cause === null) {
    return;
  }
  const code = (cause as { webstudioCode?: unknown }).webstudioCode;
  return typeof code === "string" ? code : undefined;
};

const getValidationIssues = (cause: unknown) => {
  if (typeof cause !== "object" || cause === null) {
    return;
  }
  const issues = (cause as { issues?: unknown }).issues;
  return Array.isArray(issues) ? issues : undefined;
};

const getMissingAssetNames = (cause: unknown) => {
  if (typeof cause !== "object" || cause === null) {
    return;
  }
  const error = cause as {
    webstudioCode?: unknown;
    missingAssetNames?: unknown;
  };
  return error.webstudioCode === "MISSING_IMPORTED_ASSET_FILES" &&
    Array.isArray(error.missingAssetNames) &&
    error.missingAssetNames.every((name) => typeof name === "string")
    ? error.missingAssetNames
    : undefined;
};

export const {
  router,
  procedure,
  middleware,
  mergeRouters,
  createCallerFactory,
} = initTRPC.context<AppContext>().create({
  errorFormatter({ shape, error, ctx }) {
    const target = ctx?.apiClient.type;
    const webstudioCode = getWebstudioErrorCode(error.cause);
    const payload =
      getApiCompatibilityPayload(error.cause) ??
      (error.code === "NOT_FOUND" &&
      webstudioCode === undefined &&
      (target === "browser" || target === "cli")
        ? createApiCompatibilityPayload({
            reason: "apiProcedureNotFound",
            target,
          })
        : undefined);
    const issues = getValidationIssues(error.cause);
    const missingAssetNames = getMissingAssetNames(error.cause);

    if (
      payload === undefined &&
      webstudioCode === undefined &&
      issues === undefined
    ) {
      return shape;
    }

    return {
      ...shape,
      data: {
        ...shape.data,
        ...(payload === undefined ? {} : { apiCompatibility: payload }),
        ...(webstudioCode === undefined ? {} : { webstudioCode }),
        ...(issues === undefined ? {} : { issues }),
        ...(missingAssetNames === undefined ? {} : { missingAssetNames }),
      },
    };
  },
});

export const createCacheMiddleware = (seconds: number) =>
  middleware(async ({ path, ctx, next }) => {
    // tRPC batches multiple requests into a single network call.
    // The `path` is used as key to find the least max age among all paths for caching
    ctx.trpcCache.setMaxAge(path, seconds);

    return next({ ctx });
  });