mirror of
https://github.com/lux-tel/websites.git
synced 2026-10-30 20:31:36 +00:00
69 lines
2.0 KiB
TypeScript
69 lines
2.0 KiB
TypeScript
import { safeTry, safeTrySync } from '@session/util-js/try';
|
|
import { type NextRequest, NextResponse } from 'next/server';
|
|
import type { SessionSanityClient } from '../lib/client';
|
|
import logger from '../lib/logger';
|
|
import { getSiteSettings } from '../queries/getSiteSettings';
|
|
|
|
type CreateValidateLinkHandlerOptions = {
|
|
draftToken: string;
|
|
client: SessionSanityClient;
|
|
};
|
|
|
|
export const createValidateLinkHandler = ({
|
|
draftToken,
|
|
client,
|
|
}: CreateValidateLinkHandlerOptions) => {
|
|
if (!draftToken) {
|
|
throw new TypeError('Missing draftToken');
|
|
}
|
|
|
|
const validateLinkHandler = async (
|
|
_req: NextRequest,
|
|
{ params: { url } }: { params: { url: string } }
|
|
) => {
|
|
if (!url) {
|
|
return new NextResponse('Missing url', { status: 400 });
|
|
}
|
|
|
|
const [decodingError, decodedURL] = safeTrySync(() => decodeURIComponent(url));
|
|
|
|
if (decodingError) {
|
|
logger.error(decodingError);
|
|
return new NextResponse('URL invalid', { status: 400 });
|
|
}
|
|
|
|
logger.info(`Checking URL: ${decodedURL}`);
|
|
const [error, checkedRes] = await safeTry(fetch(decodedURL));
|
|
|
|
if (error) {
|
|
logger.error(error);
|
|
return new NextResponse(error.message, { status: 404 });
|
|
}
|
|
|
|
if (!checkedRes.ok) {
|
|
return new NextResponse(checkedRes.statusText, { status: checkedRes.status });
|
|
}
|
|
|
|
return new NextResponse('URL valid', { status: 200 });
|
|
};
|
|
|
|
const generateStaticParams = async () => {
|
|
const settings = await getSiteSettings({ client });
|
|
|
|
const links = new Set<string>();
|
|
|
|
for (const link of [...(settings?.headerLinks ?? []), ...(settings?.footerLinks ?? [])]) {
|
|
if (link._type === 'externalLink') links.add(link.url);
|
|
}
|
|
|
|
const linksArray = Array.from(links).filter((link) => !link.startsWith('mailto:'));
|
|
|
|
logger.info(`Generating static params for ${links.size} links`);
|
|
logger.info(linksArray);
|
|
|
|
return linksArray.map((link) => ({ url: encodeURIComponent(link) }));
|
|
};
|
|
|
|
return { GET: validateLinkHandler, generateStaticParams };
|
|
};
|