Skip to content

Commit

Permalink
move shortlink redirect logic to middlware
Browse files Browse the repository at this point in the history
  • Loading branch information
wesbos committed Oct 23, 2023
1 parent 6708462 commit ff9a0ae
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 19 deletions.
24 changes: 22 additions & 2 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import * as Sentry from '@sentry/sveltekit';
import { sequence } from '@sveltejs/kit/hooks';
import { form_data } from 'sk-form-data';
import { PrismaClient } from '@prisma/client';
import type { Handle } from '@sveltejs/kit';
import { redirect, type Handle } from '@sveltejs/kit';
import { find_user_by_access_token } from './server/auth/users';
import { dev } from '$app/environment';
import get_show_path from '$utilities/slug';

Sentry.init({
dsn: 'https://ea134756b8f244ff99638864ce038567@o4505358925561856.ingest.sentry.io/4505358945419264',
Expand Down Expand Up @@ -56,8 +57,27 @@ export const prisma: Handle = async function ({ event, resolve }) {
return response;
};

export const redirects: Handle = async function ({ event, resolve, ...rest }) {
const { pathname } = event.url;
const path_parts = pathname.split('/');
// Not something we care about
if (path_parts.length > 2) resolve(event);
const maybe_show_number = parseInt(path_parts.at(1) || '');
// Not a number, so not a show, pass it down the middleware chain
if (isNaN(maybe_show_number)) return resolve(event);
// Is there a show with this number?
const show = await prisma_client.show.findFirst({ where: { number: maybe_show_number } });
// No show found, pass it down the middleware chain - will probably 404, but thats sveltekit's job to figure that out, not ours!
if (!show) return resolve(event);
const url = get_show_path(show);
// Redirect to the page for this show
throw redirect(302, url);
};

// * END HOOKS

// Wraps requests in this sequence of hooks
export const handle: Handle = sequence(sequence(Sentry.sentryHandle(), prisma, auth, form_data));
export const handle: Handle = sequence(
sequence(Sentry.sentryHandle(), prisma, auth, form_data, redirects)
);
export const handleError = Sentry.handleErrorWithSentry();
13 changes: 0 additions & 13 deletions src/routes/(site)/[show_number]/+page.server.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,6 @@ export const load: PageServerLoad = async function ({ setHeaders, params, locals
// maybe that's a todo for another day
const with_h3_body = body_string.replace(pattern, replacement);

setHeaders({
'cache-control': 'max-age=240'
});

return {
show: {
...show_raw,
Expand Down

0 comments on commit ff9a0ae

Please sign in to comment.