Skip to content

Commit

Permalink
fix(draft-mode): support guest space with draft mode
Browse files Browse the repository at this point in the history
  • Loading branch information
chrishelgert committed Aug 7, 2023
1 parent a1338d2 commit 222f482
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 17 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"next-pwa": "^5.6.0",
"next-seo": "^5.15.0",
"next-sitemap": "^3.1.32",
"query-string": "^8.1.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-focus-lock": "^2.9.2",
Expand Down
14 changes: 2 additions & 12 deletions src/_ctf-private/useContentfulEditorial.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { GraphQLClient } from 'graphql-request';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import create from 'zustand';
Expand All @@ -11,7 +10,7 @@ import {
guestSpaceRequiredParameters,
resetParam,
} from '@src/_ctf-private/constants';
import { getSdk } from '@src/lib/__generated/sdk';
import { createGuestSpaceClient } from '@src/lib/client';

interface ContentfulEditorialStore {
preview: boolean;
Expand Down Expand Up @@ -109,17 +108,8 @@ export const useContentfulEditorial = () => {
};
}

const graphQlClient = new GraphQLClient(
`https://graphql.${domain}/content/v1/spaces/${space_id}/`,
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${preview ? preview_token : delivery_token}`,
},
},
);
return {
preview,
client: getSdk(graphQlClient),
client: createGuestSpaceClient({ domain, preview, preview_token, delivery_token, space_id }),
};
};
16 changes: 16 additions & 0 deletions src/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,19 @@ const previewGraphQlClient = new GraphQLClient(endpoint, {

export const client = getSdk(graphQlClient);
export const previewClient = getSdk(previewGraphQlClient);

export const createGuestSpaceClient = ({
domain = 'contentful.com',
space_id,
preview,
preview_token,
delivery_token,
}) =>
getSdk(
new GraphQLClient(`https://graphql.${domain}/content/v1/spaces/${space_id}/`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${preview ? preview_token : delivery_token}`,
},
}),
);
35 changes: 30 additions & 5 deletions src/pages/api/draft.page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { COOKIE_NAME_PRERENDER_BYPASS } from 'next/dist/server/api-utils';
import qs from 'query-string';

import { previewClient } from '@src/lib/client';
import {
editorialParameters,
guestSpaceOptionalParameters,
guestSpaceRequiredParameters,
} from '@src/_ctf-private';
import { createGuestSpaceClient, previewClient } from '@src/lib/client';

function enableDraftMode(res) {
res.setDraftMode({ enable: true });
Expand All @@ -22,6 +28,18 @@ function enableDraftMode(res) {
}
}

function getGuestSpaceParams(query: Record<string, any>) {
if (guestSpaceRequiredParameters.every(param => query[param])) {
return [
...guestSpaceRequiredParameters,
...guestSpaceOptionalParameters,
...editorialParameters,
].reduce((prev, curr) => ({ ...prev, [curr]: query[curr] }), {});
}

return null;
}

