mirror of
https://github.com/lux-tel/websites.git
synced 2026-10-30 20:31:36 +00:00
39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { validatePreviewUrl } from '@sanity/preview-url-secret';
|
|
import type { SanityClient } from 'next-sanity';
|
|
import { draftMode } from 'next/headers';
|
|
import { type NextRequest, NextResponse } from 'next/server';
|
|
import type { SessionSanityClient } from '../lib/client';
|
|
import logger from '../lib/logger';
|
|
|
|
type CreateEnableDraftHandlerOptions = {
|
|
client: SessionSanityClient;
|
|
draftToken: string;
|
|
};
|
|
|
|
export const createEnableDraftHandler = ({
|
|
draftToken,
|
|
client,
|
|
}: CreateEnableDraftHandlerOptions) => {
|
|
if (!draftToken) {
|
|
throw new TypeError('Missing draftToken');
|
|
}
|
|
|
|
const enableDraftHandler = async (req: NextRequest) => {
|
|
const { isValid, redirectTo = '/' } = await validatePreviewUrl(
|
|
/** This is required to make TS happy about replacing the `fetch` method on the client */
|
|
client as unknown as SanityClient,
|
|
req.url
|
|
);
|
|
|
|
if (!isValid) {
|
|
return new NextResponse('Invalid secret', { status: 401 });
|
|
}
|
|
|
|
(await draftMode()).enable();
|
|
logger.info(`Enabled draft mode for ${req.url}`);
|
|
return NextResponse.redirect(new URL(redirectTo, req.url));
|
|
};
|
|
|
|
return { GET: enableDraftHandler };
|
|
};
|