Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 6 additions & 11 deletions apps/api/src/features/auth/authApp.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
import { print, parse } from 'graphql';
import { createApp } from '../../app.js';
import { createAuthService } from './authService.js';
import type { AuthRepository } from './authRepository.js';
Expand Down Expand Up @@ -44,7 +43,8 @@ function setup(secure = false) {
secure,
);
async function request(
document: Parameters<typeof print>[0],
// A generated operation (typed query string) or raw query text.
document: { toString(): string },
variables: Record<string, unknown> = {},
sentCookie = cookie,
csrf = true,
Expand All @@ -56,7 +56,7 @@ function setup(secure = false) {
...(csrf ? { 'X-Requested-With': 'recipe-platform' } : {}),
...(sentCookie ? { Cookie: sentCookie } : {}),
},
body: JSON.stringify({ query: print(document), variables }),
body: JSON.stringify({ query: document.toString(), variables }),
});
const setCookie = response.headers.get('set-cookie');
if (setCookie) cookie = setCookie.split(';')[0]!;
Expand Down Expand Up @@ -171,18 +171,13 @@ describe('cookie GraphQL authentication', () => {
it('rejects the old token-bearing GraphQL contract', async () => {
const { request } = setup();
expect(
(
await request(
parse('query { currentUser(sessionToken: "old") { id } }'),
)
).errors,
(await request('query { currentUser(sessionToken: "old") { id } }'))
.errors,
).toBeDefined();
expect(
(
await request(
parse(
'mutation { login(email:"a@example.com",password:"x") { sessionToken } }',
),
'mutation { login(email:"a@example.com",password:"x") { sessionToken } }',
)
).errors,
).toBeDefined();
Expand Down
9 changes: 9 additions & 0 deletions apps/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--
Cascade layer priority follows the order layers are first named in the
document. Code-split pages bring their own CSS files, which the build may
link before the main stylesheet; declaring the order here, before any
stylesheet, keeps it fixed. Must match src/styles/layers.css.
-->
<style>
@layer reset, base, components, utilities;
</style>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>Recipe Platform</title>
</head>
Expand Down
1 change: 0 additions & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
},
"dependencies": {
"@t31/validation": "*",
"graphql": "16.12.0",
"react": "19.2.0",
"react-dom": "19.2.0",
"react-easy-crop": "6.2.4",
Expand Down
24 changes: 18 additions & 6 deletions apps/web/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,30 @@
import { useEffect } from 'react';
import { lazy, useEffect } from 'react';
import { useAppStore } from './store';

import { Route, Routes } from 'react-router-dom';

import AppShell from './components/shell/AppShell/AppShell';

import LoginPage from './features/auth/LoginPage';
import RegisterPage from './features/auth/RegisterPage';
import RequireAuth from './features/auth/RequireAuth';

import ExplorePage from './features/explore/ExplorePage';
import CookbookPage from './features/cookbook/CookbookPage';
import RecipeCreatePage from './features/recipes/RecipeCreatePage';
import RecipeDetailPage from './features/recipe-detail/RecipeDetailPage';

/*
* Explore is the landing page and loads with the app. Other pages are split
* into their own chunks and fetched on first visit (AppShell shows a loading
* state meanwhile), so a visitor who only browses never downloads, for
* example, the image cropper used by Add Recipe.
*/
const LoginPage = lazy(() => import('./features/auth/LoginPage'));
const RegisterPage = lazy(() => import('./features/auth/RegisterPage'));
const CookbookPage = lazy(() => import('./features/cookbook/CookbookPage'));
const RecipeCreatePage = lazy(
() => import('./features/recipes/RecipeCreatePage'),
);
const RecipeDetailPage = lazy(
() => import('./features/recipe-detail/RecipeDetailPage'),
);

import NotFoundPage from './features/not-found/NotFoundPage';

export function App() {
Expand Down
7 changes: 6 additions & 1 deletion apps/web/src/components/shell/AppShell/AppShell.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Suspense } from 'react';
import { Outlet } from 'react-router-dom';

import LoadingIndicator from '../../ui/LoadingIndicator/LoadingIndicator';
import SiteHeader from '../SiteHeader/SiteHeader';
import './AppShell.css';

Expand All @@ -8,7 +10,10 @@ function AppShell() {
<div className="app-shell">
<SiteHeader />
<main className="container">
<Outlet />
{/* Lazily loaded pages (App.tsx) suspend here; the header stays. */}
<Suspense fallback={<LoadingIndicator label="Loading page…" />}>
<Outlet />
</Suspense>
</main>
</div>
);
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/features/auth/RequireAuth.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ describe('protected routes with session restoration', () => {
if (register) {
const links = screen.getAllByRole('link', { name: 'Register' });
await interaction.click(links[links.length - 1]!);
// Register is lazy-loaded (code splitting): wait for the page itself.
await screen.findByRole('heading', { name: 'Register' });
await interaction.type(screen.getByLabelText(/^Name/), 'Hasan');
await interaction.type(
screen.getByLabelText(/^Confirm password/),
Expand Down
9 changes: 6 additions & 3 deletions apps/web/src/features/auth/authApi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { ApiError, graphqlRequest as request } from '../../lib/graphqlClient';
import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
import {
ApiError,
graphqlRequest as request,
type GraphqlDocument,
} from '../../lib/graphqlClient';
import {
RegisterDocument,
LoginDocument,
Expand All @@ -16,7 +19,7 @@ const errorMessages: Record<string, string> = {
RATE_LIMITED: 'Too many attempts. Please try again in a minute.',
};
async function graphqlRequest<T, V>(
document: TypedDocumentNode<T, V>,
document: GraphqlDocument<T, V>,
variables: V,
): Promise<T> {
try {
Expand Down
10 changes: 8 additions & 2 deletions apps/web/src/features/recipes/recipeApi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { create } from 'zustand';
import { z } from 'zod';
/*
* Same pattern as Zod's z.uuid(), which the API uses for recipe ids.
* Checked here with a plain regex so Explore does not load Zod (~40 KB
* gzipped) just to reject malformed ids before calling the API.
*/
const UUID_PATTERN =
/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
import {
RecipesDocument,
CookbookDocument,
Expand Down Expand Up @@ -54,7 +60,7 @@ export async function listRecipes(
}

export async function getRecipe(id: string, signal?: AbortSignal) {
if (!z.uuid().safeParse(id).success) return null;
if (!UUID_PATTERN.test(id)) return null;
const { recipe } = await graphqlRequest(RecipeDocument, { id }, signal);
return recipe ? toRecipe(recipe) : null;
}
Expand Down
16 changes: 12 additions & 4 deletions apps/web/src/lib/graphqlClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { print } from 'graphql';
import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
import type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';

/**
* A generated operation from contracts/generated.ts: the query text as a
* string, typed with its result (T) and variables (V). Sending the text
* directly keeps graphql-js out of the browser bundle.
*/
export type GraphqlDocument<T, V> = DocumentTypeDecoration<T, V> & {
toString(): string;
};

const GRAPHQL_URL = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql';

Expand All @@ -13,7 +21,7 @@ export class ApiError extends Error {
}

export async function graphqlRequest<T, V>(
document: TypedDocumentNode<T, V>,
document: GraphqlDocument<T, V>,
variables: V,
signal?: AbortSignal,
): Promise<T> {
Expand All @@ -26,7 +34,7 @@ export async function graphqlRequest<T, V>(
'X-Requested-With': 'recipe-platform',
},
credentials: 'same-origin',
body: JSON.stringify({ query: print(document), variables }),
body: JSON.stringify({ query: document.toString(), variables }),
signal,
});
} catch (error) {
Expand Down
Loading