diff --git a/README.md b/README.md index f197e0d..af57e27 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 3b48a0b..0cff506 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -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'; @@ -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(); return createYoga<{ req?: IncomingMessage }, AuthContext>({ cors: false, @@ -93,9 +101,11 @@ export function createApp( Query: { health: () => 'ok', ...authResolvers.Query, + ...recipes.Query, }, Mutation: { ...authResolvers.Mutation, + ...recipes.Mutation, }, } satisfies Resolvers, }), diff --git a/apps/api/src/db/seed.ts b/apps/api/src/db/seed.ts new file mode 100644 index 0000000..3c58e23 --- /dev/null +++ b/apps/api/src/db/seed.ts @@ -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(); +} diff --git a/apps/api/src/db/seedData.ts b/apps/api/src/db/seedData.ts new file mode 100644 index 0000000..42554bd --- /dev/null +++ b/apps/api/src/db/seedData.ts @@ -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(); + } +} diff --git a/apps/api/src/features/auth/authRepository.ts b/apps/api/src/features/auth/authRepository.ts index 61f1327..18fe834 100644 --- a/apps/api/src/features/auth/authRepository.ts +++ b/apps/api/src/features/auth/authRepository.ts @@ -56,13 +56,16 @@ export interface AuthRepository { export function createAuthRepository( pool: Pool = db, executor: Pick = 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( ` SELECT id, name, email, password_hash - FROM project2.users + FROM ${schema}.users WHERE email = $1 LIMIT 1 `, @@ -86,7 +89,7 @@ export function createAuthRepository( async createUser(name, email, passwordHash) { const result = await executor.query( ` - INSERT INTO project2.users (name, email, password_hash) + INSERT INTO ${schema}.users (name, email, password_hash) VALUES ($1, $2, $3) RETURNING id, name, email `, @@ -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'); @@ -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 `, @@ -155,8 +158,8 @@ export function createAuthRepository( const result = await executor.query( ` 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() @@ -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], diff --git a/apps/api/src/features/recipes/recipeContract.test.ts b/apps/api/src/features/recipes/recipeContract.test.ts new file mode 100644 index 0000000..6d172f0 --- /dev/null +++ b/apps/api/src/features/recipes/recipeContract.test.ts @@ -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); + }); +}); diff --git a/apps/api/src/features/recipes/recipeRepository.ts b/apps/api/src/features/recipes/recipeRepository.ts new file mode 100644 index 0000000..617a052 --- /dev/null +++ b/apps/api/src/features/recipes/recipeRepository.ts @@ -0,0 +1,229 @@ +import { GraphQLError } from 'graphql'; +import type { Pool, PoolClient } from 'pg'; +import { db } from '../../db/client.js'; +import type { CookbookScope, 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}"`; + const ownedByViewer = 'r.author_id=$1::uuid'; + const publicRecipe = "r.visibility='public'"; + const visibleToViewer = `(${publicRecipe} OR ${ownedByViewer})`; + const savedByViewer = `EXISTS(SELECT 1 FROM ${t('saved_recipes')} s WHERE s.recipe_id=r.id AND s.user_id=$1::uuid)`; + + function listAccessCondition(scope: 'explore' | CookbookScope) { + if (scope === 'explore') return publicRecipe; + const membership: Record = { + created: ownedByViewer, + saved: savedByViewer, + all: `(${ownedByViewer} OR ${savedByViewer})`, + }; + return `${visibleToViewer} AND (${membership[scope]})`; + } + + function listFilterConditions() { + // Keep filter parameters separate from access rules; shared by count and rows. + return [ + "($2='' OR strpos(lower(r.title || ' ' || r.description),lower($2))>0)", + '($3::text IS NULL OR r.category=$3)', + '($4::int IS NULL OR r.prep_minutes+r.cook_minutes <= $4)', + ]; + } + // 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(work: (client: PoolClient) => Promise) { + 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, + id: string, + userId: string | null, + ) { + const result = await executor.query( + select + ` WHERE r.id=$2 AND ${visibleToViewer}`, + [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' | CookbookScope = 'explore', + ) { + const where = ` WHERE ${[listAccessCondition(scope), ...listFilterConditions()].join(' AND ')}`; + 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; diff --git a/apps/api/src/features/recipes/recipeResolvers.ts b/apps/api/src/features/recipes/recipeResolvers.ts new file mode 100644 index 0000000..f45e485 --- /dev/null +++ b/apps/api/src/features/recipes/recipeResolvers.ts @@ -0,0 +1,61 @@ +import { GraphQLError } from 'graphql'; +import { z } from 'zod'; +import type { AuthContext as ApiContext } from '../auth/authResolvers.js'; +import type { Resolvers } from '../../generated.js'; +import type { RecipeRepository } from './recipeRepository.js'; +import { + listInputSchema, + recipeId, + recipeInputSchema, + validate, +} from './recipeValidation.js'; + +function requireUser(context: ApiContext) { + if (!context.user) + throw new GraphQLError('Please log in.', { + extensions: { code: 'UNAUTHENTICATED' }, + }); + return context.user.id; +} +export function createRecipeResolvers(repository: RecipeRepository) { + return { + Query: { + recipes: (_parent, args, context) => + repository.list( + validate(listInputSchema, args.input ?? {}), + context.user?.id ?? null, + ), + recipe: (_parent, args, context) => + repository.get(recipeId(args.id), context.user?.id ?? null), + cookbook: (_parent, args, context) => + repository.list( + validate(listInputSchema, args.input ?? {}), + requireUser(context), + validate(z.enum(['all', 'saved', 'created']), args.scope ?? 'all'), + ), + }, + Mutation: { + createRecipe: (_parent, args, context) => { + const userId = requireUser(context); + return repository.create( + validate(recipeInputSchema, args.input), + userId, + ); + }, + updateRecipe: (_parent, args, context) => { + const userId = requireUser(context); + return repository.update( + recipeId(args.id), + validate(recipeInputSchema, args.input), + userId, + ); + }, + deleteRecipe: (_parent, args, context) => + repository.delete(recipeId(args.id), requireUser(context)), + saveRecipe: (_parent, args, context) => + repository.save(recipeId(args.id), requireUser(context)), + unsaveRecipe: (_parent, args, context) => + repository.unsave(recipeId(args.id), requireUser(context)), + }, + } satisfies Pick, 'Query' | 'Mutation'>; +} diff --git a/apps/api/src/features/recipes/recipeValidation.test.ts b/apps/api/src/features/recipes/recipeValidation.test.ts new file mode 100644 index 0000000..9825a7c --- /dev/null +++ b/apps/api/src/features/recipes/recipeValidation.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from 'vitest'; +import { + listInputSchema, + recipeInputSchema, + validate, +} from './recipeValidation.js'; + +const input = { + title: ' Soup ', + description: '', + category: 'soup', + difficulty: 'easy', + visibility: 'private', + prepMinutes: 0, + cookMinutes: 10, + servings: 2, + ingredients: [{ name: ' Salt ', amount: 0.125, unit: '', note: null }], + instructions: [' Stir '], + tags: [' Quick ', 'quick'], +}; +describe('recipe validation', () => { + it('normalizes text and tags while allowing optional cuisine and image', () => { + const result = validate(recipeInputSchema, input); + expect(result.title).toBe('Soup'); + expect(result.cuisine).toBeNull(); + expect(result.imageUrl).toBeNull(); + expect(result.tags).toEqual(['quick']); + expect(result.instructions).toEqual(['Stir']); + }); + it.each([ + { ...input, category: 'Soup' }, + { ...input, servings: 1.5 }, + { ...input, ingredients: [] }, + { ...input, instructions: [' '] }, + { ...input, imageUrl: 'javascript:alert(1)' }, + { ...input, ingredients: [{ name: 'Salt', amount: 0.00001, unit: '' }] }, + { ...input, ingredients: [{ name: 'Salt', amount: Infinity, unit: '' }] }, + ])('rejects input the database or UI cannot represent', (value) => { + expect(() => validate(recipeInputSchema, value)).toThrow(); + }); + it('uses bounded pagination defaults', () => { + expect(validate(listInputSchema, {})).toMatchObject({ + page: 1, + pageSize: 6, + search: '', + }); + expect(() => validate(listInputSchema, { pageSize: 51 })).toThrow(); + }); +}); diff --git a/apps/api/src/features/recipes/recipeValidation.ts b/apps/api/src/features/recipes/recipeValidation.ts new file mode 100644 index 0000000..b98f118 --- /dev/null +++ b/apps/api/src/features/recipes/recipeValidation.ts @@ -0,0 +1,99 @@ +import { GraphQLError } from 'graphql'; +import { z } from 'zod'; + +export const categorySchema = z.enum([ + 'breakfast', + 'lunch', + 'dinner', + 'dessert', + 'soup', +]); +const optionalText = z + .string() + .trim() + .max(200) + .nullish() + .transform((value) => value || null); +export const recipeInputSchema = z.object({ + title: z.string().trim().min(1).max(160), + description: z.string().trim().max(200), + imageUrl: z + .url({ protocol: /^https?$/ }) + .max(2048) + .nullish() + .transform((value) => value ?? null), + category: categorySchema, + cuisine: optionalText, + difficulty: z.enum(['easy', 'medium', 'hard']), + visibility: z.enum(['public', 'private']), + prepMinutes: z.number().int().min(0).max(10080), + cookMinutes: z.number().int().min(0).max(10080), + servings: z.number().int().min(1).max(1000), + ingredients: z + .array( + z.object({ + name: z.string().trim().min(1).max(200), + amount: z + .number() + .positive() + .max(99999999.9999) + .refine( + (value) => Math.round(value * 10000) / 10000 === value, + 'Use at most four decimal places.', + ), + unit: z.string().trim().max(50), + note: optionalText, + }), + ) + .min(1) + .max(100), + instructions: z.array(z.string().trim().min(1).max(5000)).min(1).max(100), + tags: z + .array(z.string().trim().toLowerCase().min(1).max(50)) + .max(30) + .transform((values) => [...new Set(values)]), +}); + +export const listInputSchema = z.object({ + search: z + .string() + .trim() + .max(200) + .nullish() + .transform((value) => value ?? ''), + category: categorySchema.nullish(), + maxCookingMinutes: z.number().int().min(0).max(20160).nullish(), + page: z + .number() + .int() + .min(1) + .max(100000) + .nullish() + .transform((value) => value ?? 1), + pageSize: z + .number() + .int() + .min(1) + .max(50) + .nullish() + .transform((value) => value ?? 6), +}); +export type RecipeInput = z.output; +export type ListInput = z.output; + +export function validate(schema: z.ZodType, input: unknown): T { + const result = schema.safeParse(input); + if (!result.success) { + const issue = result.error.issues[0]!; + throw new GraphQLError( + `${issue.path.join('.') || 'input'}: ${issue.message}`, + { + extensions: { code: 'BAD_USER_INPUT' }, + }, + ); + } + return result.data; +} +export function recipeId(value: unknown) { + return validate(z.uuid(), value); +} diff --git a/apps/api/src/generated.ts b/apps/api/src/generated.ts index ad6d0f0..1e42561 100644 --- a/apps/api/src/generated.ts +++ b/apps/api/src/generated.ts @@ -14,6 +14,19 @@ export type Scalars = { Float: { input: number; output: number }; }; +export type RecipeDifficulty = 'easy' | 'medium' | 'hard'; + +export type RecipeVisibility = 'public' | 'private'; + +export type RecipeCategory = + | 'breakfast' + | 'lunch' + | 'dinner' + | 'dessert' + | 'soup'; + +export type CookbookScope = 'all' | 'saved' | 'created'; + export type User = { __typename?: 'User'; id: Scalars['ID']['output']; @@ -28,17 +41,59 @@ export type AuthPayload = { export type Query = { __typename?: 'Query'; + recipes: RecipePage; + recipe?: Maybe; + cookbook: RecipePage; health: Scalars['String']['output']; currentUser?: Maybe; }; +export type QueryRecipesArgs = { + input?: InputMaybe; +}; + +export type QueryRecipeArgs = { + id: Scalars['ID']['input']; +}; + +export type QueryCookbookArgs = { + input?: InputMaybe; + scope?: InputMaybe; +}; + export type Mutation = { __typename?: 'Mutation'; + createRecipe: Recipe; + updateRecipe: Recipe; + deleteRecipe: Scalars['Boolean']['output']; + saveRecipe: Recipe; + unsaveRecipe: Scalars['Boolean']['output']; register: AuthPayload; login: AuthPayload; signOut: Scalars['Boolean']['output']; }; +export type MutationCreateRecipeArgs = { + input: RecipeInput; +}; + +export type MutationUpdateRecipeArgs = { + id: Scalars['ID']['input']; + input: RecipeInput; +}; + +export type MutationDeleteRecipeArgs = { + id: Scalars['ID']['input']; +}; + +export type MutationSaveRecipeArgs = { + id: Scalars['ID']['input']; +}; + +export type MutationUnsaveRecipeArgs = { + id: Scalars['ID']['input']; +}; + export type MutationRegisterArgs = { name: Scalars['String']['input']; email: Scalars['String']['input']; @@ -50,6 +105,99 @@ export type MutationLoginArgs = { password: Scalars['String']['input']; }; +export type RecipeAuthor = { + __typename?: 'RecipeAuthor'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; +}; + +export type Ingredient = { + __typename?: 'Ingredient'; + id: Scalars['ID']['output']; + name: Scalars['String']['output']; + amount: Scalars['Float']['output']; + unit: Scalars['String']['output']; + note?: Maybe; +}; + +export type Instruction = { + __typename?: 'Instruction'; + step: Scalars['Int']['output']; + text: Scalars['String']['output']; +}; + +export type RatingSummary = { + __typename?: 'RatingSummary'; + average: Scalars['Float']['output']; + count: Scalars['Int']['output']; +}; + +export type Recipe = { + __typename?: 'Recipe'; + id: Scalars['ID']['output']; + title: Scalars['String']['output']; + description: Scalars['String']['output']; + category: RecipeCategory; + cuisine?: Maybe; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl?: Maybe; + sourceRecipeId?: Maybe; + prepMinutes: Scalars['Int']['output']; + cookMinutes: Scalars['Int']['output']; + servings: Scalars['Int']['output']; + createdAt: Scalars['String']['output']; + updatedAt: Scalars['String']['output']; + author: RecipeAuthor; + ingredients: Array; + instructions: Array; + tags: Array; + rating: RatingSummary; + saveCount: Scalars['Int']['output']; + isSaved: Scalars['Boolean']['output']; + isCreatedByCurrentUser: Scalars['Boolean']['output']; +}; + +export type RecipePage = { + __typename?: 'RecipePage'; + items: Array; + totalCount: Scalars['Int']['output']; + totalPages: Scalars['Int']['output']; + page: Scalars['Int']['output']; + pageSize: Scalars['Int']['output']; +}; + +export type RecipeListInput = { + search?: InputMaybe; + category?: InputMaybe; + maxCookingMinutes?: InputMaybe; + page?: InputMaybe; + pageSize?: InputMaybe; +}; + +export type IngredientInput = { + name: Scalars['String']['input']; + amount: Scalars['Float']['input']; + unit: Scalars['String']['input']; + note?: InputMaybe; +}; + +export type RecipeInput = { + title: Scalars['String']['input']; + description: Scalars['String']['input']; + imageUrl?: InputMaybe; + category: RecipeCategory; + cuisine?: InputMaybe; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + prepMinutes: Scalars['Int']['input']; + cookMinutes: Scalars['Int']['input']; + servings: Scalars['Int']['input']; + ingredients: Array; + instructions: Array; + tags: Array; +}; + export type ResolverTypeWrapper = Promise | T; export type ResolverWithResolve = { @@ -169,6 +317,10 @@ export type DirectiveResolverFn< /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { + RecipeDifficulty: RecipeDifficulty; + RecipeVisibility: RecipeVisibility; + RecipeCategory: RecipeCategory; + CookbookScope: CookbookScope; User: ResolverTypeWrapper; ID: ResolverTypeWrapper; String: ResolverTypeWrapper; @@ -176,6 +328,17 @@ export type ResolversTypes = { Query: ResolverTypeWrapper>; Mutation: ResolverTypeWrapper>; Boolean: ResolverTypeWrapper; + RecipeAuthor: ResolverTypeWrapper; + Ingredient: ResolverTypeWrapper; + Float: ResolverTypeWrapper; + Instruction: ResolverTypeWrapper; + Int: ResolverTypeWrapper; + RatingSummary: ResolverTypeWrapper; + Recipe: ResolverTypeWrapper; + RecipePage: ResolverTypeWrapper; + RecipeListInput: RecipeListInput; + IngredientInput: IngredientInput; + RecipeInput: RecipeInput; }; /** Mapping between all available schema types and the resolvers parents */ @@ -187,6 +350,17 @@ export type ResolversParentTypes = { Query: Record; Mutation: Record; Boolean: Scalars['Boolean']['output']; + RecipeAuthor: RecipeAuthor; + Ingredient: Ingredient; + Float: Scalars['Float']['output']; + Instruction: Instruction; + Int: Scalars['Int']['output']; + RatingSummary: RatingSummary; + Recipe: Recipe; + RecipePage: RecipePage; + RecipeListInput: RecipeListInput; + IngredientInput: IngredientInput; + RecipeInput: RecipeInput; }; export type UserResolvers< @@ -212,6 +386,24 @@ export type QueryResolvers< ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query'], > = { + recipes?: Resolver< + ResolversTypes['RecipePage'], + ParentType, + ContextType, + Partial + >; + recipe?: Resolver< + Maybe, + ParentType, + ContextType, + RequireFields + >; + cookbook?: Resolver< + ResolversTypes['RecipePage'], + ParentType, + ContextType, + Partial + >; health?: Resolver; currentUser?: Resolver< Maybe, @@ -225,6 +417,36 @@ export type MutationResolvers< ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation'], > = { + createRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + updateRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + deleteRecipe?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; + saveRecipe?: Resolver< + ResolversTypes['Recipe'], + ParentType, + ContextType, + RequireFields + >; + unsaveRecipe?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType, + RequireFields + >; register?: Resolver< ResolversTypes['AuthPayload'], ParentType, @@ -240,9 +462,123 @@ export type MutationResolvers< signOut?: Resolver; }; +export type RecipeAuthorResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RecipeAuthor'] = ResolversParentTypes['RecipeAuthor'], +> = { + id?: Resolver; + name?: Resolver; +}; + +export type IngredientResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Ingredient'] = ResolversParentTypes['Ingredient'], +> = { + id?: Resolver; + name?: Resolver; + amount?: Resolver; + unit?: Resolver; + note?: Resolver, ParentType, ContextType>; +}; + +export type InstructionResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Instruction'] = ResolversParentTypes['Instruction'], +> = { + step?: Resolver; + text?: Resolver; +}; + +export type RatingSummaryResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RatingSummary'] = ResolversParentTypes['RatingSummary'], +> = { + average?: Resolver; + count?: Resolver; +}; + +export type RecipeResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['Recipe'] = ResolversParentTypes['Recipe'], +> = { + id?: Resolver; + title?: Resolver; + description?: Resolver; + category?: Resolver< + ResolversTypes['RecipeCategory'], + ParentType, + ContextType + >; + cuisine?: Resolver, ParentType, ContextType>; + difficulty?: Resolver< + ResolversTypes['RecipeDifficulty'], + ParentType, + ContextType + >; + visibility?: Resolver< + ResolversTypes['RecipeVisibility'], + ParentType, + ContextType + >; + imageUrl?: Resolver, ParentType, ContextType>; + sourceRecipeId?: Resolver< + Maybe, + ParentType, + ContextType + >; + prepMinutes?: Resolver; + cookMinutes?: Resolver; + servings?: Resolver; + createdAt?: Resolver; + updatedAt?: Resolver; + author?: Resolver; + ingredients?: Resolver< + Array, + ParentType, + ContextType + >; + instructions?: Resolver< + Array, + ParentType, + ContextType + >; + tags?: Resolver, ParentType, ContextType>; + rating?: Resolver; + saveCount?: Resolver; + isSaved?: Resolver; + isCreatedByCurrentUser?: Resolver< + ResolversTypes['Boolean'], + ParentType, + ContextType + >; +}; + +export type RecipePageResolvers< + ContextType = any, + ParentType extends + ResolversParentTypes['RecipePage'] = ResolversParentTypes['RecipePage'], +> = { + items?: Resolver, ParentType, ContextType>; + totalCount?: Resolver; + totalPages?: Resolver; + page?: Resolver; + pageSize?: Resolver; +}; + export type Resolvers = { User?: UserResolvers; AuthPayload?: AuthPayloadResolvers; Query?: QueryResolvers; Mutation?: MutationResolvers; + RecipeAuthor?: RecipeAuthorResolvers; + Ingredient?: IngredientResolvers; + Instruction?: InstructionResolvers; + RatingSummary?: RatingSummaryResolvers; + Recipe?: RecipeResolvers; + RecipePage?: RecipePageResolvers; }; diff --git a/apps/api/src/schema.graphql b/apps/api/src/schema.graphql index 436b41f..8825478 100644 --- a/apps/api/src/schema.graphql +++ b/apps/api/src/schema.graphql @@ -1,3 +1,28 @@ +enum RecipeDifficulty { + easy + medium + hard +} + +enum RecipeVisibility { + public + private +} + +enum RecipeCategory { + breakfast + lunch + dinner + dessert + soup +} + +enum CookbookScope { + all + saved + created +} + type User { id: ID! name: String! @@ -9,12 +34,99 @@ type AuthPayload { } type Query { + recipes(input: RecipeListInput): RecipePage! + recipe(id: ID!): Recipe + cookbook(input: RecipeListInput, scope: CookbookScope): RecipePage! health: String! currentUser: User } type Mutation { + createRecipe(input: RecipeInput!): Recipe! + updateRecipe(id: ID!, input: RecipeInput!): Recipe! + deleteRecipe(id: ID!): Boolean! + saveRecipe(id: ID!): Recipe! + unsaveRecipe(id: ID!): Boolean! register(name: String!, email: String!, password: String!): AuthPayload! login(email: String!, password: String!): AuthPayload! signOut: Boolean! } + +type RecipeAuthor { + id: ID! + name: String! +} +type Ingredient { + id: ID! + name: String! + amount: Float! + unit: String! + note: String +} +type Instruction { + step: Int! + text: String! +} +type RatingSummary { + average: Float! + count: Int! +} +type Recipe { + id: ID! + title: String! + description: String! + category: RecipeCategory! + cuisine: String + difficulty: RecipeDifficulty! + visibility: RecipeVisibility! + imageUrl: String + sourceRecipeId: ID + prepMinutes: Int! + cookMinutes: Int! + servings: Int! + createdAt: String! + updatedAt: String! + author: RecipeAuthor! + ingredients: [Ingredient!]! + instructions: [Instruction!]! + tags: [String!]! + rating: RatingSummary! + saveCount: Int! + isSaved: Boolean! + isCreatedByCurrentUser: Boolean! +} +type RecipePage { + items: [Recipe!]! + totalCount: Int! + totalPages: Int! + page: Int! + pageSize: Int! +} +input RecipeListInput { + search: String + category: RecipeCategory + maxCookingMinutes: Int + page: Int + pageSize: Int +} +input IngredientInput { + name: String! + amount: Float! + unit: String! + note: String +} +input RecipeInput { + title: String! + description: String! + imageUrl: String + category: RecipeCategory! + cuisine: String + difficulty: RecipeDifficulty! + visibility: RecipeVisibility! + prepMinutes: Int! + cookMinutes: Int! + servings: Int! + ingredients: [IngredientInput!]! + instructions: [String!]! + tags: [String!]! +} diff --git a/contracts/generated.ts b/contracts/generated.ts index 18828d8..25c9a17 100644 --- a/contracts/generated.ts +++ b/contracts/generated.ts @@ -8,51 +8,48 @@ export type Incremental = [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never; }; import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; -export type Maybe = T | null; -export type InputMaybe = Maybe; -/** All built-in and custom scalars, mapped to their actual values */ -export type Scalars = { - ID: { input: string; output: string }; - String: { input: string; output: string }; - Boolean: { input: boolean; output: boolean }; - Int: { input: number; output: number }; - Float: { input: number; output: number }; -}; +export type RecipeDifficulty = 'easy' | 'medium' | 'hard'; -export type User = { - __typename?: 'User'; - id: Scalars['ID']['output']; - name: Scalars['String']['output']; - email: Scalars['String']['output']; -}; +export type RecipeVisibility = 'public' | 'private'; -export type AuthPayload = { - __typename?: 'AuthPayload'; - user: User; -}; +export type RecipeCategory = + | 'breakfast' + | 'lunch' + | 'dinner' + | 'dessert' + | 'soup'; -export type Query = { - __typename?: 'Query'; - health: Scalars['String']['output']; - currentUser?: Maybe; -}; +export type CookbookScope = 'all' | 'saved' | 'created'; -export type Mutation = { - __typename?: 'Mutation'; - register: AuthPayload; - login: AuthPayload; - signOut: Scalars['Boolean']['output']; +export type RecipeListInput = { + search?: string | null | undefined; + category?: RecipeCategory | null | undefined; + maxCookingMinutes?: number | null | undefined; + page?: number | null | undefined; + pageSize?: number | null | undefined; }; -export type MutationRegisterArgs = { - name: Scalars['String']['input']; - email: Scalars['String']['input']; - password: Scalars['String']['input']; +export type IngredientInput = { + name: string; + amount: number; + unit: string; + note?: string | null | undefined; }; -export type MutationLoginArgs = { - email: Scalars['String']['input']; - password: Scalars['String']['input']; +export type RecipeInput = { + title: string; + description: string; + imageUrl?: string | null | undefined; + category: RecipeCategory; + cuisine?: string | null | undefined; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + prepMinutes: number; + cookMinutes: number; + servings: number; + ingredients: Array; + instructions: Array; + tags: Array; }; export type HealthQueryVariables = Exact<{ [key: string]: never }>; @@ -88,6 +85,371 @@ export type CurrentUserQuery = { currentUser: { id: string; name: string; email: string } | null; }; +export type RecipeFieldsFragment = { + id: string; + title: string; + description: string; + category: RecipeCategory; + cuisine: string | null; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; +}; + +export type RecipesQueryVariables = Exact<{ + input?: RecipeListInput | null | undefined; +}>; + +export type RecipesQuery = { + recipes: { + totalCount: number; + totalPages: number; + page: number; + pageSize: number; + items: Array<{ + id: string; + title: string; + description: string; + category: RecipeCategory; + cuisine: string | null; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }>; + }; +}; + +export type RecipeQueryVariables = Exact<{ + id: string | number; +}>; + +export type RecipeQuery = { + recipe: { + id: string; + title: string; + description: string; + category: RecipeCategory; + cuisine: string | null; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + } | null; +}; + +export type CookbookQueryVariables = Exact<{ + input?: RecipeListInput | null | undefined; + scope?: CookbookScope | null | undefined; +}>; + +export type CookbookQuery = { + cookbook: { + totalCount: number; + totalPages: number; + page: number; + pageSize: number; + items: Array<{ + id: string; + title: string; + description: string; + category: RecipeCategory; + cuisine: string | null; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }>; + }; +}; + +export type CreateRecipeMutationVariables = Exact<{ + input: RecipeInput; +}>; + +export type CreateRecipeMutation = { + createRecipe: { + id: string; + title: string; + description: string; + category: RecipeCategory; + cuisine: string | null; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }; +}; + +export type UpdateRecipeMutationVariables = Exact<{ + id: string | number; + input: RecipeInput; +}>; + +export type UpdateRecipeMutation = { + updateRecipe: { + id: string; + title: string; + description: string; + category: RecipeCategory; + cuisine: string | null; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }; +}; + +export type DeleteRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +export type DeleteRecipeMutation = { deleteRecipe: boolean }; + +export type SaveRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +export type SaveRecipeMutation = { + saveRecipe: { + id: string; + title: string; + description: string; + category: RecipeCategory; + cuisine: string | null; + difficulty: RecipeDifficulty; + visibility: RecipeVisibility; + imageUrl: string | null; + sourceRecipeId: string | null; + prepMinutes: number; + cookMinutes: number; + servings: number; + createdAt: string; + updatedAt: string; + tags: Array; + saveCount: number; + isSaved: boolean; + isCreatedByCurrentUser: boolean; + author: { id: string; name: string }; + ingredients: Array<{ + id: string; + name: string; + amount: number; + unit: string; + note: string | null; + }>; + instructions: Array<{ step: number; text: string }>; + rating: { average: number; count: number }; + }; +}; + +export type UnsaveRecipeMutationVariables = Exact<{ + id: string | number; +}>; + +export type UnsaveRecipeMutation = { unsaveRecipe: boolean }; + +export const RecipeFieldsFragmentDoc = { + kind: 'Document', + definitions: [ + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; export const HealthDocument = { kind: 'Document', definitions: [ @@ -334,3 +696,946 @@ export const CurrentUserDocument = { }, ], } as unknown as DocumentNode; +export const RecipesDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Recipes' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeListInput' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'recipes' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'items' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'totalCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'totalPages' } }, + { kind: 'Field', name: { kind: 'Name', value: 'page' } }, + { kind: 'Field', name: { kind: 'Name', value: 'pageSize' } }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const RecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Recipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'recipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const CookbookDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'query', + name: { kind: 'Name', value: 'Cookbook' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeListInput' }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'scope' }, + }, + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'CookbookScope' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'cookbook' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'scope' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'scope' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'items' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'totalCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'totalPages' } }, + { kind: 'Field', name: { kind: 'Name', value: 'page' } }, + { kind: 'Field', name: { kind: 'Name', value: 'pageSize' } }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const CreateRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'CreateRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeInput' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'createRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + CreateRecipeMutation, + CreateRecipeMutationVariables +>; +export const UpdateRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'UpdateRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + { + kind: 'VariableDefinition', + variable: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + type: { + kind: 'NonNullType', + type: { + kind: 'NamedType', + name: { kind: 'Name', value: 'RecipeInput' }, + }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'updateRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + { + kind: 'Argument', + name: { kind: 'Name', value: 'input' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'input' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + UpdateRecipeMutation, + UpdateRecipeMutationVariables +>; +export const DeleteRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'DeleteRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'deleteRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + DeleteRecipeMutation, + DeleteRecipeMutationVariables +>; +export const SaveRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'SaveRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'saveRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'FragmentSpread', + name: { kind: 'Name', value: 'RecipeFields' }, + }, + ], + }, + }, + ], + }, + }, + { + kind: 'FragmentDefinition', + name: { kind: 'Name', value: 'RecipeFields' }, + typeCondition: { + kind: 'NamedType', + name: { kind: 'Name', value: 'Recipe' }, + }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'title' } }, + { kind: 'Field', name: { kind: 'Name', value: 'description' } }, + { kind: 'Field', name: { kind: 'Name', value: 'category' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cuisine' } }, + { kind: 'Field', name: { kind: 'Name', value: 'difficulty' } }, + { kind: 'Field', name: { kind: 'Name', value: 'visibility' } }, + { kind: 'Field', name: { kind: 'Name', value: 'imageUrl' } }, + { kind: 'Field', name: { kind: 'Name', value: 'sourceRecipeId' } }, + { kind: 'Field', name: { kind: 'Name', value: 'prepMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'cookMinutes' } }, + { kind: 'Field', name: { kind: 'Name', value: 'servings' } }, + { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } }, + { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'author' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'ingredients' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'id' } }, + { kind: 'Field', name: { kind: 'Name', value: 'name' } }, + { kind: 'Field', name: { kind: 'Name', value: 'amount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'unit' } }, + { kind: 'Field', name: { kind: 'Name', value: 'note' } }, + ], + }, + }, + { + kind: 'Field', + name: { kind: 'Name', value: 'instructions' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'step' } }, + { kind: 'Field', name: { kind: 'Name', value: 'text' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'tags' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'rating' }, + selectionSet: { + kind: 'SelectionSet', + selections: [ + { kind: 'Field', name: { kind: 'Name', value: 'average' } }, + { kind: 'Field', name: { kind: 'Name', value: 'count' } }, + ], + }, + }, + { kind: 'Field', name: { kind: 'Name', value: 'saveCount' } }, + { kind: 'Field', name: { kind: 'Name', value: 'isSaved' } }, + { + kind: 'Field', + name: { kind: 'Name', value: 'isCreatedByCurrentUser' }, + }, + ], + }, + }, + ], +} as unknown as DocumentNode; +export const UnsaveRecipeDocument = { + kind: 'Document', + definitions: [ + { + kind: 'OperationDefinition', + operation: 'mutation', + name: { kind: 'Name', value: 'UnsaveRecipe' }, + variableDefinitions: [ + { + kind: 'VariableDefinition', + variable: { kind: 'Variable', name: { kind: 'Name', value: 'id' } }, + type: { + kind: 'NonNullType', + type: { kind: 'NamedType', name: { kind: 'Name', value: 'ID' } }, + }, + }, + ], + selectionSet: { + kind: 'SelectionSet', + selections: [ + { + kind: 'Field', + name: { kind: 'Name', value: 'unsaveRecipe' }, + arguments: [ + { + kind: 'Argument', + name: { kind: 'Name', value: 'id' }, + value: { + kind: 'Variable', + name: { kind: 'Name', value: 'id' }, + }, + }, + ], + }, + ], + }, + }, + ], +} as unknown as DocumentNode< + UnsaveRecipeMutation, + UnsaveRecipeMutationVariables +>; diff --git a/contracts/operations.graphql b/contracts/operations.graphql index 06ef45b..974ac34 100644 --- a/contracts/operations.graphql +++ b/contracts/operations.graphql @@ -33,3 +33,91 @@ query CurrentUser { email } } + +fragment RecipeFields on Recipe { + id + title + description + category + cuisine + difficulty + visibility + imageUrl + sourceRecipeId + prepMinutes + cookMinutes + servings + createdAt + updatedAt + author { + id + name + } + ingredients { + id + name + amount + unit + note + } + instructions { + step + text + } + tags + rating { + average + count + } + saveCount + isSaved + isCreatedByCurrentUser +} +query Recipes($input: RecipeListInput) { + recipes(input: $input) { + items { + ...RecipeFields + } + totalCount + totalPages + page + pageSize + } +} +query Recipe($id: ID!) { + recipe(id: $id) { + ...RecipeFields + } +} +query Cookbook($input: RecipeListInput, $scope: CookbookScope) { + cookbook(input: $input, scope: $scope) { + items { + ...RecipeFields + } + totalCount + totalPages + page + pageSize + } +} +mutation CreateRecipe($input: RecipeInput!) { + createRecipe(input: $input) { + ...RecipeFields + } +} +mutation UpdateRecipe($id: ID!, $input: RecipeInput!) { + updateRecipe(id: $id, input: $input) { + ...RecipeFields + } +} +mutation DeleteRecipe($id: ID!) { + deleteRecipe(id: $id) +} +mutation SaveRecipe($id: ID!) { + saveRecipe(id: $id) { + ...RecipeFields + } +} +mutation UnsaveRecipe($id: ID!) { + unsaveRecipe(id: $id) +} diff --git a/docs/recipe-api.md b/docs/recipe-api.md new file mode 100644 index 0000000..f1060a0 --- /dev/null +++ b/docs/recipe-api.md @@ -0,0 +1,246 @@ +# Recipe API – Delivery 2 + +Branch: `hasan/feat/recipe-crud-cookies`. API-et bruker eksisterende GraphQL Yoga og +PostgreSQL-oppsett, med SQL-parametre gjennom `pg`, som autentiseringen. +Zod validerer input; databasekontrollene beholdes. Ingen ny migrasjon er nødvendig. + +## Hurtigstart for frontend + +Alle queries og mutations sendes med HTTP POST til samme GraphQL-adresse. +Operasjonsnavnet i forespørselen bestemmer hva serveren gjør. + +| Miljø | Adresse fra frontend | +| ----------------- | --------------------------------------------------- | +| Lokal Vite-server | `/graphql` (Vite videresender til API på port 3001) | +| Deploy på VM | `/project2/api/graphql` | + +Start lokalt med `npm run dev` fra prosjektroten. PostgreSQL må kjøre, +`DATABASE_URL` må være satt i `.env`, og migrasjonene må være kjørt med +`npm run db:migrate`. + +Bruk de ferdige operasjonene i [operations.graphql](../contracts/operations.graphql) +og importer tilhørende dokumenter og typer fra +[generated.ts](../contracts/generated.ts). Ikke rediger den genererte filen. + +| Komponent/funksjon | Generert dokument | +| ------------------ | --------------------------------------------- | +| Explore | `RecipesDocument` | +| Recipe Detail | `RecipeDocument` | +| Add Recipe | `CreateRecipeDocument` | +| Edit Recipe | `UpdateRecipeDocument` | +| Slett oppskrift | `DeleteRecipeDocument` | +| Save / Unsave | `SaveRecipeDocument` / `UnsaveRecipeDocument` | +| Cookbook | `CookbookDocument` | + +Eksempelet under kan ligge i `apps/web/src/features/recipes/recipeApi.ts` når +frontend kobles til i steg 3. Det oppretter en oppskrift for innlogget bruker. +Samme URL, headere og cookie-innstilling brukes for de øvrige operasjonene. + +```ts +import { print } from 'graphql'; +import { + CreateRecipeDocument, + type CreateRecipeMutation, + type CreateRecipeMutationVariables, +} from '../../../../../contracts/generated'; + +export async function createRecipe( + input: CreateRecipeMutationVariables['input'], +) { + const url = import.meta.env.DEV ? '/graphql' : '/project2/api/graphql'; + const variables: CreateRecipeMutationVariables = { input }; + const response = await fetch(url, { + method: 'POST', + credentials: 'same-origin', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + }, + body: JSON.stringify({ query: print(CreateRecipeDocument), variables }), + }); + if (!response.ok) throw new Error('Kunne ikke kontakte API-et.'); + + const result = (await response.json()) as { + data?: CreateRecipeMutation; + errors?: Array<{ message: string; extensions?: { code?: string } }>; + }; + const error = result.errors?.[0]; + if (error) { + // Komponentlaget kan bruke koden til å velge en passende feilmelding. + throw new Error(error.extensions?.code ?? 'API_ERROR'); + } + if (!result.data) throw new Error('API-et returnerte ingen data.'); + return result.data.createRecipe; +} +``` + +Et gyldig `input` for eksempelet: + +```json +{ + "title": "Enkel suppe", + "description": "En rask suppe for to.", + "category": "soup", + "difficulty": "easy", + "visibility": "private", + "prepMinutes": 5, + "cookMinutes": 10, + "servings": 2, + "ingredients": [{ "name": "Vann", "amount": 1, "unit": "l" }], + "instructions": ["Kok opp vannet."], + "tags": ["quick"] +} +``` + +`updateRecipe` krever hele samme input, i tillegg til oppskriftens `id`; +operasjonen er ikke en delvis oppdatering. Listeoperasjoner returnerer +`items`, `totalCount`, `totalPages`, `page` og `pageSize`. Cookbook bruker +`scope: "all"`, `"saved"` eller `"created"`. + +Ved frontendkobling må komponenten håndtere lasting og feil, beholde formdata +ved feil og oppdatere relevante lister etter en vellykket mutation. +Oppskriftssidene bruker fortsatt mock-data frem til steg 3. + +## Autentisering + +Branchen er oppdatert med `dev`, som inkluderer auth-cookie-forbedringene. Auth og CRUD bruker samme +GraphQL-context og HttpOnly-cookie. Serveren finner brukeren fra en gyldig, +ikke-utløpt sesjon. Forfatter og cookbook-bruker kommer alltid fra context, +aldri fra klientens bruker-ID. `currentUser` returnerer bruker eller `null`. + +Frontend sender `credentials: 'same-origin'`, `Content-Type: application/json` +og `X-Requested-With: recipe-platform`, som eksisterende auth-klient. +Sesjonstoken sendes ikke som GraphQL-argument eller i responsdata, og lagres +ikke i localStorage. Logout sletter cookien og ugyldiggjør sesjonen i databasen. +Cookie har HttpOnly, SameSite=Lax og Path=/; Secure aktiveres ved HTTPS. + +## Operasjoner + +Alle operasjonene finnes i `contracts/operations.graphql`, med genererte typer og +dokumenter i `contracts/generated.ts`. Regenerer med `npm run types:api`. + +| Operasjon | Tilgang og oppførsel | +| ------------------------- | ----------------------------------------------------------------------------- | +| `recipes(input)` | Offentlige oppskrifter, også for innlogget eier. | +| `recipe(id)` | Offentlig oppskrift eller eierens private. Utilgjengelig/ukjent gir `null`. | +| `createRecipe(input)` | Krever innlogging; lagrer hele oppskriften i én transaksjon. | +| `updateRecipe(id, input)` | Bare eier; erstatter alle redigerbare felt og barn i én transaksjon. | +| `deleteRecipe(id)` | Bare eier; databasen sletter tilknyttede rader automatisk. | +| `saveRecipe(id)` | Bare innlogget bruker; offentlig oppskrift av en annen bruker; idempotent. | +| `unsaveRecipe(id)` | Fjerner bare egen lagring; idempotent, også etter at oppskriften blir privat. | +| `cookbook(input, scope)` | Krever innlogging. Scope er `all`, `saved` eller `created`. | + +Listeinput støtter `search` (tittel/beskrivelse), `category`, `maxCookingMinutes`, +`page` og `pageSize` (1–50, standard 6). Filtrering og paginering skjer i SQL. +Sortering er nyeste først med ID som stabil tie-breaker. En side utenfor området +begrenses til siste side. Tom liste har `totalPages: 0` og `page: 1`. + +Oppskriften returnerer forfatterens offentlige ID/navn, ingredienser, ordnede steg, +tagger, datoer, vurderingsoppsummering og brukeravhengige lagrings-/eierskapsflagg. +E-post og passordhash eksponeres ikke som oppskriftsforfatterdata. + +## Input og frontendkobling + +`RecipeInput` inneholder tittel, beskrivelse, kategori, difficulty, visibility, +prepMinutes, cookMinutes, servings, ingredients, instructions og tags. +`cuisine` og `imageUrl` er valgfrie. Bildet må være en HTTP(S)-URL; dette API-et +laster ikke opp bildefiler. En ingrediens har name, amount, unit og valgfri note. +Instruksjoner sendes som en liste strenger; rekkefølgen bestemmer step/position. + +Minst én ingrediens og ett steg kreves. Mengder må være positive med maksimalt +fire desimaler og passe `numeric(12,4)`. Porsjoner er heltall 1–1000, tider er +heltall 0–10080 minutter per felt, beskrivelse maksimalt 200 tegn. Tagger trimmes, +normaliseres til små bokstaver og dedupliseres. Kategori bruker databasens fem nøkler. + +Frontend må kobles separat ved de eksisterende data-grensene. Spesielt: + +- Add Recipe har nå separate felt for navn, mengde og enhet. Konverter + mengdeverdien fra formtekst til tall. Legg til eksplisitte felt for difficulty, + prepMinutes og cookMinutes før integrasjonen; ikke gjett vanskelighetsgrad + eller fordel den eksisterende cookingTime-verdien automatisk. +- Explore/Detail må bytte mock-data med de genererte operasjonene. +- Send samme cookie og forespørselshoder som auth-klienten på oppskriftsoperasjoner. +- Etter mutasjoner: refetch liste/detail/cookbook slik at lagringstilstanden er lik. +- `cuisine` er nullable; en frontend-mapper må håndtere manglende verdi. +- Bruk eksisterende pending/error/not-found-mønstre og behold formdata ved feil. + +Feilkoder: `BAD_USER_INPUT`, `UNAUTHENTICATED`, `NOT_FOUND` og `FORBIDDEN`. +Ugyldige enumverdier avvises av GraphQL før resolveren kjøres; klienten må også +håndtere GraphQL-valideringsfeil uten disse domenekodene. +Uventede databasefeil maskeres av Yoga. Oppdatering/sletting av andres eller +ukjente oppskrifter gir samme feil og avslører ikke private data. + +### Avtale for frontendintegrasjon og videre arbeid + +- GraphQL bruker RecipeDifficulty, RecipeVisibility, RecipeCategory og + CookbookScope som enums. Verdiene beholder databasens små bokstaver, for + eksempel `easy`, `public`, `soup` og `saved`. JSON-variabler sendes fortsatt + som strenger, men inline enumverdier skrives uten anførselstegn. Cookbook- + operasjoner må deklarere `$scope: CookbookScope`, ikke `$scope: String`. + Bruk de regenererte kontraktene; ingen databasemigrasjon er nødvendig. +- Søk gjelder foreløpig bare tittel/beskrivelse. Mock-søket inkluderer også + ingredienser/tagger og normaliserer bindestrek, understrek og mellomrom mer + omfattende. Beskriv det faktiske søkeomfanget i UI-et ved integrasjon. + Behold søkeinput ved datagrensen; ingrediens-/taggsøk og felles + normaliseringsregler avklares i D3 og implementeres i backend. +- Vis bare støttet sortering ved integrasjon: nyeste først. Cookbook sitt + «recently updated» er ikke det samme som opprettelsesdato. Flere sorteringer + skal implementeres i backend før LIMIT/OFFSET, med stabil tie-breaker og + tester over flere sider. Ikke sorter eller filtrer én hentet side lokalt. +- Midlertidig opprettes oppskrifter uten opplastede bilder. Skjul/deaktiver + filvalg og beskjæring med en tydelig forklaring ved integrasjon. Ikke send + lokale blob-/data-URL-er som imageUrl. Senere kan en separat opplastingstjeneste + returnere en varig HTTP(S)-URL til eksisterende CRUD-input. +- Frontendintegrasjonen gjøres i en egen branch etter API-endringene. + Separate liste-/detaljspørringer i SQL og domenefeil som oversettes til + GraphQL-feil ved resolvergrensen vurderes i senere, avgrensede endringer. + Listeoperasjonene henter foreløpig komplette oppskrifter også i databasen. + +## Lokal kontroll og seed + +Kjør fra roten, med `DATABASE_URL` i `.env`: + +```powershell +npm.cmd run db:migrate +npm.cmd run check +npm.cmd run test:db +npm.cmd run test:api +``` + +`test:api` kjører virkelige GraphQL-operasjoner mot et tilfeldig PostgreSQL-skjema. +Det bruker ekte register/login og sesjoner, tester public/private, CRUD, +save/cookbook og fremprovoserer en barnefeil for å verifisere rollback. Skjemaet +slettes i `finally`; eksisterende `project2` og migrasjonshistorikk røres ikke. +Krever CREATE SCHEMA-rettighet. Kjør bare mot en database avsatt til utvikling/test. +Integrasjonstestene er egne kommandoer, ikke del av standard CI; runneren må ha +en separat testdatabase og kjøre begge kommandoene for automatisk DB-verifisering. + +Valgfri demoseed, etter migrasjon: + +```powershell +$env:SEED_PASSWORD = '' +npm.cmd run db:seed +Remove-Item Env:SEED_PASSWORD +``` + +Seed oppretter `demo@example.invalid`, én offentlig og én privat suppe med faste +UUID-er og strukturerte barn i én transaksjon. Gjentatte kjøringer overskriver +ikke eksisterende seed-rader eller passord. Kjøres eksplisitt, aldri under deploy. +Passordet lagres som Argon2-hash. På Linux: `SEED_PASSWORD='...' npm run db:seed`. + +## Sjekk mot Delivery 2-planen + +- D2-01/03: relasjoner og migrasjoner finnes allerede; kontrakter er utvidet. +- D2-04: eksplisitt demoseed er lagt til. +- D2-05/06/08/10: API-testmønster, autentisert context, reads/visibility og create + er implementert, sammen med eierstyrt update/delete. +- D2-12: persistent Save/Unsave/Cookbook er implementert. +- D2-07/09/11/13: frontendintegrasjon gjenstår; eksisterende auth-UI virker fortsatt. +- D2-02/15/16: VM-deploy og full nettleserdemonstrasjon må kontrolleres etter + integrasjon. Bruk eksisterende Apache/systemd-oppsett og `/project2/api/graphql`. +- D2-14: ratingmutasjoner/reviews er utsatt. Avansert sortering/søk er D3. +- Editable copies og bildeopplasting er ikke inkludert. Databasens sourceRecipeId + returneres, men klienten kan ikke endre kildehenvisning via vanlig CRUD-input. + +AI er brukt til plananalyse, implementasjon og tester. Endringene skal gjennomgås +i PR og kontrolleres med prosjektets sjekker og API-/databasetestene. diff --git a/package.json b/package.json index 773ce73..0d9c093 100644 --- a/package.json +++ b/package.json @@ -28,11 +28,13 @@ "lint": "eslint . --max-warnings 0", "format": "prettier --write .", "format:check": "prettier --check .", - "typecheck": "tsc -p apps/web/tsconfig.json && tsc -p apps/api/tsconfig.json --noEmit && tsc -p apps/api/tsconfig.test.json", + "typecheck": "tsc -p apps/web/tsconfig.json && tsc -p apps/api/tsconfig.json --noEmit && tsc -p apps/api/tsconfig.test.json && tsc -p scripts/tsconfig.json", "test": "vitest run --passWithNoTests", "test:e2e": "playwright test", "check": "npm run format:check && npm run lint && npm run types:check && npm run db:check && npm run typecheck && npm test && npm run build", - "test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts" + "test:db": "tsx --env-file-if-exists=.env scripts/test-database.ts", + "test:api": "tsx --env-file-if-exists=.env scripts/test-recipe-api.ts", + "db:seed": "tsx --env-file-if-exists=.env apps/api/src/db/seed.ts" }, "devDependencies": { "@eslint/js": "9.39.5", diff --git a/scripts/generate-api.ts b/scripts/generate-api.ts index 4584e61..0084dc0 100644 --- a/scripts/generate-api.ts +++ b/scripts/generate-api.ts @@ -15,12 +15,13 @@ const targets = [ { filename: 'apps/api/src/generated.ts', plugins: [{ typescript: {} }, { resolvers: {} }], - config: { useTypeImports: true }, + config: { useTypeImports: true, enumsAsTypes: true }, }, { filename: 'contracts/generated.ts', - plugins: [{ typescript: {} }, { operations: {} }, { typedDocument: {} }], - config: { useTypeImports: true }, + // typescript-operations v6 also emits the used input types. + plugins: [{ operations: {} }, { typedDocument: {} }], + config: { useTypeImports: true, enumsAsTypes: true }, }, ]; diff --git a/scripts/test-recipe-api.ts b/scripts/test-recipe-api.ts new file mode 100644 index 0000000..d4b1712 --- /dev/null +++ b/scripts/test-recipe-api.ts @@ -0,0 +1,532 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { test } from 'node:test'; +import { Pool } from 'pg'; +import { print } from 'graphql'; +import type { TypedDocumentNode } from '@graphql-typed-document-node/core'; +import { createApp } from '../apps/api/src/app.js'; +import { createAuthRepository } from '../apps/api/src/features/auth/authRepository.js'; +import { createAuthService } from '../apps/api/src/features/auth/authService.js'; +import { seedDatabase } from '../apps/api/src/db/seedData.js'; +import { + RegisterDocument, + LoginDocument, + CurrentUserDocument, + SignOutDocument, + CreateRecipeDocument, + UpdateRecipeDocument, + DeleteRecipeDocument, + RecipesDocument, + RecipeDocument, + SaveRecipeDocument, + UnsaveRecipeDocument, + CookbookDocument, + type RecipeInput, +} from '../contracts/generated.js'; + +await test('recipe GraphQL API against PostgreSQL', async (t) => { + assert.ok(process.env.DATABASE_URL, 'Set DATABASE_URL in .env.'); + const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + connectionTimeoutMillis: 5000, + }); + const schema = 'api_test_' + randomUUID().replaceAll('-', ''); + const api = createApp( + createAuthService(createAuthRepository(pool, pool, schema)), + false, + false, + { pool, schema }, + ); + const input: RecipeInput = { + title: 'Test soup', + description: 'Simple soup', + category: 'soup', + cuisine: null, + difficulty: 'easy', + visibility: 'public', + prepMinutes: 5, + cookMinutes: 10, + servings: 2, + ingredients: [ + { name: 'Salt', amount: 0.125, unit: 'tsp' }, + { name: 'Water', amount: 1, unit: 'l' }, + ], + instructions: ['Boil water', 'Add salt'], + tags: [' Quick ', 'quick'], + }; + async function request( + document: TypedDocumentNode, + variables: V, + cookie?: string, + ) { + const response = await api.fetch('http://localhost/graphql', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Requested-With': 'recipe-platform', + ...(cookie ? { Cookie: cookie } : {}), + }, + body: JSON.stringify({ query: print(document), variables }), + }); + const sessionCookie = + response.headers.get('set-cookie')?.split(';')[0] ?? ''; + const result = (await response.json()) as { + data: T; + errors?: { message: string; extensions: { code?: string } }[]; + }; + return { ...result, cookie: sessionCookie }; + } + async function ok( + document: TypedDocumentNode, + variables: V, + cookie?: string, + ) { + const result = await request(document, variables, cookie); + assert.equal(result.errors, undefined, JSON.stringify(result.errors)); + return result.data; + } + async function fails( + document: TypedDocumentNode, + variables: V, + code: string, + cookie?: string, + ) { + const result = await request(document, variables, cookie); + assert.equal( + result.errors?.[0]?.extensions.code, + code, + JSON.stringify(result), + ); + } + async function register(name: string, email: string) { + const result = await request(RegisterDocument, { + name, + email, + password: 'test-password', + }); + assert.equal(result.errors, undefined); + assert.ok(result.cookie); + assert.ok(!JSON.stringify(result.data).includes('sessionToken')); + return { ...result.data.register, cookie: result.cookie }; + } + async function loginSession(email: string, password: string) { + const result = await request(LoginDocument, { email, password }); + assert.equal(result.errors, undefined); + assert.ok(result.cookie); + return { ...result.data.login, cookie: result.cookie }; + } + try { + await pool.query(`CREATE SCHEMA "${schema}"`); + const journal = JSON.parse( + await readFile('apps/api/migrations/meta/_journal.json', 'utf8'), + ) as { entries: { tag: string }[] }; + // Exercise all real migrations; no writes to project2 or its migration history. + const client = await pool.connect(); + try { + await client.query('BEGIN'); + for (const { tag } of journal.entries) + await client.query( + (await readFile(`apps/api/migrations/${tag}.sql`, 'utf8')).replaceAll( + '"project2"', + `"${schema}"`, + ), + ); + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK'); + throw error; + } finally { + client.release(); + } + + const owner = await register('Owner', 'owner@example.com'); + const reader = await register('Reader', 'reader@example.com'); + await t.test('persistent login and authenticated context', async () => { + const login = await loginSession('owner@example.com', 'test-password'); + assert.equal( + (await ok(CurrentUserDocument, {}, login.cookie)).currentUser?.id, + owner.user.id, + ); + assert.equal((await ok(CurrentUserDocument, {})).currentUser, null); + assert.equal( + ( + await ok( + CurrentUserDocument, + {}, + 't31_project2_session=invalid-token', + ) + ).currentUser, + null, + ); + await pool.query( + `UPDATE "${schema}".sessions SET expires_at=now()-interval '1 second' WHERE id=$1`, + [login.cookie.split('=')[1]], + ); + assert.equal( + (await ok(CurrentUserDocument, {}, login.cookie)).currentUser, + null, + ); + }); + await t.test( + 'anonymous, malformed and expired sessions cannot create', + async () => { + for (const token of [ + undefined, + 't31_project2_session=invalid-token', + 't31_project2_session=' + randomUUID(), + ]) + await fails( + CreateRecipeDocument, + { input }, + 'UNAUTHENTICATED', + token, + ); + }, + ); + await t.test('Zod rejects invalid input without writing rows', async () => { + for (const invalid of [ + { ...input, title: ' ' }, + { ...input, servings: 0 }, + { ...input, ingredients: [] }, + { ...input, instructions: [] }, + { + ...input, + ingredients: [{ name: 'Salt', amount: 0.00001, unit: 'tsp' }], + }, + ]) { + await fails( + CreateRecipeDocument, + { input: invalid }, + 'BAD_USER_INPUT', + owner.cookie, + ); + } + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 0, + ); + }); + const publicRecipe = ( + await ok(CreateRecipeDocument, { input }, owner.cookie) + ).createRecipe; + const privateRecipe = ( + await ok( + CreateRecipeDocument, + { input: { ...input, title: 'Private soup', visibility: 'private' } }, + owner.cookie, + ) + ).createRecipe; + await t.test( + 'creation persists ordered content and uses authenticated author', + async () => { + assert.equal(publicRecipe.author.id, owner.user.id); + assert.equal(publicRecipe.cuisine, null); + assert.deepEqual(publicRecipe.tags, ['quick']); + const read = (await ok(RecipeDocument, { id: publicRecipe.id })) + .recipe!; + assert.equal(read.ingredients[0]?.amount, 0.125); + assert.deepEqual( + read.instructions.map((step) => step.text), + input.instructions, + ); + assert.equal(read.isCreatedByCurrentUser, false); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 2, + ); + }, + ); + await t.test( + 'public list excludes private data; private detail is owner-only', + async () => { + for (const token of [undefined, owner.cookie, reader.cookie]) { + const list = (await ok(RecipesDocument, {}, token)).recipes; + assert.deepEqual( + list.items.map((item) => item.id), + [publicRecipe.id], + ); + } + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id })).recipe, + null, + ); + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id }, reader.cookie)) + .recipe, + null, + ); + assert.equal( + (await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie)) + .recipe?.id, + privateRecipe.id, + ); + assert.equal( + (await ok(RecipeDocument, { id: randomUUID() })).recipe, + null, + ); + }, + ); + await t.test('search, filters and paging run on the server', async () => { + assert.equal( + ( + await ok(RecipesDocument, { + input: { search: 'SOUP', category: 'soup', page: 99, pageSize: 1 }, + }) + ).recipes.page, + 1, + ); + assert.equal( + (await ok(RecipesDocument, { input: { search: 'missing' } })).recipes + .totalCount, + 0, + ); + assert.equal( + (await ok(RecipesDocument, { input: { maxCookingMinutes: 14 } })) + .recipes.totalCount, + 0, + ); + await fails( + RecipesDocument, + { input: { pageSize: 51 } }, + 'BAD_USER_INPUT', + ); + }); + await t.test('only the owner can update or delete', async () => { + await fails( + UpdateRecipeDocument, + { id: publicRecipe.id, input }, + 'NOT_FOUND', + reader.cookie, + ); + await fails( + DeleteRecipeDocument, + { id: publicRecipe.id }, + 'NOT_FOUND', + reader.cookie, + ); + await fails( + UpdateRecipeDocument, + { id: publicRecipe.id, input }, + 'UNAUTHENTICATED', + ); + const edited = ( + await ok( + UpdateRecipeDocument, + { + id: publicRecipe.id, + input: { + ...input, + title: 'Updated soup', + instructions: ['Serve'], + ingredients: [{ name: 'Pepper', amount: 1, unit: '' }], + }, + }, + owner.cookie, + ) + ).updateRecipe; + assert.equal(edited.title, 'Updated soup'); + assert.equal(edited.ingredients.length, 1); + assert.deepEqual(edited.instructions, [{ step: 1, text: 'Serve' }]); + }); + await t.test( + 'save is idempotent, private recipes and own recipes are blocked', + async () => { + await fails( + SaveRecipeDocument, + { id: publicRecipe.id }, + 'UNAUTHENTICATED', + ); + await fails( + SaveRecipeDocument, + { id: privateRecipe.id }, + 'FORBIDDEN', + reader.cookie, + ); + await fails( + SaveRecipeDocument, + { id: publicRecipe.id }, + 'FORBIDDEN', + owner.cookie, + ); + for (let i = 0; i < 2; i++) { + const saved = ( + await ok(SaveRecipeDocument, { id: publicRecipe.id }, reader.cookie) + ).saveRecipe; + assert.equal(saved.isSaved, true); + assert.equal(saved.saveCount, 1); + } + assert.equal( + (await ok(CookbookDocument, { scope: 'saved' }, reader.cookie)) + .cookbook.totalCount, + 1, + ); + assert.equal( + (await ok(CookbookDocument, { scope: 'created' }, owner.cookie)) + .cookbook.totalCount, + 2, + ); + await fails(CookbookDocument, {}, 'UNAUTHENTICATED'); + }, + ); + await t.test( + 'making a saved recipe private hides it from other cookbooks', + async () => { + await ok( + UpdateRecipeDocument, + { id: publicRecipe.id, input: { ...input, visibility: 'private' } }, + owner.cookie, + ); + for (const scope of ['all', 'saved', 'created'] as const) { + assert.equal( + (await ok(CookbookDocument, { scope }, reader.cookie)).cookbook + .totalCount, + 0, + ); + } + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id }, reader.cookie)) + .recipe, + null, + ); + await ok(UnsaveRecipeDocument, { id: publicRecipe.id }, reader.cookie); + await ok(UnsaveRecipeDocument, { id: publicRecipe.id }, reader.cookie); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".saved_recipes`, + ) + ).rows[0].count, + 0, + ); + }, + ); + await t.test( + 'child insert failures roll back both creation and updates', + async () => { + await pool.query( + `CREATE FUNCTION "${schema}".reject_test_ingredient() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.name='fail-test' THEN RAISE EXCEPTION 'forced child failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER reject_test BEFORE INSERT ON "${schema}".recipe_ingredients FOR EACH ROW EXECUTE FUNCTION "${schema}".reject_test_ingredient()`, + ); + const bad = { + ...input, + ingredients: [ + ...input.ingredients, + { name: 'fail-test', amount: 1, unit: '' }, + ], + }; + const failedCreate = await request( + CreateRecipeDocument, + { input: bad }, + owner.cookie, + ); + assert.ok(failedCreate.errors); + const before = ( + await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie) + ).recipe; + assert.ok( + ( + await request( + UpdateRecipeDocument, + { id: privateRecipe.id, input: bad }, + owner.cookie, + ) + ).errors, + ); + assert.deepEqual( + (await ok(RecipeDocument, { id: privateRecipe.id }, owner.cookie)) + .recipe, + before, + ); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipes`, + ) + ).rows[0].count, + 2, + ); + }, + ); + await t.test( + 'delete cascades; logout revokes later protected calls', + async () => { + await ok(DeleteRecipeDocument, { id: publicRecipe.id }, owner.cookie); + assert.equal( + (await ok(RecipeDocument, { id: publicRecipe.id }, owner.cookie)) + .recipe, + null, + ); + assert.equal( + ( + await pool.query( + `SELECT count(*)::int AS count FROM "${schema}".recipe_ingredients WHERE recipe_id=$1`, + [publicRecipe.id], + ) + ).rows[0].count, + 0, + ); + await ok(SignOutDocument, {}, owner.cookie); + await fails( + CreateRecipeDocument, + { input }, + 'UNAUTHENTICATED', + owner.cookie, + ); + }, + ); + await t.test( + 'demo seed is repeatable and preserves existing passwords', + async () => { + await seedDatabase(pool, 'demo-test-password', schema); + const originalHash = ( + await pool.query( + `SELECT password_hash FROM "${schema}".users WHERE email='demo@example.invalid'`, + ) + ).rows[0].password_hash; + await seedDatabase(pool, 'different-demo-password', schema); + assert.equal( + ( + await pool.query( + `SELECT password_hash FROM "${schema}".users WHERE email='demo@example.invalid'`, + ) + ).rows[0].password_hash, + originalHash, + ); + const demo = await loginSession( + 'demo@example.invalid', + 'demo-test-password', + ); + const cookbook = ( + await ok(CookbookDocument, { scope: 'created' }, demo.cookie) + ).cookbook; + assert.equal(cookbook.totalCount, 2); + assert.equal( + cookbook.items.filter((recipe) => recipe.visibility === 'private') + .length, + 1, + ); + assert.ok( + cookbook.items.every( + (recipe) => + recipe.ingredients.length === 2 && + recipe.instructions.length === 2, + ), + ); + }, + ); + } finally { + try { + await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); + } finally { + await pool.end(); + } + } +}); diff --git a/scripts/tsconfig.json b/scripts/tsconfig.json new file mode 100644 index 0000000..06da1da --- /dev/null +++ b/scripts/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "module": "NodeNext", + "moduleResolution": "NodeNext", + "types": ["node"], + "noEmit": true + }, + "include": ["test-recipe-api.ts"] +}