Skip to content

Commit

Permalink
hardcoded routes endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
stefanoverna committed Dec 24, 2024
1 parent 44c1dc2 commit 78b8f06
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/pages/api/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ export function withCORS(responseInit?: ResponseInit): ResponseInit {
}

export function json(response: unknown, init?: ResponseInit): Response {
return new Response(JSON.stringify(response, null, 2), init);
return new Response(JSON.stringify(response, null, 2), {
...init,
headers: { ...init?.headers, 'Content-Type': 'application/json' },
});
}

export function handleUnexpectedError(request: Request, error: unknown) {
Expand Down
48 changes: 48 additions & 0 deletions src/pages/hardcoded-routes.json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { APIRoute } from 'astro';
import { handleUnexpectedError, json } from './api/_utils';
import { buildSitemapUrls as cmaResourceEndpointUrls } from './docs/content-management-api/resources/[entitySlug]/[endpointRel]/_graphql';
import { buildSitemapUrls as cmaResourceUrls } from './docs/content-management-api/resources/[entitySlug]/_graphql';

const allAstroFiles = import.meta.glob<string>('../pages/**/*.astro', {
query: '?raw',
import: 'default',
eager: false,
});

export type BuildSitemapUrlsFn = (ctx: {
request: Request;
responseHeaders: Headers;
}) => Promise<string[]>;

export const fetchHardcodedRoutes = async () => {
let urlsPromises: Array<Promise<string[]>> = [];

for (const astroFilePath of Object.keys(allAstroFiles)) {
if (astroFilePath.includes('_')) {
continue;
}

if (!astroFilePath.includes('[')) {
const url = astroFilePath.replace('./', '/').replace('.astro', '').replace('/index', '');
urlsPromises.push(Promise.resolve([url || '/']));
}
}

return (await Promise.all(urlsPromises)).flat();
};

export const GET: APIRoute = async ({ request }) => {
try {
const responseHeaders = new Headers();

const urls = await Promise.all([
fetchHardcodedRoutes(),
cmaResourceUrls({ request, responseHeaders }),
cmaResourceEndpointUrls({ request, responseHeaders }),
]);

return json(urls.flat(), { headers: responseHeaders });
} catch (error) {
return handleUnexpectedError(request, error);
}
};

0 comments on commit 78b8f06

Please sign in to comment.