Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 14 additions & 0 deletions apps/api/src/db/demoAccounts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
* E-mail addresses of the accounts created by the demo seed (seedData.ts).
* They use the reserved .invalid domain, and registration refuses them, so
* a real user can never take an address the seed relies on.
*/
export const DEMO_COOK_EMAIL = 'demo@example.invalid';

export function demoTasterEmail(taster: number) {
return `demo-taster-${taster}@example.invalid`;
}

export function isReservedDemoEmail(email: string) {
return /^demo(-taster-\d+)?@example\.invalid$/i.test(email.trim());
}
59 changes: 58 additions & 1 deletion apps/api/src/db/seedData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ import { fileURLToPath } from 'node:url';
import type { Pool } from 'pg';

import { seedRecipes } from './seedRecipes.js';
import { DEMO_COOK_EMAIL, demoTasterEmail } from './demoAccounts.js';

const AUTHOR_ID = '11111111-1111-4111-8111-111111111111';

// Extra demo accounts that rate the public demo recipes (see seedRatings).
const TASTER_COUNT = 4;
const RATING_SCORES = [3, 4, 4, 5, 5] as const;

const IMAGE_SOURCE_DIR = fileURLToPath(
new URL('./seed-images/', import.meta.url),
);
Expand Down Expand Up @@ -101,7 +106,7 @@ export async function seedDatabase(
(id, name, email, password_hash)
VALUES ($1, $2, $3, $4)
ON CONFLICT (id) DO NOTHING`,
[AUTHOR_ID, 'Demo Cook', 'demo@example.invalid', passwordHash],
[AUTHOR_ID, 'Demo Cook', DEMO_COOK_EMAIL, passwordHash],
);

for (const item of prepared) {
Expand Down Expand Up @@ -223,9 +228,61 @@ export async function seedDatabase(
console.log(`Seeded: ${recipe.title}`);
}

/*
* Demo ratings, so "Highest rated" has data to sort. Four taster
* accounts (sharing SEED_PASSWORD) rate about 80 % of the public
* recipes with 3–5 stars. Scores come from a hash of recipe and taster,
* so every run produces the same data. Existing users and ratings are
* kept, as for the rest of the seed. Private recipes are not rated, as
* the API also forbids it.
*/
let ratingCount = 0;
for (let taster = 1; taster <= TASTER_COUNT; taster += 1) {
const tasterId = stableUuid(`taster:${taster}`);
const email = demoTasterEmail(taster);
await client.query(
`INSERT INTO ${schema}.users (id, name, email, password_hash)
VALUES ($1, $2, $3, $4)
ON CONFLICT DO NOTHING`,
[tasterId, `Demo Taster ${taster}`, email, passwordHash],
);
// If another account already uses the address (e.g. registered before
// it was reserved), the insert was skipped. Rating with tasterId would
// then break a foreign key and roll back the whole seed, so skip it.
const owner = await client.query<{ id: string }>(
`SELECT id FROM ${schema}.users WHERE email = $1`,
[email],
);
if (owner.rows[0]?.id !== tasterId) {
console.warn(
`Skipping demo ratings from ${email}: the address belongs to another account.`,
);
continue;
}
for (const item of prepared) {
if (item.recipe.visibility !== 'public') continue;
const hash = createHash('sha256')
.update(`rating:${item.recipe.slug}:${taster}`)
.digest();
if (hash[0]! % 5 === 0) continue; // About one in five is left unrated.
const result = await client.query(
`INSERT INTO ${schema}.ratings (recipe_id, user_id, score)
VALUES ($1, $2, $3)
ON CONFLICT DO NOTHING`,
[
item.recipeId,
tasterId,
RATING_SCORES[hash[1]! % RATING_SCORES.length],
],
);
ratingCount += result.rowCount ?? 0;
}
}

await client.query('COMMIT');

console.log(`Successfully seeded ${prepared.length} recipes.`);
console.log(`Added ${ratingCount} demo ratings.`);
} catch (error) {
await client.query('ROLLBACK');
throw error;
Expand Down
108 changes: 102 additions & 6 deletions apps/api/src/db/seedRecipes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,17 +574,112 @@ const recipes: Record<string, RawRecipe> = {

const PRIVATE_RECIPES = new Set(['raw-egg', 'car-muffin']);

const DESCRIPTION_OVERRIDES: Record<string, string> = {
/*
* Hand-written card descriptions, one per recipe (max 200 characters, the
* same limit the API enforces). Seeding fails if a recipe has none, so new
* demo recipes cannot fall back to generated filler text.
*/
const DESCRIPTIONS: Record<string, string> = {
lasagna:
'A comforting Italian-style lasagna layered with rich beef tomato sauce, pasta sheets, creamy béchamel and melted mozzarella.',
'norsk-matpakke':
'A traditional Norwegian packed lunch with wholegrain bread, cheese and fresh toppings. Simple, practical and perfect for work or school.',
'fish-burger':
'Breaded white fish fried until crisp, served in a toasted bun with lettuce and a quick lemon mayonnaise.',
'beef-burger':
'A juicy beef patty with melted cheddar, crisp lettuce and tomato in a soft bun. Ready in half an hour.',
'potato-boats':
'Baked potatoes scooped out, mashed with butter and cheddar, refilled and baked until golden. Served with sour cream.',
'baked-potatoes':
'Crisp-skinned oven potatoes with a fluffy inside. Serve with butter and sea salt, or as a side for fish and meat.',
shells:
'Pasta shells in a creamy garlic and Parmesan sauce. A quick weeknight dinner made with pantry staples.',
salmon:
'Salmon fillets brushed with lemon, dill and garlic, then baked. Light, quick and good with potatoes or vegetables.',
cod: 'Tender cod baked in butter with lemon and parsley. A simple Nordic dinner that is ready in under 30 minutes.',
'fried-chicken':
'Chicken thighs marinated in buttermilk, coated in paprika-spiced flour and fried until golden and crunchy.',
'beef-dinner':
'Pan-seared beef steaks with buttery potatoes and green beans. A classic plate for a slightly special evening.',
sausage:
'Sausages roasted on one tray with sweet bell peppers and red onion. Few dishes to wash and lots of flavour.',
'fried-sausages':
'Sausages fried with slowly softened onions in butter. A hearty breakfast or a quick lunch.',
'fish-n-chips':
'Cod in a light, crisp batter made with sparkling water, served with thick-cut chips. A British favourite at home.',
masala:
'A mild vegetable curry with chickpeas, tomatoes and coconut milk, warmed by garam masala and fresh ginger.',
'tiki-masala':
'Yogurt-marinated chicken simmered in a creamy, spiced tomato sauce. Serve with rice or naan.',
'roasted-chicken':
'A whole chicken roasted with herb butter, lemon and garlic until the skin is golden. Great for Sunday dinner.',
'indian-dish-with-rice':
'Chickpeas simmered in a spiced tomato and onion sauce, served over fluffy basmati rice. Vegetarian and filling.',
'yellow-rice-with-chikcen':
'Chicken and rice cooked together in one pot with turmeric and broth, giving every grain a warm golden colour.',
'peanut-soup':
'A rich soup of sweet potato, peanut butter and tomato, inspired by West African groundnut stews.',
'tomato-soup':
'Ripe tomatoes, onion and garlic simmered and blended into a smooth, creamy soup. Perfect with grilled cheese.',
'sweet-potato-soup':
'Sweet potatoes blended with onion, garlic and broth into a velvety, naturally sweet soup.',
'broth-soup':
'A clear vegetable broth with carrots, celery and egg noodles. Light, warming and easy on the stomach.',
pancakes:
'Thin Norwegian pancakes (pannekaker) made from a simple batter of flour, milk and eggs. Serve with jam or sugar.',
'american-pancakes':
'Thick, fluffy pancakes raised with baking powder. Stack them high and finish with syrup or berries.',
'slovenian-pancakes':
'Slovenian palačinke: thin crêpe-like pancakes rolled around jam. A favourite breakfast or dessert.',
'peppered-eggs':
'Softly scrambled eggs cooked slowly in butter with a splash of milk and plenty of black pepper.',
'fried-egg':
'Eggs fried gently in butter until the whites set and the yolks stay runny. Breakfast in ten minutes.',
'english-breakfast':
'Eggs, sausages, baked beans, mushrooms and toast on one plate. A full English breakfast for a slow morning.',
'raw-egg':
'Eggs simmered for 8–10 minutes for firm yolks, then cooled in cold water so they peel easily.',
'roasted-coffee-beans':
'A freshly brewed cup of filter coffee made from aromatic roasted coffee beans.',
'shrimp-salad':
'Cooked shrimp with avocado, cucumber and mixed lettuce, tossed in a light dressing. Fresh and quick.',
'homemade-fries':
'Potato sticks seasoned with paprika and garlic and baked until crisp, using far less oil than deep frying.',
'grilled-cheese':
'Sourdough fried in butter around melted cheddar with a thin layer of Dijon mustard. Crisp outside, gooey inside.',
'norsk-matpakke':
'A traditional Norwegian packed lunch with wholegrain bread, cheese and fresh toppings. Simple, practical and perfect for work or school.',
baguette:
'A fresh baguette filled with ham, cheddar and crisp lettuce. A quick lunch to make in ten minutes.',
chips:
'Thinly sliced potatoes baked with olive oil, sea salt and paprika until golden and crunchy.',
'plain-rice':
'Fluffy long-grain rice cooked by the absorption method, so the grains stay separate every time.',
cake: 'A classic vanilla sponge for birthdays and celebrations, ready to decorate however you like.',
'carrot-cake':
'A moist carrot cake spiced with cinnamon and topped with a smooth cream cheese frosting.',
'orange-cake':
'A soft, buttery sponge cake flavoured with the zest and juice of fresh oranges.',
'vanilla-cake':
'A simple, fluffy vanilla sponge. Good on its own with coffee or as the base for a layered cake.',
'car-cake':
'A colorful homemade birthday cake decorated in the shape of a car.',
'car-wheels-cake':
'A chocolate celebration cake with playful wheel-shaped decorations.',
'oatmeal-muffin':
'Wholesome muffins with rolled oats, lightly sweetened with honey, so they work for breakfast too.',
'chocolate-muffin':
'Rich cocoa muffins with chocolate chips folded into the batter. Soft, moist and quick to make.',
'bringebær-muffins':
'Light muffins packed with fresh raspberries (bringebær). Best eaten warm on the day they are baked.',
'colored-cupcakes':
'Vanilla cupcakes topped with swirls of brightly coloured frosting. Made for parties and birthdays.',
'car-muffin':
'Vanilla birthday muffins piped with buttercream icing and decorated as little cars.',
'white-cookies':
'Simple vanilla sugar cookies, rolled and cut into shapes. Decorate them with icing or enjoy them plain.',
'gingerbread-cookies':
'Traditional Nordic gingerbread (pepperkaker) spiced with ginger and cinnamon and sweetened with golden syrup.',
'chocolate-cookies':
'Soft and chewy cookies with brown sugar and plenty of chocolate chips. Ready in under 30 minutes.',
};

function parseIngredients(
Expand Down Expand Up @@ -634,12 +729,13 @@ export const seedRecipes: DemoRecipe[] = Object.entries(recipes).map(
? 'private'
: 'public';

const description = DESCRIPTIONS[slug];
if (!description) throw new Error(`Missing seed description: ${slug}`);

return {
slug,
title,
description:
DESCRIPTION_OVERRIDES[slug] ??
`A homemade ${title.toLowerCase()} recipe featuring flavorful ingredients and straightforward preparation. Suitable for ${category} and inspired by ${cuisine.toLowerCase()} cooking.`,
description,
category,
cuisine,
difficulty,
Expand Down
14 changes: 14 additions & 0 deletions apps/api/src/features/auth/authService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,20 @@ describe('authService', () => {
expect(repository.createSession).not.toHaveBeenCalled();
});

it('reserves the demo seed addresses', async () => {
const repository = createRepository();
const service = createAuthService(repository, createPasswordHasher());

for (const email of [
'demo@example.invalid',
'Demo-Taster-3@example.invalid',
])
await expect(
service.register('Hasan', email, 'secret123'),
).rejects.toThrow('An account with this email already exists.');
expect(repository.createUserWithSession).not.toHaveBeenCalled();
});

it('logs in with the correct password', async () => {
const repository = createRepository({
findUserByEmail: vi.fn(async () => storedUser),
Expand Down
4 changes: 3 additions & 1 deletion apps/api/src/features/auth/authService.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { isReservedDemoEmail } from '../../db/demoAccounts.js';
import {
loginSchema,
registerSchema,
Expand Down Expand Up @@ -54,7 +55,8 @@ export function createAuthService(

const existingUser = await repository.findUserByEmail(normalizedEmail);

if (existingUser) {
// Demo seed addresses are reserved even before the seed has run.
if (existingUser || isReservedDemoEmail(normalizedEmail)) {
throw new GraphQLError('An account with this email already exists.', {
extensions: { code: 'EMAIL_TAKEN' },
});
Expand Down
58 changes: 58 additions & 0 deletions scripts/test-recipe-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -823,7 +823,25 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
await t.test(
'demo seed is repeatable and preserves existing passwords',
async () => {
// Someone already holds one taster address (e.g. registered before it
// was reserved): the seed must still succeed, skipping that taster.
await pool.query(
`INSERT INTO "${schema}".users (name, email, password_hash) VALUES ('Squatter', 'demo-taster-2@example.invalid', 'x')`,
);
await seedDatabase(pool, 'demo-test-password', schema, imageDirectory);
assert.equal(
(
await pool.query(
`SELECT count(*)::int AS n FROM "${schema}".ratings x JOIN "${schema}".users u ON u.id = x.user_id WHERE u.email = 'demo-taster-2@example.invalid'`,
)
).rows[0].n,
0,
);
// Re-seeding must update descriptions already in the database.
await pool.query(
`UPDATE "${schema}".recipes SET description = 'Old generated text' WHERE author_id = $1`,
['11111111-1111-4111-8111-111111111111'],
);

const originalHash = (
await pool.query(
Expand Down Expand Up @@ -856,13 +874,15 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {

const seeded = await pool.query<{
title: string;
description: string;
visibility: string;
image_url: string;
ingredient_count: number;
instruction_count: number;
}>(
`SELECT
r.title,
r.description,
r.visibility,
r.image_url,
(
Expand Down Expand Up @@ -910,7 +930,45 @@ await test('recipe GraphQL API against PostgreSQL', async (t) => {
);

assert.match(seededRecipe.image_url, /^\/uploads\/[a-f0-9-]+\.webp$/);
// The stored description is the hand-written one, also after the
// stale value set above (checks the database, not the seed input).
assert.equal(seededRecipe.description, recipe.description);
assert.doesNotMatch(seededRecipe.description, /^A homemade /);
}

// Demo tasters rate most public recipes and never private ones.
const rated = await pool.query<{
visibility: string;
ratings: number;
min: number | null;
max: number | null;
}>(
`SELECT r.visibility, count(x.score)::int AS ratings,
min(x.score) AS min, max(x.score) AS max
FROM "${schema}".recipes r
LEFT JOIN "${schema}".ratings x ON x.recipe_id = r.id
WHERE r.author_id = $1
GROUP BY r.id, r.visibility`,
['11111111-1111-4111-8111-111111111111'],
);
const publicRows = rated.rows.filter(
(row) => row.visibility === 'public',
);
assert.ok(
publicRows.filter((row) => row.ratings > 0).length >=
publicRows.length * 0.8,
'Most public demo recipes should have ratings.',
);
assert.ok(
rated.rows
.filter((row) => row.visibility === 'private')
.every((row) => row.ratings === 0),
);
assert.ok(
publicRows.every(
(row) => row.ratings === 0 || (row.min! >= 3 && row.max! <= 5),
),
);
},
);
} finally {
Expand Down