Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/baguette.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/beef-burger.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/beef-dinner.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/broth-soup.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/cake.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/car-cake.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/car-muffin.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/carrot-cake.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/chips.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/cod.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/fish-burger.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/fish-n-chips.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/fried-egg.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/fried-sausages.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/homemade-fries.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/lasagna.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/masala.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/oatmeal-muffin.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/orange-cake.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/pancakes.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/peanut-soup.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/peppered-eggs.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/plain-rice.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/potato-boats.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/raw-egg.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/salmon.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/sausage.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/shells.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/shrimp-salad.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/tiki-masala.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/tomato-soup.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/api/src/db/seed-images/vanilla-cake.webp
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
230 changes: 202 additions & 28 deletions apps/api/src/db/seedData.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,231 @@
// Explicit opt-in demo data; never run automatically during deploy.

import { hash } from 'argon2';
import { createHash } from 'node:crypto';
import { copyFile, mkdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { Pool } from 'pg';

// Explicit opt-in demo data; never run automatically during deploy.
const authorId = '11111111-1111-4111-8111-111111111111';
import { seedRecipes } from './seedRecipes.js';

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

const IMAGE_SOURCE_DIR = fileURLToPath(
new URL('./seed-images/', import.meta.url),
);

const DEFAULT_UPLOAD_DIR = fileURLToPath(
new URL('../../../../uploads/', import.meta.url),
);

const MAX_IMAGE_BYTES = 10 * 1024 * 1024;

function stableUuid(value: string): string {
const hex = createHash('sha256').update(`t31-demo-v1:${value}`).digest('hex');

return [
hex.slice(0, 8),
hex.slice(8, 12),
`4${hex.slice(13, 16)}`,
`a${hex.slice(17, 20)}`,
hex.slice(20, 32),
].join('-');
}

function imageFilename(slug: string): string {
const safeName = slug
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');

return `${safeName}.webp`;
}

export async function seedDatabase(
pool: Pool,
password: string | undefined,
schema = 'project2',
uploadDir = process.env.UPLOAD_DIR ?? DEFAULT_UPLOAD_DIR,
) {
if (!/^[a-z_][a-z0-9_]*$/.test(schema))
if (!/^[a-z_][a-z0-9_]*$/.test(schema)) {
throw new Error('Invalid database schema.');
}

if (!password || password.length < 12) {
throw new Error(
'Set SEED_PASSWORD (at least 12 characters) before running db:seed.',
);
throw new Error('Set SEED_PASSWORD to at least 12 characters.');
}
const prepared = await Promise.all(
seedRecipes.map(async (recipe) => {
const sourcePath = join(IMAGE_SOURCE_DIR, imageFilename(recipe.slug));

const image = await readFile(sourcePath).catch(() => {
throw new Error(`Missing image: ${sourcePath}`);
});

if (image.length === 0 || image.length > MAX_IMAGE_BYTES) {
throw new Error(`Invalid image size: ${sourcePath}`);
}

if (
image.toString('ascii', 0, 4) !== 'RIFF' ||
image.toString('ascii', 8, 12) !== 'WEBP'
) {
throw new Error(`Expected a WebP image: ${sourcePath}`);
}

const filename = `${stableUuid(`image:${recipe.slug}`)}.webp`;

return {
recipe,
recipeId: stableUuid(`recipe:${recipe.slug}`),
sourcePath,
filename,
imageUrl: `/uploads/${filename}`,
byteSize: image.length,
};
}),
);

await mkdir(uploadDir, { recursive: true });

const passwordHash = await hash(password);
const client = await pool.connect();

try {
await client.query('BEGIN');

await client.query(
`INSERT INTO ${schema}.users (id,name,email,password_hash)
VALUES ($1,'Demo Cook','demo@example.invalid',$2) ON CONFLICT (id) DO NOTHING`,
[authorId, passwordHash],
`INSERT INTO ${schema}.users
(id, name, email, password_hash)
VALUES ($1, $2, $3, $4)
ON CONFLICT (id) DO NOTHING`,
[AUTHOR_ID, 'Demo Cook', 'demo@example.invalid', passwordHash],
);
for (const [id, title, visibility] of [
['22222222-2222-4222-8222-222222222222', 'Demo vegetable soup', 'public'],
['33333333-3333-4333-8333-333333333333', 'Demo private soup', 'private'],
]) {
const inserted = await client.query(
`INSERT INTO ${schema}.recipes
(id,author_id,title,description,category,difficulty,visibility,prep_minutes,cook_minutes,servings)
VALUES ($1,$2,$3,'Simple demonstration recipe','soup','easy',$4,5,15,2)
ON CONFLICT (id) DO NOTHING RETURNING id`,
[id, authorId, title, visibility],

for (const item of prepared) {
const { recipe } = item;

const destination = join(uploadDir, item.filename);

await copyFile(item.sourcePath, destination);

await client.query(
`INSERT INTO ${schema}.uploaded_images
(filename, owner_id, byte_size)
VALUES ($1, $2, $3)
ON CONFLICT (filename)
DO UPDATE SET
byte_size = EXCLUDED.byte_size`,
[item.filename, AUTHOR_ID, item.byteSize],
);
if (!inserted.rowCount) continue;

await client.query(
`INSERT INTO ${schema}.recipe_ingredients (recipe_id,name,amount,unit,position)
VALUES ($1,'Water',500,'ml',1),($1,'Carrots',2,'',2)`,
[id],
`INSERT INTO ${schema}.recipes (
id,
author_id,
title,
description,
image_url,
category,
cuisine,
difficulty,
visibility,
prep_minutes,
cook_minutes,
servings
)
VALUES (
$1, $2, $3, $4, $5, $6,
$7, $8, $9, $10, $11, $12
)
ON CONFLICT (id)
DO UPDATE SET
title = EXCLUDED.title,
description = EXCLUDED.description,
image_url = EXCLUDED.image_url,
category = EXCLUDED.category,
cuisine = EXCLUDED.cuisine,
difficulty = EXCLUDED.difficulty,
visibility = EXCLUDED.visibility,
prep_minutes = EXCLUDED.prep_minutes,
cook_minutes = EXCLUDED.cook_minutes,
servings = EXCLUDED.servings,
updated_at = now()`,
[
item.recipeId,
AUTHOR_ID,
recipe.title,
recipe.description,
item.imageUrl,
recipe.category,
recipe.cuisine,
recipe.difficulty,
recipe.visibility,
recipe.prepMinutes,
recipe.cookMinutes,
recipe.servings,
],
);

await client.query(
`INSERT INTO ${schema}.recipe_instructions (recipe_id,text,position)
VALUES ($1,'Chop the carrots.',1),($1,'Simmer in water until tender.',2)`,
[id],
`DELETE FROM ${schema}.recipe_ingredients
WHERE recipe_id = $1`,
[item.recipeId],
);

await client.query(
`INSERT INTO ${schema}.recipe_tags (recipe_id,tag) VALUES ($1,'demo')`,
[id],
`DELETE FROM ${schema}.recipe_instructions
WHERE recipe_id = $1`,
[item.recipeId],
);

await client.query(
`DELETE FROM ${schema}.recipe_tags
WHERE recipe_id = $1`,
[item.recipeId],
);

for (const [index, ingredient] of recipe.ingredients.entries()) {
await client.query(
`INSERT INTO ${schema}.recipe_ingredients
(recipe_id, name, amount, unit, position)
VALUES ($1, $2, $3, $4, $5)`,
[
item.recipeId,
ingredient.name,
ingredient.amount,
ingredient.unit,
index + 1,
],
);
}

for (const [index, instruction] of recipe.instructions.entries()) {
await client.query(
`INSERT INTO ${schema}.recipe_instructions
(recipe_id, text, position)
VALUES ($1, $2, $3)`,
[item.recipeId, instruction, index + 1],
);
}

for (const tag of new Set(recipe.tags)) {
await client.query(
`INSERT INTO ${schema}.recipe_tags
(recipe_id, tag)
VALUES ($1, $2)`,
[item.recipeId, tag],
);
}

console.log(`Seeded: ${recipe.title}`);
}

await client.query('COMMIT');

console.log(`Successfully seeded ${prepared.length} recipes.`);
} catch (error) {
await client.query('ROLLBACK');
throw error;
Expand Down
Loading