export default async (req, res) => {
const { secret, slug, locale } = req.query;

Expand All @@ -31,10 +49,17 @@ export default async (req, res) => {
return res.status(401).json({ message: 'Invalid token' });
}

// For main private we need to support guest spaces
const guestSpaceParams = getGuestSpaceParams(req.query);
const queryString = guestSpaceParams ? `?${qs.stringify(guestSpaceParams)}` : '';
const client = queryString.length
? createGuestSpaceClient(guestSpaceParams as any)
: previewClient;

// Check for a slug, if no slug is passed we assume we need to redirect to the root
if (slug) {
try {
const blogPageData = await previewClient.pageBlogPost({
const blogPageData = await client.pageBlogPost({
slug,
locale,
preview: true,
Expand All @@ -50,13 +75,13 @@ export default async (req, res) => {
enableDraftMode(res);

// Redirect to the path from the fetched post
res.redirect(`/${locale ? `${locale}/` : ''}${blogPost?.slug}`);
res.redirect(`/${locale ? `${locale}/` : ''}${blogPost?.slug}${queryString}`);
} catch {
return res.status(401).json({ message: 'Invalid slug' });
}
} else {
try {
const landingPageData = await previewClient.pageLanding({
const landingPageData = await client.pageLanding({
locale,
preview: true,
});
Expand All @@ -69,7 +94,7 @@ export default async (req, res) => {
enableDraftMode(res);

// Redirect to the root
res.redirect(`/${locale ? `${locale}` : ''}`);
res.redirect(`/${locale ? `${locale}` : ''}${queryString}`);
} catch {
return res.status(401).json({ message: 'Page not found' });
}
Expand Down
24 changes: 24 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4576,6 +4576,11 @@ decamelize@^1.2.0:
resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290"
integrity sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==

decode-uri-component@^0.4.1:
version "0.4.1"
resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.4.1.tgz#2ac4859663c704be22bf7db760a1494a49ab2cc5"
integrity sha512-+8VxcR21HhTy8nOt6jf20w0c9CADrw1O8d+VZ/YzzCt4bJ3uBjw+D1q2osAB8RnpwwaeYBxy0HyKQxD5JBMuuQ==

decompress-response@^3.3.0:
version "3.3.0"
resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-3.3.0.tgz#80a4dd323748384bfa248083622aedec982adff3"
Expand Down Expand Up @@ -5394,6 +5399,11 @@ fill-range@^7.0.1:
dependencies:
to-regex-range "^5.0.1"

filter-obj@^5.1.0:
version "5.1.0"
resolved "https://registry.yarnpkg.com/filter-obj/-/filter-obj-5.1.0.tgz#5bd89676000a713d7db2e197f660274428e524ed"
integrity sha512-qWeTREPoT7I0bifpPUXtxkZJ1XJzxWtfoWWkdVGqa+eCr3SHW/Ocp89o8vLvbUuQnadybJpjOKu4V+RwO6sGng==

find-cache-dir@^3.3.1:
version "3.3.2"
resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-3.3.2.tgz#b30c5b6eff0730731aea9bbd9dbecbd80256d64b"
Expand Down Expand Up @@ -7905,6 +7915,15 @@ pvutils@^1.1.3:
resolved "https://registry.yarnpkg.com/pvutils/-/pvutils-1.1.3.tgz#f35fc1d27e7cd3dfbd39c0826d173e806a03f5a3"
integrity sha512-pMpnA0qRdFp32b1sJl1wOJNxZLQ2cbQx+k6tjNtZ8CpvVhNqEPRgivZ2WOUev2YMajecdH7ctUPDvEe87nariQ==

query-string@^8.1.0:
version "8.1.0"
resolved "https://registry.yarnpkg.com/query-string/-/query-string-8.1.0.tgz#e7f95367737219544cd360a11a4f4ca03836e115"
integrity sha512-BFQeWxJOZxZGix7y+SByG3F36dA0AbTy9o6pSmKFcFz7DAj0re9Frkty3saBn3nHo3D0oZJ/+rx3r8H8r8Jbpw==
dependencies:
decode-uri-component "^0.4.1"
filter-obj "^5.1.0"
split-on-first "^3.0.0"

queue-microtask@^1.2.2:
version "1.2.3"
resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243"
Expand Down Expand Up @@ -8667,6 +8686,11 @@ sourcemap-codec@^1.4.8:
resolved "https://registry.yarnpkg.com/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz#ea804bd94857402e6992d05a38ef1ae35a9ab4c4"
integrity sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==

split-on-first@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/split-on-first/-/split-on-first-3.0.0.tgz#f04959c9ea8101b9b0bbf35a61b9ebea784a23e7"
integrity sha512-qxQJTx2ryR0Dw0ITYyekNQWpz6f8dGd7vffGNflQQ3Iqj9NJ6qiZ7ELpZsJ/QBhIVAiDfXdag3+Gp8RvWa62AA==

sponge-case@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/sponge-case/-/sponge-case-1.0.1.tgz#260833b86453883d974f84854cdb63aecc5aef4c"
Expand Down

0 comments on commit 222f482

Please sign in to comment.