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
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
74 changes: 74 additions & 0 deletions apps/api/src/features/recipes/recipeContract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { readFileSync } from 'node:fs';
import { buildSchema, graphql, isEnumType, parse, validate } from 'graphql';
import { describe, expect, it } from 'vitest';
import { categorySchema, recipeInputSchema } from './recipeValidation.js';

const schema = buildSchema(
readFileSync(new URL('../../schema.graphql', import.meta.url), 'utf8'),
);

describe('recipe GraphQL contract', () => {
it('keeps enum values consistent with input validation', () => {
const values = (name: string) => {
const type = schema.getType(name);
if (!isEnumType(type)) throw new Error(`${name} must be an enum`);
return type.getValues().map((value) => value.name);
};
expect(values('RecipeCategory')).toEqual(categorySchema.options);
expect(values('RecipeDifficulty')).toEqual(
recipeInputSchema.shape.difficulty.options,
);
expect(values('RecipeVisibility')).toEqual(
recipeInputSchema.shape.visibility.options,
);
expect(values('CookbookScope')).toEqual(['all', 'saved', 'created']);
});

it('accepts all shared operations against the schema', () => {
const operations = readFileSync(
new URL('../../../../../contracts/operations.graphql', import.meta.url),
'utf8',
);
expect(validate(schema, parse(operations))).toEqual([]);
});

it.each([
['RecipeCategory', 'Soup'],
['RecipeDifficulty', 'expert'],
['RecipeVisibility', 'hidden'],
['CookbookScope', 'everyone'],
])('rejects invalid %s variables before resolving', async (type, value) => {
const field = type === 'CookbookScope' ? 'cookbook' : 'recipes';
const argument =
type === 'CookbookScope'
? 'scope: $value'
: type === 'RecipeCategory'
? 'input: { category: $value }'
: '';
// Difficulty/visibility are mutation inputs; use their real input fields.
const source = argument
? `query($value: ${type}) { ${field}(${argument}) { totalCount } }`
: `mutation($value: ${type}!) {
createRecipe(input: {
title: "Soup", description: "", category: soup,
difficulty: ${type === 'RecipeDifficulty' ? '$value' : 'easy'},
visibility: ${type === 'RecipeVisibility' ? '$value' : 'public'},
prepMinutes: 0, cookMinutes: 10, servings: 1,
ingredients: [], instructions: [], tags: []
}) { id }
}`;
let resolved = false;
const result = await graphql({
schema,
source,
variableValues: { value },
rootValue: {
[argument ? field : 'createRecipe']: () => {
resolved = true;
},
},
});
expect(result.errors?.[0]?.message).toContain('does not exist');
expect(resolved).toBe(false);
});
});
Loading