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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,9 @@ feilkoder, genererte klientoperasjoner og rate limiting bak Apache.

## Database

Se [Recipe API og Delivery 2-status](docs/recipe-api.md) for CRUD-kontrakter,
Bearer-autentisering, Zod-validering, seed og API-integrasjonstester.

Se [databasemodellen](docs/database-model.md) for tabeller, ER-diagram, regler, migrasjon og tester. Modellen utvider autentiseringen og er klar for CRUD i neste steg.

## Nyttige kommandoer
Expand Down
10 changes: 10 additions & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import type { Pool } from 'pg';
import { db } from './db/client.js';
import { createRecipeRepository } from './features/recipes/recipeRepository.js';
import { createRecipeResolvers } from './features/recipes/recipeResolvers.js';
import { readFileSync } from 'node:fs';
import { createSchema, createYoga } from 'graphql-yoga';

Expand All @@ -19,8 +23,12 @@ export function createApp(
service: AuthService = authService,
trustProxy = process.env.AUTH_TRUST_PROXY === 'true',
secureCookie = process.env.AUTH_COOKIE_SECURE === 'true',
database: { pool?: Pool; schema?: string } = {},
) {
const authResolvers = createAuthResolvers(service);
const recipes = createRecipeResolvers(
createRecipeRepository(database.pool ?? db, database.schema ?? 'project2'),
);
const cookies = new WeakMap<Request, string>();
return createYoga<{ req?: IncomingMessage }, AuthContext>({
cors: false,
Expand Down Expand Up @@ -93,9 +101,11 @@ export function createApp(
Query: {
health: () => 'ok',
...authResolvers.Query,
...recipes.Query,
},
Mutation: {
...authResolvers.Mutation,
...recipes.Mutation,
},
} satisfies Resolvers<AuthContext>,
}),
Expand Down
10 changes: 10 additions & 0 deletions apps/api/src/db/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { db } from './client.js';
import { seedDatabase } from './seedData.js';
try {
await seedDatabase(db, process.env.SEED_PASSWORD);
console.log(
'Demo data ready. Existing seed rows and passwords were not overwritten.',
);
} finally {
await db.end();
}
61 changes: 61 additions & 0 deletions apps/api/src/db/seedData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { hash } from 'argon2';
import type { Pool } from 'pg';

// Explicit opt-in demo data; never run automatically during deploy.
const authorId = '11111111-1111-4111-8111-111111111111';
export async function seedDatabase(
pool: Pool,
password: string | undefined,
schema = 'project2',
) {
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.',
);
}
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],
);
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],
);
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],
);
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],
);
await client.query(
`INSERT INTO ${schema}.recipe_tags (recipe_id,tag) VALUES ($1,'demo')`,
[id],
);
}
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
17 changes: 10 additions & 7 deletions apps/api/src/features/auth/authRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,16 @@ export interface AuthRepository {
export function createAuthRepository(
pool: Pool = db,
executor: Pick<Pool, 'query'> = pool,
schema = 'project2',
): AuthRepository {
if (!/^[a-z_][a-z0-9_]*$/.test(schema))
throw new Error('Invalid database schema.');
return {
async findUserByEmail(email) {
const result = await executor.query<UserRow>(
`
SELECT id, name, email, password_hash
FROM project2.users
FROM ${schema}.users
WHERE email = $1
LIMIT 1
`,
Expand All @@ -86,7 +89,7 @@ export function createAuthRepository(
async createUser(name, email, passwordHash) {
const result = await executor.query<PublicUser>(
`
INSERT INTO project2.users (name, email, password_hash)
INSERT INTO ${schema}.users (name, email, password_hash)
VALUES ($1, $2, $3)
RETURNING id, name, email
`,
Expand All @@ -106,7 +109,7 @@ export function createAuthRepository(
const client = await pool.connect();
try {
await client.query('BEGIN');
const repository = createAuthRepository(pool, client);
const repository = createAuthRepository(pool, client, schema);
const user = await repository.createUser(name, email, passwordHash);
const sessionToken = await repository.createSession(user.id, expiresAt);
await client.query('COMMIT');
Expand Down Expand Up @@ -134,7 +137,7 @@ export function createAuthRepository(
async createSession(userId, expiresAt) {
const result = await executor.query<{ id: string }>(
`
INSERT INTO project2.sessions (user_id, expires_at)
INSERT INTO ${schema}.sessions (user_id, expires_at)
VALUES ($1, $2)
RETURNING id
`,
Expand All @@ -155,8 +158,8 @@ export function createAuthRepository(
const result = await executor.query<SessionUserRow>(
`
SELECT users.id, users.name, users.email
FROM project2.sessions AS sessions
JOIN project2.users AS users
FROM ${schema}.sessions AS sessions
JOIN ${schema}.users AS users
ON users.id = sessions.user_id
WHERE sessions.id = $1
AND sessions.expires_at > now()
Expand All @@ -172,7 +175,7 @@ export function createAuthRepository(
if (!sessionTokenSchema.safeParse(sessionToken).success) return;
await executor.query(
`
DELETE FROM project2.sessions
DELETE FROM ${schema}.sessions
WHERE id = $1
`,
[sessionToken],
Expand Down
217 changes: 217 additions & 0 deletions apps/api/src/features/recipes/recipeRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
import { GraphQLError } from 'graphql';
import type { Pool, PoolClient } from 'pg';
import { db } from '../../db/client.js';
import type { Recipe } from '../../generated.js';
import type { RecipeInput, ListInput } from './recipeValidation.js';

export function createRecipeRepository(pool: Pool = db, schema = 'project2') {
if (!/^[a-z_][a-z0-9_]*$/.test(schema))
throw new Error('Invalid database schema.');
const t = (name: string) => `"${schema}"."${name}"`;
// One read includes ordered children and derived values; no per-recipe queries.
const select = `SELECT r.id, r.title, r.description, r.category, r.cuisine,
r.difficulty, r.visibility, r.image_url AS "imageUrl", r.source_recipe_id AS "sourceRecipeId",
r.prep_minutes AS "prepMinutes", r.cook_minutes AS "cookMinutes", r.servings,
to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "createdAt",
to_char(r.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS "updatedAt",
json_build_object('id',u.id,'name',u.name) AS author,
coalesce(r.author_id = $1::uuid,false) AS "isCreatedByCurrentUser",
EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid) AS "isSaved",
(SELECT count(*)::int FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id) AS "saveCount",
(SELECT json_build_object('average',coalesce(round(avg(score),1),0)::float,'count',count(*)::int) FROM ${t('ratings')} WHERE recipe_id=r.id) AS rating,
coalesce((SELECT json_agg(json_build_object('id',i.id,'name',i.name,'amount',i.amount::float,'unit',i.unit,'note',i.note) ORDER BY i.position) FROM ${t('recipe_ingredients')} i WHERE i.recipe_id=r.id),'[]') AS ingredients,
coalesce((SELECT json_agg(json_build_object('step',i.position,'text',i.text) ORDER BY i.position) FROM ${t('recipe_instructions')} i WHERE i.recipe_id=r.id),'[]') AS instructions,
coalesce((SELECT json_agg(tag ORDER BY tag) FROM ${t('recipe_tags')} WHERE recipe_id=r.id),'[]') AS tags
FROM ${t('recipes')} r JOIN ${t('users')} u ON u.id=r.author_id`;

async function transaction<T>(work: (client: PoolClient) => Promise<T>) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
async function read(
executor: Pick<Pool, 'query'>,
id: string,
userId: string | null,
) {
const result = await executor.query<Recipe>(
select +
` WHERE r.id=$2 AND (r.visibility='public' OR r.author_id=$1::uuid)`,
[userId, id],
);
return result.rows[0] ?? null;
}
async function readRequired(client: PoolClient, id: string, userId: string) {
const recipe = await read(client, id, userId);
if (!recipe) throw new Error('Recipe could not be read after writing.');
return recipe;
}
async function owned(client: PoolClient, id: string, userId: string) {
const result = await client.query(
`SELECT id FROM ${t('recipes')} WHERE id=$1 AND author_id=$2 FOR UPDATE`,
[id, userId],
);
if (!result.rowCount)
throw new GraphQLError('Recipe not found or not owned by you.', {
extensions: { code: 'NOT_FOUND' },
});
}
async function children(client: PoolClient, id: string, input: RecipeInput) {
for (const [index, ingredient] of input.ingredients.entries()) {
await client.query(
`INSERT INTO ${t('recipe_ingredients')} (recipe_id,name,amount,unit,note,position) VALUES ($1,$2,$3,$4,$5,$6)`,
[
id,
ingredient.name,
ingredient.amount,
ingredient.unit,
ingredient.note,
index + 1,
],
);
}
for (const [index, instruction] of input.instructions.entries())
await client.query(
`INSERT INTO ${t('recipe_instructions')} (recipe_id,text,position) VALUES ($1,$2,$3)`,
[id, instruction, index + 1],
);
for (const tag of input.tags)
await client.query(
`INSERT INTO ${t('recipe_tags')} (recipe_id,tag) VALUES ($1,$2)`,
[id, tag],
);
}
const values = (input: RecipeInput) => [
input.title,
input.description,
input.imageUrl,
input.category,
input.cuisine,
input.difficulty,
input.visibility,
input.prepMinutes,
input.cookMinutes,
input.servings,
];
return {
get: (id: string, userId: string | null) => read(pool, id, userId),
async list(
input: ListInput,
userId: string | null,
scope: 'explore' | 'all' | 'saved' | 'created' = 'explore',
) {
const access =
scope === 'explore'
? `r.visibility='public'`
: `(r.visibility='public' OR r.author_id=$1::uuid) AND (` +
(scope === 'created'
? 'r.author_id=$1::uuid'
: scope === 'saved'
? `EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`
: `r.author_id=$1::uuid OR EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`) +
')';
const where = ` WHERE ${access} AND ($2='' OR strpos(lower(r.title || ' ' || r.description),lower($2))>0) AND ($3::text IS NULL OR r.category=$3) AND ($4::int IS NULL OR r.prep_minutes+r.cook_minutes <= $4)`;
const args = [
userId,
input.search,
input.category ?? null,
input.maxCookingMinutes ?? null,
];
// Count and rows share a snapshot, including when another request creates/deletes recipes.
return transaction(async (client) => {
await client.query('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
const count = await client.query<{ total: number }>(
`SELECT count(*)::int AS total, $1::uuid AS "viewerId" FROM ${t('recipes')} r` +
where,
args,
);
const totalCount = count.rows[0]!.total;
const totalPages = Math.ceil(totalCount / input.pageSize);
const page = Math.min(input.page, Math.max(totalPages, 1));
const rows = await client.query(
select +
where +
' ORDER BY r.created_at DESC,r.id DESC LIMIT $5 OFFSET $6',
[...args, input.pageSize, (page - 1) * input.pageSize],
);
return {
items: rows.rows,
totalCount,
totalPages,
page,
pageSize: input.pageSize,
};
});
},
async create(input: RecipeInput, userId: string) {
return transaction(async (client) => {
const result = await client.query<{ id: string }>(
`INSERT INTO ${t('recipes')} (title,description,image_url,category,cuisine,difficulty,visibility,prep_minutes,cook_minutes,servings,author_id) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id`,
[...values(input), userId],
);
const id = result.rows[0]!.id;
await children(client, id, input);
return readRequired(client, id, userId);
});
},
async update(id: string, input: RecipeInput, userId: string) {
return transaction(async (client) => {
await owned(client, id, userId);
await client.query(
`UPDATE ${t('recipes')} SET title=$1,description=$2,image_url=$3,category=$4,cuisine=$5,difficulty=$6,visibility=$7,prep_minutes=$8,cook_minutes=$9,servings=$10 WHERE id=$11`,
[...values(input), id],
);
for (const name of [
'recipe_ingredients',
'recipe_instructions',
'recipe_tags',
])
await client.query(`DELETE FROM ${t(name)} WHERE recipe_id=$1`, [id]);
await children(client, id, input);
return readRequired(client, id, userId);
});
},
async delete(id: string, userId: string) {
return transaction(async (client) => {
await owned(client, id, userId);
await client.query(`DELETE FROM ${t('recipes')} WHERE id=$1`, [id]);
return true;
});
},
async save(id: string, userId: string) {
return transaction(async (client) => {
const result = await client.query(
`SELECT id FROM ${t('recipes')} WHERE id=$1 AND visibility='public' AND author_id<>$2 FOR SHARE`,
[id, userId],
);
if (!result.rowCount)
throw new GraphQLError(
'Only public recipes by other users can be saved.',
{ extensions: { code: 'FORBIDDEN' } },
);
await client.query(
`INSERT INTO ${t('saved_recipes')} (user_id,recipe_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`,
[userId, id],
);
return readRequired(client, id, userId);
});
},
async unsave(id: string, userId: string) {
await pool.query(
`DELETE FROM ${t('saved_recipes')} WHERE user_id=$1 AND recipe_id=$2`,
[userId, id],
);
return true;
},
};
}
export type RecipeRepository = ReturnType<typeof createRecipeRepository>;
Loading