Skip to content

Commit

Permalink
Merge pull request #12 from buildheadless/preview
Browse files Browse the repository at this point in the history
Separate sanity server loader from client loader
  • Loading branch information
thomasKn authored Nov 19, 2023
2 parents 3c5f659 + 8d6dc37 commit 4047418
Show file tree
Hide file tree
Showing 12 changed files with 83 additions and 39 deletions.
14 changes: 4 additions & 10 deletions templates/hydrogen-theme/app/components/sanity/VisualEditing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { enableOverlays } from "@sanity/overlays";
import { cx } from "class-variance-authority";

import { useEnvironmentVariables } from "~/hooks/useEnvironmentVariables";
import { getSanityClient } from "~/lib/sanity/client";
import { useLiveMode } from "~/lib/sanity/sanity.loader";
import { useIsInIframe } from "~/hooks/useIsInIframe";
import { useSanityClient } from "~/hooks/useSanityClient";
import { useSanityLoader } from "~/hooks/useSanityLoader";

export function VisualEditing() {
const env = useEnvironmentVariables();
Expand All @@ -18,14 +18,8 @@ export function VisualEditing() {
null
);
const sanityStudioUrl = env?.SANITY_STUDIO_URL!;
const { client } = getSanityClient({
projectId: env?.SANITY_STUDIO_PROJECT_ID!,
dataset: env?.SANITY_STUDIO_DATASET!,
studioUrl: sanityStudioUrl,
useStega: env?.SANITY_STUDIO_USE_STEGA!,
apiVersion: env?.SANITY_STUDIO_API_VERSION!,
useCdn: env?.NODE_ENV === "production",
});
const client = useSanityClient();
const { useLiveMode } = useSanityLoader();

useEffect(() => {
if (!sanityStudioUrl) return;
Expand Down
19 changes: 19 additions & 0 deletions templates/hydrogen-theme/app/hooks/useSanityClient.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { getSanityClient } from "~/lib/sanity/client";
import { useEnvironmentVariables } from "./useEnvironmentVariables";
import { useSanityPreviewMode } from "./useSanityPreviewMode";

export function useSanityClient() {
const env = useEnvironmentVariables();
const sanityPreviewMode = useSanityPreviewMode();
const { client } = getSanityClient({
projectId: env?.SANITY_STUDIO_PROJECT_ID!,
dataset: env?.SANITY_STUDIO_DATASET!,
studioUrl: env?.SANITY_STUDIO_URL!,
useStega: env?.SANITY_STUDIO_USE_STEGA!,
apiVersion: env?.SANITY_STUDIO_API_VERSION!,
useCdn: env?.NODE_ENV === "production",
sanityPreviewMode,
});

return client;
}
13 changes: 13 additions & 0 deletions templates/hydrogen-theme/app/hooks/useSanityLoader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { createQueryStore } from "@sanity/react-loader";
import { useSanityClient } from "./useSanityClient";

export function useSanityLoader() {
const client = useSanityClient();
const queryStore = createQueryStore({
client,
ssr: false,
});
const { useLiveMode, useQuery } = queryStore;

return { queryStore, useLiveMode, useQuery };
}
4 changes: 2 additions & 2 deletions templates/hydrogen-theme/app/hooks/useSanityQuery.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import type { QueryParams } from "@sanity/client/stega";
import type { QueryStoreState, UseQueryOptions } from "@sanity/react-loader";

import { useQuery } from "~/lib/sanity/sanity.loader";
import { useSanityLoader } from "./useSanityLoader";

export function useSanityQuery<T>(cms: {
initial: UseQueryOptions<T>["initial"];
params: QueryParams;
query: string;
}): QueryStoreState<T, unknown> {
const { initial, params, query } = cms;
const { useQuery } = useSanityLoader();

return useQuery(query, params, {
initial,
Expand Down
13 changes: 11 additions & 2 deletions templates/hydrogen-theme/app/lib/sanity/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,17 @@ export const getSanityClient = (args: {
studioUrl: string;
apiVersion: string;
useCdn: boolean;
sanityPreviewMode?: boolean;
}) => {
const { projectId, dataset, useStega, studioUrl, apiVersion, useCdn } = args;
const {
projectId,
dataset,
useStega,
studioUrl,
apiVersion,
useCdn,
sanityPreviewMode,
} = args;

return {
client: createClient({
Expand All @@ -18,7 +27,7 @@ export const getSanityClient = (args: {
useCdn,
apiVersion: apiVersion || "2023-10-01",
stega: {
enabled: useStega === "true" ? true : false,
enabled: sanityPreviewMode && useStega === "true" ? true : false,
studioUrl,
},
}),
Expand Down
7 changes: 0 additions & 7 deletions templates/hydrogen-theme/app/lib/sanity/sanity.loader.ts

This file was deleted.

30 changes: 19 additions & 11 deletions templates/hydrogen-theme/app/lib/sanity/sanity.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ import type {
} from "@sanity/client/stega";
import { CacheShort, createWithCache } from "@shopify/hydrogen";

import { queryStore } from "./sanity.loader";
import { getSanityClient } from "./client";
import { createQueryStore } from "@sanity/react-loader";

type CreateSanityClientOptions = {
cache: Cache;
waitUntil: ExecutionContext["waitUntil"];
sanityPreviewMode: boolean;
config: {
projectId: string;
dataset: string;
Expand Down Expand Up @@ -45,13 +46,10 @@ export type Sanity = {
}>;
};

let sanityServerClientHasBeenInitialized = false;

export function createSanityClient(options: CreateSanityClientOptions) {
const { cache, waitUntil, config } = options;
const { cache, waitUntil, config, sanityPreviewMode } = options;
const { projectId, dataset, useStega, useCdn, studioUrl, apiVersion } =
config;
const { loadQuery } = queryStore;

const { client } = getSanityClient({
projectId,
Expand All @@ -60,12 +58,13 @@ export function createSanityClient(options: CreateSanityClientOptions) {
apiVersion,
useStega,
studioUrl,
sanityPreviewMode,
});

if (!sanityServerClientHasBeenInitialized) {
queryStore.setServerClient(client);
sanityServerClientHasBeenInitialized = true;
}
const queryStore = createQueryStore({
client,
ssr: false,
});

const sanity: Sanity = {
client,
Expand All @@ -75,8 +74,9 @@ export function createSanityClient(options: CreateSanityClientOptions) {
cache: strategy = CacheShort(),
queryOptions,
}) {
const { loadQuery } = queryStore;
const { query } = groqdQuery as GroqdQuery;
const queryHash = await hashQuery(query, params);
const queryHash = await hashQuery(query, params, sanityPreviewMode);
const withCache = createWithCache({
cache,
waitUntil,
Expand Down Expand Up @@ -119,9 +119,17 @@ export async function sha256(message: string): Promise<string> {
* Hash query and its parameters for use as cache key
* NOTE: Oxygen deployment will break if the cache key is long or contains `\n`
*/
function hashQuery(query: GroqdQuery["query"], params?: QueryParams) {
function hashQuery(
query: GroqdQuery["query"],
params?: QueryParams,
sanityPreviewMode?: boolean
) {
let hash = query;

if (sanityPreviewMode) {
hash += "previewMode";
}

if (params !== null) {
hash += JSON.stringify(params);
}
Expand Down
8 changes: 5 additions & 3 deletions templates/hydrogen-theme/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { Fonts } from "./components/Fonts";
import { CMS_SETTINGS_QUERY } from "./qroq/queries";
import { generateFontsPreloadLinks } from "./lib/fonts";
import { useLocale } from "./hooks/useLocale";
import { vercelStegaCleanAll } from "@sanity/client/stega";

// This is important to avoid re-fetching root queries on sub-navigations
export const shouldRevalidate: ShouldRevalidateFunction = ({
Expand Down Expand Up @@ -78,9 +79,8 @@ export const meta: MetaFunction<typeof loader> = (loaderData) => {
};

export async function loader({ context }: LoaderFunctionArgs) {
const { session, cart, env, sanity, locale, sanitySession } = context;
const { session, cart, env, sanity, locale, sanityPreviewMode } = context;
const customerAccessToken = await session.get("customerAccessToken");
const sanityPreviewMode = await sanitySession.has("previewMode");

const cmsSettings = await sanity.query({
groqdQuery: CMS_SETTINGS_QUERY,
Expand All @@ -100,7 +100,9 @@ export async function loader({ context }: LoaderFunctionArgs) {
locale,
sanityPreviewMode,
cms: {
initial: cmsSettings,
initial: sanityPreviewMode
? cmsSettings
: vercelStegaCleanAll(cmsSettings),
query: CMS_SETTINGS_QUERY.query,
params: {},
},
Expand Down
1 change: 1 addition & 0 deletions templates/hydrogen-theme/app/routes/($locale).$.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { I18nLocale } from "~/lib/type";
import { CmsSection } from "~/components/CmsSection";
import { PAGE_QUERY } from "~/qroq/queries";
import { useSanityQuery } from "~/hooks/useSanityQuery";
import { useSanityPreviewMode } from "~/hooks/useSanityPreviewMode";

export async function loader({ context, params, request }: LoaderFunctionArgs) {
const { sanity, locale } = context;
Expand Down
9 changes: 5 additions & 4 deletions templates/hydrogen-theme/app/routes/sanity.preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import type {
ActionFunctionArgs,
LoaderFunctionArgs,
} from "@shopify/remix-oxygen";
import { json, redirect } from "@shopify/remix-oxygen";
import { json, redirectDocument } from "@shopify/remix-oxygen";

import { notFound } from "~/lib/utils";

const ROOT_PATH = "/" as const;

export async function action({ context, request }: ActionFunctionArgs) {
const { sanitySession, env } = context;
const { sanitySession } = context;

if (!(request.method === "POST" && sanitySession)) {
return json({ message: "Method not allowed" }, 405);
Expand All @@ -18,7 +19,7 @@ export async function action({ context, request }: ActionFunctionArgs) {
const slug = (body.get("slug") as string) ?? ROOT_PATH;
const redirectTo = slug;

return redirect(redirectTo, {
return redirectDocument(redirectTo, {
headers: {
"Set-Cookie": await sanitySession.destroy(),
},
Expand All @@ -43,7 +44,7 @@ export async function loader({ context, request }: LoaderFunctionArgs) {
"Set-Cookie": useStega ? await sanitySession.commit() : "",
};

return redirect(redirectTo, {
return redirectDocument(redirectTo, {
status: 307,
headers,
});
Expand Down
1 change: 1 addition & 0 deletions templates/hydrogen-theme/remix.env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ declare module "@shopify/remix-oxygen" {
storefront: Storefront;
session: HydrogenSession;
sanitySession: SanitySession;
sanityPreviewMode: boolean;
waitUntil: ExecutionContext["waitUntil"];
sanity: Sanity;
locale: I18nLocale;
Expand Down
3 changes: 3 additions & 0 deletions templates/hydrogen-theme/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export default {
HydrogenSession.init(request, [env.SESSION_SECRET]),
SanitySession.init(request, [env.SESSION_SECRET]),
]);
const sanityPreviewMode = await sanitySession.has("previewMode");

/*
* Create Hydrogen's Storefront client.
Expand Down Expand Up @@ -79,6 +80,7 @@ export default {
const sanity = createSanityClient({
cache,
waitUntil,
sanityPreviewMode,
config: {
projectId: envVars.SANITY_STUDIO_PROJECT_ID,
dataset: envVars.SANITY_STUDIO_DATASET,
Expand All @@ -99,6 +101,7 @@ export default {
getLoadContext: () => ({
session,
sanitySession,
sanityPreviewMode,
storefront,
cart,
env: envVars,
Expand Down

0 comments on commit 4047418

Please sign in to comment.