Skip to content

Commit

Permalink
fix: (#281,#271) previews working in next example
Browse files Browse the repository at this point in the history
  • Loading branch information
wjohnsto committed Jun 17, 2021
1 parent 0aa4bd2 commit 3ec213c
Show file tree
Hide file tree
Showing 10 changed files with 141 additions and 109 deletions.
47 changes: 38 additions & 9 deletions examples/next/getting-started/src/pages/posts/[postSlug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,36 @@ import { getNextStaticProps, client, is404 } from '@wpengine/headless-next';
import { Footer, Header, Hero } from 'components';
import { GetStaticPropsContext } from 'next';
import Head from 'next/head';
import type { Post } from '@wpengine/headless-core';
import styles from 'scss/pages/post.module.scss';

export default function Page() {
const { usePost, useGeneralSettings } = client();
export interface PostProps {
post: Post | Post['preview']['node'] | null | undefined;
preview?: boolean;
}

export function PostComponent({ post, preview }: PostProps) {
const { useGeneralSettings, useQuery } = client();
const generalSettings = useGeneralSettings();
const post = usePost();
const { isLoading } = useQuery().$state;

if (preview && (typeof window === 'undefined' || isLoading)) {
return (
<>
<Header
title={generalSettings.title}
description={generalSettings.description}
/>
<Hero title={'Loading...'} />
<main className="content content-single">
<div className="wrap">
<div>Loading...</div>
</div>
</main>
<Footer copyrightHolder={generalSettings.title} />
</>
);
}

return (
<>
Expand All @@ -17,18 +42,15 @@ export default function Page() {

<Head>
<title>
{post.title()} - {generalSettings.title}
{post?.title()} - {generalSettings.title}
</title>
</Head>

<Hero title={post.title()} bgImage={post.featuredImageId} />
<Hero title={post?.title()} bgImage={post?.featuredImageId} />

<main className="content content-single">
<div className="wrap">
{post && (
<div dangerouslySetInnerHTML={{ __html: post.content() ?? '' }} />
)}
<div>{ post.author.node.nicename }</div>
<div dangerouslySetInnerHTML={{ __html: post?.content() ?? '' }} />
</div>
</main>

Expand All @@ -37,6 +59,13 @@ export default function Page() {
);
}

export default function Page() {
const { usePost } = client();
const post = usePost();

return <PostComponent post={post} />;
}

export async function getStaticProps(context: GetStaticPropsContext) {
if (await is404(context)) {
return {
Expand Down
8 changes: 6 additions & 2 deletions examples/next/getting-started/src/pages/posts/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { GetStaticPropsContext } from 'next';
import Head from 'next/head';
import { useRouter } from 'next/router';
import React from 'react';
import styles from 'scss/pages/home.module.scss';
import styles from 'scss/pages/posts.module.scss';

export default function Page() {
const {
query = {},
} = useRouter();
const { postSlug, postCursor } = query;
const { usePosts, useGeneralSettings } = client();
const { usePosts, useGeneralSettings, useQuery, } = client();
const generalSettings = useGeneralSettings();
const isBefore = postSlug === 'before';
const posts = usePosts({
Expand All @@ -21,6 +21,10 @@ export default function Page() {
last: isBefore ? 6 : undefined,
});

if (useQuery().$state.isLoading) {
return null;
}

return (
<>
<Header
Expand Down
46 changes: 0 additions & 46 deletions examples/next/getting-started/src/pages/preview/post/preview.tsx

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// CSS for the themes/front-page.tsx template.
// CSS for the index.tsx template.

@import "scss/variables";

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// CSS for the themes/front-page.tsx template.
// CSS for the posts/index.tsx template.

@import "scss/variables";

Expand Down
27 changes: 17 additions & 10 deletions packages/core/src/auth/authorize.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { headlessConfig } from '../config';
import isString from 'lodash/isString';
import { parseUrl } from '../utils';
import { isServerSide, parseUrl } from '../utils';
import { CookieOptions, getAccessToken } from './cookie';
import fetch from 'isomorphic-fetch';
import isEmpty from 'lodash/isEmpty';
import trimEnd from 'lodash/trimEnd';

/**
* Exchanges an Authorization Code for an Access Token that you can use to make authenticated requests to
Expand Down Expand Up @@ -61,13 +63,22 @@ export function ensureAuthorization(
redirectUri: string,
options?: CookieOptions,
): string | { redirect: string } | undefined {
const { wpUrl, apiUrl, apiEndpoint } = headlessConfig();
const { wpUrl, apiEndpoint } = headlessConfig();
let { apiUrl } = headlessConfig();
const accessToken = getAccessToken(options);

if (!isString(apiUrl)) {
throw new Error(
'You must provide an apiUrl value in your Headless config in order to use the authorize middleware',
);
if (!!accessToken && accessToken.length > 0) {
return accessToken;
}

if (!isString(apiUrl) || isEmpty(apiUrl)) {
if (!isServerSide()) {
apiUrl = trimEnd(window.location.origin, '/');
} else {
throw new Error(
'You must provide an apiUrl value in your Headless config in order to use the authorize middleware',
);
}
}

if (!isString(apiEndpoint)) {
Expand All @@ -76,10 +87,6 @@ export function ensureAuthorization(
);
}

if (!!accessToken && accessToken.length > 0) {
return accessToken;
}

const parsedUrl = parseUrl(redirectUri);

if (!parsedUrl) {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ let configSet = false;
export function normalizeConfig(config: HeadlessConfig): HeadlessConfig {
const cfg = defaults({}, config, {
blogUrlPrefix: '',
apiUrl: config.wpUrl,
apiUrl: '',
apiEndpoint: '/api/auth/wpe-headless',
});

Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/utils/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ export function parseUrl(url: string | undefined): ParsedUrlInfo | undefined {

const parsed = URL_REGEX.exec(url);

if (!isArrayLike(parsed) || isEmpty(parsed) || isUndefined(parsed[4])) {
if (
!isArrayLike(parsed) ||
isEmpty(parsed) ||
(isUndefined(parsed[4]) && url[0] !== '/')
) {
return;
}

Expand Down
101 changes: 68 additions & 33 deletions packages/next/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
CreateReactClientOptions,
ReactClient,
} from '@gqless/react';
import type { LoggerOptions } from '@gqless/logger';
// import type { LoggerOptions } from '@gqless/logger';
import { useRouter } from 'next/router';
import isObject from 'lodash/isObject';
import merge from 'lodash/merge';
Expand All @@ -13,19 +13,21 @@ import {
GeneratedSchema,
PostIdType,
PageIdType,
ensureAuthorization,
} from '@wpengine/headless-core';
// import defaults from 'lodash/defaults';
import { useEffect } from 'react';
import isString from 'lodash/isString';
import {
hasCategoryId,
hasCategorySlug,
HasObject,
hasPageId,
hasPageUri,
hasPagePreviewUri,
hasPostId,
hasPostSlug,
hasPostUri,
hasPostPreviewUri,
} from './utils';
import defaults from 'lodash/defaults';

/* eslint-disable @typescript-eslint/ban-types, @typescript-eslint/explicit-module-boundary-types */
export function client<Schema extends GeneratedSchema = GeneratedSchema>(
Expand Down Expand Up @@ -111,13 +113,6 @@ export function client<Schema extends GeneratedSchema = GeneratedSchema>(
idType: PostIdType.URI,
}) as ReturnType<Schema['query']['post']>;
}
if (hasPostPreviewUri(query)) {
return post({
id: query.postPreviewUri.join('/'),
idType: PostIdType.URI,
asPreview: true,
}) as ReturnType<Schema['query']['post']>;
}
}

return post(args as Parameters<Schema['query']['post']>[0]) as ReturnType<
Expand Down Expand Up @@ -150,20 +145,59 @@ export function client<Schema extends GeneratedSchema = GeneratedSchema>(
idType: PageIdType.URI,
}) as ReturnType<Schema['query']['page']>;
}
if (hasPagePreviewUri(query)) {
return page({
id: query.pagePreviewUri.join('/'),
idType: PageIdType.URI,
asPreview: true,
}) as ReturnType<Schema['query']['page']>;
}
}

return page(args as Parameters<Schema['query']['page']>[0]) as ReturnType<
Schema['query']['page']
>;
}

/* eslint-disable consistent-return */

function usePreview(
args: Record<'pageId', string>,
): ReturnType<Schema['query']['page']>;
function usePreview(
args: Record<'postId', string>,
): ReturnType<Schema['query']['post']>;
function usePreview(
args: HasObject,
): ReturnType<Schema['query']['page'] | Schema['query']['post']> | undefined {
useEffect(() => {
if (typeof window === 'undefined') {
return;
}

const authResult = ensureAuthorization(window.location.href);

if (!isString(authResult) && isString(authResult?.redirect)) {
setTimeout(() => {
window.location.replace(authResult?.redirect as string);
}, 200);
}
}, []);

const { post, page } = useQuery();

const pagePreview = page({
id: (args?.pageId as string) ?? '',
idType: PageIdType.DATABASE_ID,
}) as ReturnType<Schema['query']['page']>;

const postPreview = post({
id: (args?.postId as string) ?? '',
idType: PostIdType.DATABASE_ID,
}) as ReturnType<Schema['query']['post']>;

if (hasPageId(args)) {
return pagePreview;
}
if (hasPostId(args)) {
return postPreview;
}
}
/* eslint-enable consistent-return */

function useCategory(
args?: Parameters<Schema['query']['category']>[0],
): ReturnType<Schema['query']['category']> {
Expand Down Expand Up @@ -204,22 +238,23 @@ export function client<Schema extends GeneratedSchema = GeneratedSchema>(
usePost,
usePages,
usePage,
usePreview,
useGeneralSettings,
};
}

export async function logQueries(options?: LoggerOptions): Promise<() => void> {
try {
const { createLogger } = await import('@gqless/logger');
const logger = createLogger(
client().client,
defaults({}, options, {
showSelections: false,
showCache: false,
} as LoggerOptions),
);
return logger.start();
} catch (e) {
return () => {};
}
}
// export async function logQueries(options?: LoggerOptions): Promise<() => void> {
// try {
// const { createLogger } = await import('@gqless/logger');
// const logger = createLogger(
// client().client,
// defaults({}, options, {
// showSelections: false,
// showCache: false,
// } as LoggerOptions),
// );
// return logger.start();
// } catch (e) {
// return () => {};
// }
// }
Loading

0 comments on commit 3ec213c

Please sign in to comment.