2 Commits

Author SHA1 Message Date
Azriel
e10b387be6 fix: auth middleware, JWT_SECRET env guard, and password reset token lookup 2026-05-10 15:23:34 +00:00
Azriel
e633d693da feat: implement backend API for Pantree Phase 1 MVP
- Project setup: package.json, tsconfig.json, jest.config.js, .env.example
- Config: env.ts, constants.ts (ALLOWED_UNITS, bcrypt rounds, JWT, deletion windows)
- DB: Knex connection, knexfile, migrations 001-006 (users, password_reset_tokens,
  pantry_items, recipes+recipe_ingredients, shopping_lists+items, deleted_records)
- Seeds: 10 seeded recipes with full ingredient lists
- Middleware: JWT authMiddleware (validates token + user existence), errorHandler
- Utils: Pino logger, JWT sign helper, Zod validators for all request shapes
- Services: authService (signup/signin/google/pwd-reset/soft-delete/restore),
  pantryService (CRUD + case-insensitive duplicate guard),
  recipeService (browse+filter+scale), shoppingListService (CRUD+merge logic),
  syncService (delta sync + tombstone cleanup), emailService (SendGrid)
- Routes: /v1/auth, /v1/pantry, /v1/recipes, /v1/shopping-lists, /v1/sync
- App: Express factory (createApp), server entry point
- Jobs: node-cron daily hard-delete + tombstone cleanup
- Tests: validators, utils, auth, pantry, recipes, shopping lists, sync
2026-05-10 15:00:15 +00:00
74 changed files with 3105 additions and 4113 deletions

View File

@@ -1,39 +1,21 @@
# ─────────────────────────────────────────────
# Pantree Backend — Environment Variables
# Copy to .env and fill in real values.
# NEVER commit .env to version control.
# ─────────────────────────────────────────────
# Server # Server
PORT=3000
NODE_ENV=development NODE_ENV=development
PORT=3000
# PostgreSQL # Database
DB_HOST=localhost DATABASE_URL=postgresql://user:password@localhost:5432/pantree
DB_PORT=5432
DB_NAME=pantree
DB_USER=postgres
DB_PASSWORD=changeme
# JWT — use a long random secret in production # JWT
JWT_SECRET=change-this-to-a-long-random-secret JWT_SECRET=change_this_to_a_long_random_secret_at_least_64_chars
JWT_EXPIRES_IN=24h JWT_EXPIRES_IN=24h
# Google OAuth # Google OAuth
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com GOOGLE_CLIENT_ID=your_google_client_id_here
# Email (SMTP / SendGrid / SES) # SendGrid
EMAIL_HOST=smtp.ethereal.email SENDGRID_API_KEY=your_sendgrid_api_key_here
EMAIL_PORT=587 SENDGRID_FROM_EMAIL=noreply@pantree.app
EMAIL_USER=
EMAIL_PASS=
EMAIL_FROM=noreply@pantree.app
# App base URL (used in password-reset links) # App
APP_BASE_URL=https://pantree.app FRONTEND_URL=https://pantree.app
PASSWORD_RESET_URL=https://pantree.app/reset-password
# Account deletion window (days)
ACCOUNT_DELETION_DAYS=15
# Password reset token expiry (hours)
RESET_TOKEN_EXPIRY_HOURS=1

6
.gitignore vendored Normal file
View File

@@ -0,0 +1,6 @@
node_modules/
dist/
.env
*.log
coverage/
.DS_Store

24
jest.config.js Normal file
View File

@@ -0,0 +1,24 @@
/** @type {import('jest').Config} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/*.test.ts'],
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.test.ts',
'!src/db/knexfile.ts',
'!src/db/migrations/**',
'!src/db/seeds/**',
'!src/server.ts'
],
coverageThreshold: {
global: {
branches: 70,
functions: 80,
lines: 80,
statements: 80
}
},
setupFiles: ['<rootDir>/src/test/setup.ts']
};

View File

@@ -1,36 +1,49 @@
{ {
"name": "pantree-backend", "name": "pantree-backend",
"version": "1.0.0", "version": "1.0.0",
"description": "Pantree backend API server", "description": "Pantree API Server",
"main": "src/main/index.js", "main": "dist/server.js",
"scripts": { "scripts": {
"start": "node src/main/index.js", "build": "tsc",
"dev": "nodemon src/main/index.js", "start": "node dist/server.js",
"dev": "ts-node-dev --respawn --transpile-only src/server.ts",
"test": "jest --runInBand --forceExit", "test": "jest --runInBand --forceExit",
"test:coverage": "jest --runInBand --forceExit --coverage" "test:coverage": "jest --runInBand --forceExit --coverage",
"migrate": "knex migrate:latest --knexfile src/db/knexfile.ts",
"migrate:rollback": "knex migrate:rollback --knexfile src/db/knexfile.ts",
"seed": "knex seed:run --knexfile src/db/knexfile.ts"
}, },
"dependencies": { "dependencies": {
"@sendgrid/mail": "^8.1.0",
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.3.1", "dotenv": "^16.4.5",
"express": "^4.18.2", "express": "^4.19.2",
"google-auth-library": "^9.10.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"knex": "^3.1.0", "knex": "^3.1.0",
"node-cron": "^3.0.3", "node-cron": "^3.0.3",
"nodemailer": "^6.9.7", "pg": "^8.11.5",
"pg": "^8.11.3", "pino": "^9.1.0",
"uuid": "^9.0.0", "pino-http": "^10.1.0",
"zod": "^3.22.4" "uuid": "^9.0.1",
"zod": "^3.23.8"
}, },
"devDependencies": { "devDependencies": {
"@types/bcrypt": "^5.0.2",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/jest": "^29.5.12",
"@types/jsonwebtoken": "^9.0.6",
"@types/node": "^20.12.12",
"@types/node-cron": "^3.0.11",
"@types/supertest": "^6.0.2",
"@types/uuid": "^9.0.8",
"jest": "^29.7.0", "jest": "^29.7.0",
"supertest": "^6.3.3" "supertest": "^7.0.0",
}, "ts-jest": "^29.1.4",
"jest": { "ts-node": "^10.9.2",
"testEnvironment": "node", "ts-node-dev": "^2.0.0",
"testMatch": [ "typescript": "^5.4.5"
"**/tests/**/*.test.js"
],
"setupFilesAfterFramework": []
} }
} }

42
src/app.ts Normal file
View File

@@ -0,0 +1,42 @@
import express from 'express';
import cors from 'cors';
import { httpLogger } from './utils/logger';
import { errorHandler } from './middleware/errorHandler';
import authRoutes from './routes/auth';
import pantryRoutes from './routes/pantry';
import recipeRoutes from './routes/recipes';
import shoppingListRoutes from './routes/shoppingLists';
import syncRoutes from './routes/sync';
export function createApp() {
const app = express();
app.use(cors());
app.use(express.json());
app.use(httpLogger);
// Health check
app.get('/health', (_req, res) => {
res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() });
});
// Routes
app.use('/v1/auth', authRoutes);
app.use('/v1/pantry', pantryRoutes);
app.use('/v1/recipes', recipeRoutes);
app.use('/v1/shopping-lists', shoppingListRoutes);
app.use('/v1/sync', syncRoutes);
// 404 handler
app.use((_req, res) => {
res.status(404).json({
error: 'Route not found.',
code: 'NOT_FOUND',
timestamp: new Date().toISOString(),
});
});
app.use(errorHandler);
return app;
}

18
src/config/constants.ts Normal file
View File

@@ -0,0 +1,18 @@
export const ALLOWED_UNITS = [
'cups', 'tbsp', 'tsp', 'oz', 'fl_oz',
'g', 'kg', 'ml', 'l',
'pieces', 'slices', 'cloves', 'pinch',
'whole', 'can', 'package', 'bunch'
] as const;
export type AllowedUnit = typeof ALLOWED_UNITS[number];
export const BCRYPT_ROUNDS = 12;
export const JWT_EXPIRES_IN = '24h';
export const PASSWORD_RESET_EXPIRES_HOURS = 1;
export const ACCOUNT_DELETION_DAYS = 15;
export const TOMBSTONE_RETENTION_DAYS = 30;
export const MAX_RECIPE_SCALE = 3;
export const MIN_RECIPE_SCALE = 1;
export const DEFAULT_PAGE_LIMIT = 20;
export const MAX_PAGE_LIMIT = 50;

30
src/config/env.ts Normal file
View File

@@ -0,0 +1,30 @@
import dotenv from 'dotenv';
dotenv.config();
function requireEnv(key: string): string {
const value = process.env[key];
if (!value) {
throw new Error(`Missing required environment variable: ${key}`);
}
return value;
}
const isTest = process.env.NODE_ENV === 'test';
export const config = {
nodeEnv: process.env.NODE_ENV ?? 'development',
port: parseInt(process.env.PORT ?? '3000', 10),
databaseUrl: process.env.DATABASE_URL ?? 'postgresql://postgres:postgres@localhost:5432/pantree_test',
jwtSecret: isTest
? (process.env.JWT_SECRET ?? 'test_secret_do_not_use_in_production_ever')
: requireEnv('JWT_SECRET'),
jwtExpiresIn: process.env.JWT_EXPIRES_IN ?? '24h',
googleClientId: process.env.GOOGLE_CLIENT_ID ?? '',
sendgridApiKey: process.env.SENDGRID_API_KEY ?? '',
sendgridFromEmail: process.env.SENDGRID_FROM_EMAIL ?? 'noreply@pantree.app',
frontendUrl: process.env.FRONTEND_URL ?? 'http://localhost:3000',
passwordResetUrl: process.env.PASSWORD_RESET_URL ?? 'http://localhost:3000/reset-password',
isTest,
isDev: process.env.NODE_ENV === 'development',
isProd: process.env.NODE_ENV === 'production',
};

View File

@@ -1,38 +0,0 @@
'use strict';
require('dotenv').config();
module.exports = {
port: parseInt(process.env.PORT || '3000', 10),
nodeEnv: process.env.NODE_ENV || 'development',
db: {
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '5432', 10),
database: process.env.DB_NAME || 'pantree',
user: process.env.DB_USER || 'postgres',
password: process.env.DB_PASSWORD || '',
},
jwt: {
secret: process.env.JWT_SECRET || 'dev-secret-change-in-production',
expiresIn: process.env.JWT_EXPIRES_IN || '24h',
},
google: {
clientId: process.env.GOOGLE_CLIENT_ID || '',
},
email: {
host: process.env.EMAIL_HOST || 'smtp.ethereal.email',
port: parseInt(process.env.EMAIL_PORT || '587', 10),
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS || '',
from: process.env.EMAIL_FROM || 'noreply@pantree.app',
},
appBaseUrl: process.env.APP_BASE_URL || 'https://pantree.app',
accountDeletionDays: parseInt(process.env.ACCOUNT_DELETION_DAYS || '15', 10),
resetTokenExpiryHours: parseInt(process.env.RESET_TOKEN_EXPIRY_HOURS || '1', 10),
};

6
src/db/connection.ts Normal file
View File

@@ -0,0 +1,6 @@
import knex from 'knex';
import knexConfig from './knexfile';
const db = knex(knexConfig);
export default db;

View File

@@ -1,31 +0,0 @@
'use strict';
const knex = require('knex');
const config = require('../config');
let instance = null;
/**
* Returns the singleton Knex instance.
* In tests, call setDb() to inject a test database.
*/
function getDb() {
if (!instance) {
instance = knex({
client: 'pg',
connection: config.db,
pool: { min: 2, max: 10 },
});
}
return instance;
}
/**
* Replaces the singleton — used in tests to inject an in-memory or
* test-scoped database without touching the real connection.
*/
function setDb(db) {
instance = db;
}
module.exports = { getDb, setDb };

22
src/db/knexfile.ts Normal file
View File

@@ -0,0 +1,22 @@
import type { Knex } from 'knex';
import { config } from '../config/env';
const knexConfig: Knex.Config = {
client: 'pg',
connection: config.databaseUrl,
migrations: {
directory: './migrations',
extension: 'ts',
},
seeds: {
directory: './seeds',
extension: 'ts',
},
pool: {
min: 2,
max: 10,
},
};
export default knexConfig;
module.exports = knexConfig;

View File

@@ -0,0 +1,27 @@
import type { Knex } from 'knex';
export async function up(knex: Knex): Promise<void> {
await knex.raw('CREATE EXTENSION IF NOT EXISTS "pgcrypto"');
await knex.schema.createTable('users', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.string('email', 255).notNullable();
table.string('password_hash', 255).nullable();
table.string('name', 255).notNullable();
table.text('profile_picture_url').nullable();
table.string('google_id', 255).nullable();
table.boolean('email_verified').defaultTo(false);
table.timestamp('deleted_at', { useTz: true }).nullable();
table.timestamp('deletion_scheduled_at', { useTz: true }).nullable();
table.timestamp('created_at', { useTz: true }).defaultTo(knex.fn.now());
table.timestamp('updated_at', { useTz: true }).defaultTo(knex.fn.now());
});
await knex.raw(`CREATE UNIQUE INDEX idx_users_email ON users (LOWER(email))`);
await knex.raw(`CREATE UNIQUE INDEX idx_users_google_id ON users (google_id) WHERE google_id IS NOT NULL`);
await knex.raw(`CREATE INDEX idx_users_deletion_scheduled ON users (deletion_scheduled_at) WHERE deletion_scheduled_at IS NOT NULL`);
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTableIfExists('users');
}

View File

@@ -1,199 +0,0 @@
-- Migration: 001_initial_schema.sql
-- Full schema for Pantree Phase 1 MVP
-- Run once against a fresh PostgreSQL 15+ database.
-- ─────────────────────────────────────────────
-- Extensions
-- ─────────────────────────────────────────────
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- ─────────────────────────────────────────────
-- USERS
-- ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) NOT NULL,
password_hash VARCHAR(255) NULL,
name VARCHAR(100) NOT NULL,
profile_picture_url TEXT NULL,
auth_provider VARCHAR(20) NOT NULL DEFAULT 'email',
google_id VARCHAR(255) NULL,
email_verified BOOLEAN NOT NULL DEFAULT FALSE,
deleted_at TIMESTAMPTZ NULL,
deletion_scheduled_at TIMESTAMPTZ NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email
ON users (LOWER(email));
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_google_id
ON users (google_id)
WHERE google_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_users_deletion_scheduled
ON users (deletion_scheduled_at)
WHERE deletion_scheduled_at IS NOT NULL;
-- ─────────────────────────────────────────────
-- PANTRY ITEMS
-- ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS pantry_items (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
item_name VARCHAR(200) NOT NULL,
item_name_lower VARCHAR(200) GENERATED ALWAYS AS (LOWER(item_name)) STORED,
quantity INTEGER NOT NULL CHECK (quantity > 0),
last_modified TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_pantry_user_item
ON pantry_items (user_id, item_name_lower);
CREATE INDEX IF NOT EXISTS idx_pantry_user_id
ON pantry_items (user_id);
CREATE INDEX IF NOT EXISTS idx_pantry_last_modified
ON pantry_items (user_id, last_modified);
-- ─────────────────────────────────────────────
-- RECIPES
-- ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS recipes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(300) NOT NULL,
instructions TEXT NOT NULL,
servings INTEGER NOT NULL CHECK (servings > 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_recipes_name
ON recipes (LOWER(name));
-- ─────────────────────────────────────────────
-- RECIPE INGREDIENTS
-- ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS recipe_ingredients (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
recipe_id UUID NOT NULL REFERENCES recipes(id) ON DELETE CASCADE,
item_name VARCHAR(200) NOT NULL,
item_name_lower VARCHAR(200) GENERATED ALWAYS AS (LOWER(item_name)) STORED,
quantity DECIMAL(10,4) NOT NULL CHECK (quantity > 0),
unit VARCHAR(50) NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_recipe_ingredients_recipe
ON recipe_ingredients (recipe_id);
CREATE INDEX IF NOT EXISTS idx_recipe_ingredients_name
ON recipe_ingredients (item_name_lower);
-- ─────────────────────────────────────────────
-- SHOPPING LISTS
-- ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS shopping_lists (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
list_name VARCHAR(200) NOT NULL,
last_modified TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_shopping_lists_user
ON shopping_lists (user_id);
CREATE INDEX IF NOT EXISTS idx_shopping_lists_last_modified
ON shopping_lists (user_id, last_modified);
-- ─────────────────────────────────────────────
-- SHOPPING LIST ITEMS
-- ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS shopping_list_items (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
shopping_list_id UUID NOT NULL REFERENCES shopping_lists(id) ON DELETE CASCADE,
item_name VARCHAR(200) NOT NULL,
item_name_lower VARCHAR(200) GENERATED ALWAYS AS (LOWER(item_name)) STORED,
quantity DECIMAL(10,4) NOT NULL CHECK (quantity > 0),
unit VARCHAR(50) NOT NULL,
checked_off BOOLEAN NOT NULL DEFAULT FALSE,
last_modified TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_shopping_list_items_merge
ON shopping_list_items (shopping_list_id, item_name_lower, unit);
CREATE INDEX IF NOT EXISTS idx_shopping_list_items_list
ON shopping_list_items (shopping_list_id);
CREATE INDEX IF NOT EXISTS idx_shopping_list_items_last_modified
ON shopping_list_items (shopping_list_id, last_modified);
-- ─────────────────────────────────────────────
-- PASSWORD RESET TOKENS
-- ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS password_reset_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(255) NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_password_reset_token_hash
ON password_reset_tokens (token_hash);
CREATE INDEX IF NOT EXISTS idx_password_reset_user
ON password_reset_tokens (user_id);
-- ─────────────────────────────────────────────
-- DELETED RECORDS (tombstones for sync)
-- ─────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS deleted_records (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
record_type VARCHAR(50) NOT NULL,
record_id UUID NOT NULL,
deleted_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_deleted_records_user
ON deleted_records (user_id, deleted_at);
-- ─────────────────────────────────────────────
-- updated_at TRIGGER
-- ─────────────────────────────────────────────
CREATE OR REPLACE FUNCTION set_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_users_updated_at
BEFORE UPDATE ON users
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
CREATE TRIGGER trg_pantry_updated_at
BEFORE UPDATE ON pantry_items
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
CREATE TRIGGER trg_recipes_updated_at
BEFORE UPDATE ON recipes
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
CREATE TRIGGER trg_shopping_lists_updated_at
BEFORE UPDATE ON shopping_lists
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
CREATE TRIGGER trg_shopping_list_items_updated_at
BEFORE UPDATE ON shopping_list_items
FOR EACH ROW EXECUTE FUNCTION set_updated_at();

View File

@@ -0,0 +1,20 @@
import type { Knex } from 'knex';
export async function up(knex: Knex): Promise<void> {
await knex.schema.createTable('password_reset_tokens', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.uuid('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
table.string('token_hash', 255).notNullable();
table.string('lookup_hash', 64).notNullable();
table.timestamp('expires_at', { useTz: true }).notNullable();
table.timestamp('used_at', { useTz: true }).nullable();
table.timestamp('created_at', { useTz: true }).defaultTo(knex.fn.now());
});
await knex.raw(`CREATE INDEX idx_prt_user_id ON password_reset_tokens (user_id)`);
await knex.raw(`CREATE UNIQUE INDEX idx_prt_lookup_hash ON password_reset_tokens (lookup_hash)`);
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTableIfExists('password_reset_tokens');
}

View File

@@ -1,282 +0,0 @@
-- Seed: 002_seed_recipes.sql
-- 50 pre-populated recipes for Pantree Phase 1.
-- Recipes are read-only in Phase 1 — users cannot create or modify them.
INSERT INTO recipes (id, name, instructions, servings) VALUES
('00000000-0000-0000-0000-000000000001', 'Classic Pancakes',
E'1. Whisk together flour, baking powder, salt, and sugar.\n2. In a separate bowl, mix milk, egg, and melted butter.\n3. Combine wet and dry ingredients until just mixed.\n4. Cook on a greased griddle over medium heat until bubbles form, then flip.\n5. Serve warm with maple syrup.',
4),
('00000000-0000-0000-0000-000000000002', 'Scrambled Eggs',
E'1. Crack eggs into a bowl, add milk, salt, and pepper. Whisk well.\n2. Melt butter in a non-stick pan over low heat.\n3. Pour in egg mixture and stir gently with a spatula.\n4. Remove from heat while still slightly wet — residual heat finishes cooking.\n5. Serve immediately.',
2),
('00000000-0000-0000-0000-000000000003', 'Spaghetti Bolognese',
E'1. Brown ground beef in a large pan over medium-high heat. Drain fat.\n2. Add diced onion and garlic; cook until softened.\n3. Stir in tomato paste, crushed tomatoes, oregano, salt, and pepper.\n4. Simmer for 20 minutes.\n5. Cook spaghetti per package instructions.\n6. Serve sauce over pasta with grated parmesan.',
4),
('00000000-0000-0000-0000-000000000004', 'Caesar Salad',
E'1. Tear romaine lettuce into bite-sized pieces.\n2. Whisk together olive oil, lemon juice, garlic, worcestershire sauce, and parmesan.\n3. Toss lettuce with dressing.\n4. Top with croutons and extra parmesan.\n5. Season with black pepper.',
2),
('00000000-0000-0000-0000-000000000005', 'Chicken Stir Fry',
E'1. Slice chicken breast into thin strips. Season with salt and pepper.\n2. Heat oil in a wok over high heat.\n3. Cook chicken until golden, about 5 minutes. Remove.\n4. Stir fry vegetables (bell pepper, broccoli, carrot) for 3 minutes.\n5. Return chicken, add soy sauce and sesame oil.\n6. Serve over steamed rice.',
3),
('00000000-0000-0000-0000-000000000006', 'Banana Bread',
E'1. Preheat oven to 350°F (175°C). Grease a loaf pan.\n2. Mash 3 ripe bananas in a bowl.\n3. Mix in melted butter, sugar, egg, and vanilla.\n4. Stir in flour, baking soda, and salt until just combined.\n5. Pour into pan and bake 60 minutes until a toothpick comes out clean.',
8),
('00000000-0000-0000-0000-000000000007', 'Tomato Soup',
E'1. Sauté diced onion and garlic in butter until soft.\n2. Add crushed tomatoes, chicken broth, sugar, salt, and pepper.\n3. Simmer 15 minutes.\n4. Blend until smooth with an immersion blender.\n5. Stir in heavy cream. Adjust seasoning.\n6. Serve with crusty bread.',
4),
('00000000-0000-0000-0000-000000000008', 'Grilled Cheese Sandwich',
E'1. Butter one side of each bread slice.\n2. Place one slice butter-side down in a pan over medium heat.\n3. Layer cheese slices on top.\n4. Place second slice butter-side up.\n5. Cook until golden, about 3 minutes per side.\n6. Slice diagonally and serve.',
1),
('00000000-0000-0000-0000-000000000009', 'Chocolate Chip Cookies',
E'1. Preheat oven to 375°F (190°C).\n2. Cream butter and sugars until fluffy.\n3. Beat in eggs and vanilla.\n4. Mix in flour, baking soda, and salt.\n5. Fold in chocolate chips.\n6. Drop spoonfuls onto baking sheet.\n7. Bake 911 minutes until edges are golden.',
24),
('00000000-0000-0000-0000-000000000010', 'Guacamole',
E'1. Halve and pit avocados. Scoop flesh into a bowl.\n2. Mash with a fork to desired consistency.\n3. Stir in lime juice, salt, diced onion, cilantro, and jalapeño.\n4. Taste and adjust seasoning.\n5. Serve immediately with tortilla chips.',
4),
('00000000-0000-0000-0000-000000000011', 'French Toast',
E'1. Whisk eggs, milk, cinnamon, and vanilla in a shallow bowl.\n2. Dip bread slices in egg mixture, coating both sides.\n3. Cook in buttered pan over medium heat until golden, about 2 minutes per side.\n4. Serve with powdered sugar and maple syrup.',
2),
('00000000-0000-0000-0000-000000000012', 'Chicken Soup',
E'1. Simmer chicken thighs in water with salt for 30 minutes. Remove and shred.\n2. Add diced carrots, celery, and onion to broth.\n3. Cook vegetables until tender, about 15 minutes.\n4. Return shredded chicken to pot.\n5. Add egg noodles and cook per package instructions.\n6. Season with salt, pepper, and parsley.',
6),
('00000000-0000-0000-0000-000000000013', 'Fried Rice',
E'1. Cook rice and let cool completely (day-old rice works best).\n2. Scramble eggs in a wok with a little oil. Remove.\n3. Stir fry diced onion, carrot, and peas in oil.\n4. Add rice and stir fry over high heat.\n5. Return eggs, add soy sauce and sesame oil.\n6. Toss and serve.',
3),
('00000000-0000-0000-0000-000000000014', 'Beef Tacos',
E'1. Brown ground beef with diced onion and garlic.\n2. Season with cumin, chili powder, salt, and pepper.\n3. Warm taco shells in oven.\n4. Fill shells with beef, shredded cheese, lettuce, and tomato.\n5. Top with sour cream and salsa.',
4),
('00000000-0000-0000-0000-000000000015', 'Oatmeal',
E'1. Bring water or milk to a boil in a saucepan.\n2. Stir in oats and reduce heat to medium.\n3. Cook, stirring occasionally, for 5 minutes.\n4. Remove from heat and let stand 2 minutes.\n5. Top with brown sugar, cinnamon, and fruit.',
2),
('00000000-0000-0000-0000-000000000016', 'Pasta Carbonara',
E'1. Cook spaghetti in salted boiling water until al dente.\n2. Fry diced pancetta until crispy.\n3. Whisk eggs, parmesan, and black pepper in a bowl.\n4. Drain pasta, reserving 1 cup pasta water.\n5. Off heat, toss pasta with pancetta, then egg mixture, adding pasta water to loosen.\n6. Serve immediately with extra parmesan.',
2),
('00000000-0000-0000-0000-000000000017', 'Vegetable Curry',
E'1. Sauté diced onion, garlic, and ginger in oil.\n2. Add curry powder, cumin, and turmeric; cook 1 minute.\n3. Add diced potato, cauliflower, and chickpeas.\n4. Pour in coconut milk and vegetable broth.\n5. Simmer 20 minutes until vegetables are tender.\n6. Serve over basmati rice.',
4),
('00000000-0000-0000-0000-000000000018', 'BLT Sandwich',
E'1. Cook bacon until crispy.\n2. Toast bread slices.\n3. Spread mayonnaise on both slices.\n4. Layer lettuce, tomato slices, and bacon.\n5. Season with salt and pepper.\n6. Close sandwich and slice in half.',
1),
('00000000-0000-0000-0000-000000000019', 'Lemon Garlic Shrimp',
E'1. Season shrimp with salt, pepper, and paprika.\n2. Melt butter in a pan over medium-high heat.\n3. Add minced garlic and cook 30 seconds.\n4. Add shrimp and cook 2 minutes per side.\n5. Squeeze lemon juice over shrimp.\n6. Garnish with parsley and serve over pasta or rice.',
2),
('00000000-0000-0000-0000-000000000020', 'Apple Pie',
E'1. Preheat oven to 425°F (220°C).\n2. Peel, core, and slice apples. Toss with sugar, cinnamon, and flour.\n3. Line pie dish with bottom crust.\n4. Fill with apple mixture and dot with butter.\n5. Cover with top crust, seal edges, and cut vents.\n6. Bake 4550 minutes until golden.',
8),
('00000000-0000-0000-0000-000000000021', 'Minestrone Soup',
E'1. Sauté onion, carrot, and celery in olive oil.\n2. Add garlic, diced tomatoes, and tomato paste.\n3. Pour in vegetable broth. Add kidney beans and zucchini.\n4. Simmer 20 minutes.\n5. Add small pasta and cook until tender.\n6. Season with salt, pepper, and basil.',
6),
('00000000-0000-0000-0000-000000000022', 'Quesadillas',
E'1. Place a flour tortilla in a dry pan over medium heat.\n2. Sprinkle shredded cheese on one half.\n3. Add diced chicken, peppers, and onion.\n4. Fold tortilla in half and cook until golden, about 2 minutes per side.\n5. Slice into wedges and serve with salsa and sour cream.',
2),
('00000000-0000-0000-0000-000000000023', 'Baked Salmon',
E'1. Preheat oven to 400°F (200°C).\n2. Place salmon fillets on a lined baking sheet.\n3. Brush with olive oil, lemon juice, garlic, and dill.\n4. Season with salt and pepper.\n5. Bake 1215 minutes until fish flakes easily.\n6. Serve with roasted vegetables.',
2),
('00000000-0000-0000-0000-000000000024', 'Hummus',
E'1. Drain and rinse chickpeas, reserving liquid.\n2. Blend chickpeas, tahini, lemon juice, garlic, and salt in a food processor.\n3. Add reserved liquid or water to reach desired consistency.\n4. Drizzle with olive oil and sprinkle with paprika.\n5. Serve with pita bread or vegetables.',
6),
('00000000-0000-0000-0000-000000000025', 'Beef Stew',
E'1. Brown beef chunks in oil in a Dutch oven. Remove.\n2. Sauté onion, carrot, and celery until softened.\n3. Add garlic, tomato paste, and flour; cook 1 minute.\n4. Return beef, add beef broth, potatoes, and thyme.\n5. Simmer covered for 1.5 hours until beef is tender.\n6. Season and serve.',
6),
('00000000-0000-0000-0000-000000000026', 'Smoothie Bowl',
E'1. Blend frozen banana, frozen berries, and milk until thick.\n2. Pour into a bowl.\n3. Top with granola, sliced fresh fruit, and honey.\n4. Add chia seeds and coconut flakes if desired.\n5. Serve immediately.',
1),
('00000000-0000-0000-0000-000000000027', 'Shakshuka',
E'1. Sauté diced onion and bell pepper in olive oil.\n2. Add garlic, cumin, paprika, and chili flakes; cook 1 minute.\n3. Pour in crushed tomatoes. Simmer 10 minutes.\n4. Make wells in the sauce and crack eggs into them.\n5. Cover and cook until whites are set but yolks are runny.\n6. Garnish with feta and parsley.',
2),
('00000000-0000-0000-0000-000000000028', 'Pesto Pasta',
E'1. Cook pasta in salted boiling water until al dente.\n2. Blend basil, pine nuts, parmesan, garlic, and olive oil into pesto.\n3. Drain pasta, reserving ½ cup pasta water.\n4. Toss pasta with pesto, adding pasta water to loosen.\n5. Season with salt and pepper.\n6. Serve with extra parmesan.',
3),
('00000000-0000-0000-0000-000000000029', 'Roast Chicken',
E'1. Preheat oven to 425°F (220°C).\n2. Pat chicken dry. Rub with butter, garlic, salt, pepper, and herbs.\n3. Stuff cavity with lemon halves and fresh thyme.\n4. Roast breast-side up for 1 hour 15 minutes.\n5. Rest 10 minutes before carving.\n6. Serve with pan juices.',
4),
('00000000-0000-0000-0000-000000000030', 'Chocolate Brownies',
E'1. Preheat oven to 350°F (175°C). Grease an 8x8 pan.\n2. Melt butter and chocolate together.\n3. Whisk in sugar, eggs, and vanilla.\n4. Fold in flour, cocoa powder, and salt.\n5. Pour into pan and bake 2530 minutes.\n6. Cool completely before cutting.',
16),
('00000000-0000-0000-0000-000000000031', 'Greek Salad',
E'1. Chop cucumber, tomatoes, and red onion.\n2. Add kalamata olives and cubed feta cheese.\n3. Drizzle with olive oil and red wine vinegar.\n4. Season with oregano, salt, and pepper.\n5. Toss gently and serve.',
2),
('00000000-0000-0000-0000-000000000032', 'Mashed Potatoes',
E'1. Peel and cube potatoes. Boil in salted water until tender, about 15 minutes.\n2. Drain and return to pot.\n3. Mash with butter and warm milk until smooth.\n4. Season generously with salt and pepper.\n5. Serve immediately.',
4),
('00000000-0000-0000-0000-000000000033', 'Lentil Soup',
E'1. Sauté diced onion, carrot, and celery in olive oil.\n2. Add garlic, cumin, and turmeric; cook 1 minute.\n3. Add rinsed red lentils and vegetable broth.\n4. Simmer 25 minutes until lentils are soft.\n5. Blend partially for a creamy texture.\n6. Season with lemon juice, salt, and pepper.',
4),
('00000000-0000-0000-0000-000000000034', 'Avocado Toast',
E'1. Toast bread slices until golden.\n2. Mash avocado with lemon juice, salt, and pepper.\n3. Spread avocado on toast.\n4. Top with red pepper flakes and everything bagel seasoning.\n5. Optional: add a poached egg on top.',
1),
('00000000-0000-0000-0000-000000000035', 'Chicken Tikka Masala',
E'1. Marinate chicken in yogurt, lemon juice, and spices for 1 hour.\n2. Grill or broil chicken until charred. Set aside.\n3. Sauté onion, garlic, and ginger in oil.\n4. Add tomato purée, cream, and spices. Simmer 10 minutes.\n5. Add chicken and simmer 10 more minutes.\n6. Serve over basmati rice with naan.',
4),
('00000000-0000-0000-0000-000000000036', 'Waffles',
E'1. Preheat waffle iron.\n2. Whisk flour, baking powder, sugar, and salt.\n3. Mix milk, eggs, and melted butter separately.\n4. Combine wet and dry ingredients until just mixed.\n5. Pour batter into waffle iron and cook until golden.\n6. Serve with butter and maple syrup.',
4),
('00000000-0000-0000-0000-000000000037', 'Tuna Salad',
E'1. Drain canned tuna and flake into a bowl.\n2. Add mayonnaise, diced celery, and red onion.\n3. Season with lemon juice, salt, and pepper.\n4. Mix well.\n5. Serve on bread, crackers, or lettuce cups.',
2),
('00000000-0000-0000-0000-000000000038', 'Mushroom Risotto',
E'1. Sauté diced onion in butter until soft.\n2. Add arborio rice and toast 1 minute.\n3. Add white wine and stir until absorbed.\n4. Add warm broth one ladle at a time, stirring constantly.\n5. Stir in sautéed mushrooms and parmesan.\n6. Season with salt, pepper, and fresh thyme.',
3),
('00000000-0000-0000-0000-000000000039', 'Blueberry Muffins',
E'1. Preheat oven to 375°F (190°C). Line muffin tin.\n2. Whisk flour, sugar, baking powder, and salt.\n3. Mix milk, egg, and melted butter.\n4. Combine wet and dry ingredients until just mixed.\n5. Fold in blueberries.\n6. Fill muffin cups ¾ full and bake 2025 minutes.',
12),
('00000000-0000-0000-0000-000000000040', 'Pad Thai',
E'1. Soak rice noodles in warm water 30 minutes. Drain.\n2. Stir fry shrimp or chicken in oil. Remove.\n3. Scramble eggs in the same pan.\n4. Add noodles, protein, bean sprouts, and green onions.\n5. Pour in pad thai sauce (fish sauce, tamarind, sugar).\n6. Toss and serve with lime, peanuts, and chili flakes.',
2),
('00000000-0000-0000-0000-000000000041', 'Corn Chowder',
E'1. Cook diced bacon until crispy. Remove.\n2. Sauté onion and celery in bacon fat.\n3. Add diced potato, corn kernels, and chicken broth.\n4. Simmer 15 minutes until potato is tender.\n5. Stir in heavy cream and season.\n6. Top with bacon and chives.',
4),
('00000000-0000-0000-0000-000000000042', 'Egg Fried Noodles',
E'1. Cook noodles per package instructions. Drain.\n2. Scramble eggs in a wok with oil. Remove.\n3. Stir fry garlic and green onion.\n4. Add noodles and toss over high heat.\n5. Return eggs, add soy sauce and sesame oil.\n6. Serve immediately.',
2),
('00000000-0000-0000-0000-000000000043', 'Caprese Salad',
E'1. Slice fresh mozzarella and tomatoes.\n2. Arrange alternating slices on a plate.\n3. Tuck fresh basil leaves between slices.\n4. Drizzle with olive oil and balsamic glaze.\n5. Season with salt and black pepper.',
2),
('00000000-0000-0000-0000-000000000044', 'Baked Mac and Cheese',
E'1. Preheat oven to 375°F (190°C).\n2. Cook macaroni until al dente. Drain.\n3. Make cheese sauce: melt butter, whisk in flour, add milk, stir in cheddar.\n4. Combine pasta and sauce. Pour into baking dish.\n5. Top with breadcrumbs and extra cheese.\n6. Bake 25 minutes until bubbly and golden.',
6),
('00000000-0000-0000-0000-000000000045', 'Chicken Fajitas',
E'1. Slice chicken breast into strips. Season with fajita spices.\n2. Cook chicken in a hot pan until cooked through. Remove.\n3. Sauté sliced bell peppers and onion until tender.\n4. Warm flour tortillas.\n5. Serve chicken and vegetables in tortillas.\n6. Top with sour cream, guacamole, and salsa.',
3),
('00000000-0000-0000-0000-000000000046', 'Overnight Oats',
E'1. Combine rolled oats, milk, and yogurt in a jar.\n2. Add chia seeds and honey. Stir well.\n3. Cover and refrigerate overnight.\n4. In the morning, top with fresh berries and nuts.\n5. Serve cold or warm briefly in microwave.',
1),
('00000000-0000-0000-0000-000000000047', 'Stuffed Bell Peppers',
E'1. Preheat oven to 375°F (190°C).\n2. Cut tops off peppers and remove seeds.\n3. Brown ground beef with onion and garlic.\n4. Mix with cooked rice, tomato sauce, and seasoning.\n5. Fill peppers with mixture. Top with cheese.\n6. Bake 3035 minutes until peppers are tender.',
4),
('00000000-0000-0000-0000-000000000048', 'Garlic Bread',
E'1. Preheat oven to 375°F (190°C).\n2. Mix softened butter with minced garlic, parsley, and salt.\n3. Slice baguette in half lengthwise.\n4. Spread garlic butter generously on cut sides.\n5. Bake 10 minutes, then broil 2 minutes until golden.\n6. Slice and serve immediately.',
4),
('00000000-0000-0000-0000-000000000049', 'Spinach and Feta Omelette',
E'1. Whisk eggs with salt and pepper.\n2. Melt butter in a non-stick pan over medium heat.\n3. Pour in eggs and cook until edges set.\n4. Add fresh spinach and crumbled feta to one half.\n5. Fold omelette in half and cook 1 more minute.\n6. Slide onto plate and serve.',
1),
('00000000-0000-0000-0000-000000000050', 'Chocolate Mousse',
E'1. Melt dark chocolate and let cool slightly.\n2. Whip heavy cream to soft peaks.\n3. Whisk egg yolks with sugar until pale.\n4. Fold chocolate into egg mixture.\n5. Fold in whipped cream gently.\n6. Chill 2 hours before serving.',
4);
-- ─────────────────────────────────────────────
-- RECIPE INGREDIENTS
-- ─────────────────────────────────────────────
INSERT INTO recipe_ingredients (recipe_id, item_name, quantity, unit) VALUES
-- Classic Pancakes
('00000000-0000-0000-0000-000000000001', 'flour', 2.0, 'cups'),
('00000000-0000-0000-0000-000000000001', 'baking powder', 2.0, 'tsp'),
('00000000-0000-0000-0000-000000000001', 'salt', 0.5, 'tsp'),
('00000000-0000-0000-0000-000000000001', 'sugar', 2.0, 'tbsp'),
('00000000-0000-0000-0000-000000000001', 'milk', 1.5, 'cups'),
('00000000-0000-0000-0000-000000000001', 'egg', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000001', 'butter', 2.0, 'tbsp'),
-- Scrambled Eggs
('00000000-0000-0000-0000-000000000002', 'eggs', 4.0, 'whole'),
('00000000-0000-0000-0000-000000000002', 'milk', 2.0, 'tbsp'),
('00000000-0000-0000-0000-000000000002', 'butter', 1.0, 'tbsp'),
-- Spaghetti Bolognese
('00000000-0000-0000-0000-000000000003', 'spaghetti', 400.0, 'g'),
('00000000-0000-0000-0000-000000000003', 'ground beef', 500.0, 'g'),
('00000000-0000-0000-0000-000000000003', 'onion', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000003', 'garlic', 3.0, 'whole'),
('00000000-0000-0000-0000-000000000003', 'crushed tomatoes', 400.0, 'g'),
('00000000-0000-0000-0000-000000000003', 'tomato paste', 2.0, 'tbsp'),
('00000000-0000-0000-0000-000000000003', 'parmesan', 50.0, 'g'),
-- Caesar Salad
('00000000-0000-0000-0000-000000000004', 'romaine lettuce', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000004', 'olive oil', 3.0, 'tbsp'),
('00000000-0000-0000-0000-000000000004', 'lemon', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000004', 'garlic', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000004', 'parmesan', 30.0, 'g'),
-- Chicken Stir Fry
('00000000-0000-0000-0000-000000000005', 'chicken breast', 400.0, 'g'),
('00000000-0000-0000-0000-000000000005', 'bell pepper', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000005', 'broccoli', 200.0, 'g'),
('00000000-0000-0000-0000-000000000005', 'soy sauce', 3.0, 'tbsp'),
('00000000-0000-0000-0000-000000000005', 'sesame oil', 1.0, 'tbsp'),
('00000000-0000-0000-0000-000000000005', 'rice', 2.0, 'cups'),
-- Banana Bread
('00000000-0000-0000-0000-000000000006', 'banana', 3.0, 'whole'),
('00000000-0000-0000-0000-000000000006', 'flour', 1.5, 'cups'),
('00000000-0000-0000-0000-000000000006', 'sugar', 0.75, 'cups'),
('00000000-0000-0000-0000-000000000006', 'butter', 0.3333, 'cups'),
('00000000-0000-0000-0000-000000000006', 'egg', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000006', 'baking soda', 1.0, 'tsp'),
-- Tomato Soup
('00000000-0000-0000-0000-000000000007', 'crushed tomatoes', 800.0, 'g'),
('00000000-0000-0000-0000-000000000007', 'onion', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000007', 'garlic', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000007', 'butter', 2.0, 'tbsp'),
('00000000-0000-0000-0000-000000000007', 'heavy cream', 0.5, 'cups'),
-- Grilled Cheese
('00000000-0000-0000-0000-000000000008', 'bread', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000008', 'cheddar cheese', 60.0, 'g'),
('00000000-0000-0000-0000-000000000008', 'butter', 1.0, 'tbsp'),
-- Chocolate Chip Cookies
('00000000-0000-0000-0000-000000000009', 'flour', 2.25, 'cups'),
('00000000-0000-0000-0000-000000000009', 'butter', 1.0, 'cups'),
('00000000-0000-0000-0000-000000000009', 'sugar', 0.75, 'cups'),
('00000000-0000-0000-0000-000000000009', 'brown sugar', 0.75, 'cups'),
('00000000-0000-0000-0000-000000000009', 'eggs', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000009', 'vanilla extract', 1.0, 'tsp'),
('00000000-0000-0000-0000-000000000009', 'baking soda', 1.0, 'tsp'),
('00000000-0000-0000-0000-000000000009', 'chocolate chips', 2.0, 'cups'),
-- Guacamole
('00000000-0000-0000-0000-000000000010', 'avocado', 3.0, 'whole'),
('00000000-0000-0000-0000-000000000010', 'lime', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000010', 'onion', 0.5, 'whole'),
('00000000-0000-0000-0000-000000000010', 'cilantro', 2.0, 'tbsp'),
-- French Toast
('00000000-0000-0000-0000-000000000011', 'bread', 4.0, 'whole'),
('00000000-0000-0000-0000-000000000011', 'eggs', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000011', 'milk', 0.25, 'cups'),
('00000000-0000-0000-0000-000000000011', 'butter', 1.0, 'tbsp'),
('00000000-0000-0000-0000-000000000011', 'cinnamon', 0.5, 'tsp'),
-- Chicken Soup
('00000000-0000-0000-0000-000000000012', 'chicken thighs', 600.0, 'g'),
('00000000-0000-0000-0000-000000000012', 'carrot', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000012', 'celery', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000012', 'onion', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000012', 'egg noodles', 200.0, 'g'),
-- Fried Rice
('00000000-0000-0000-0000-000000000013', 'rice', 2.0, 'cups'),
('00000000-0000-0000-0000-000000000013', 'eggs', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000013', 'soy sauce', 3.0, 'tbsp'),
('00000000-0000-0000-0000-000000000013', 'sesame oil', 1.0, 'tbsp'),
('00000000-0000-0000-0000-000000000013', 'onion', 1.0, 'whole'),
-- Beef Tacos
('00000000-0000-0000-0000-000000000014', 'ground beef', 400.0, 'g'),
('00000000-0000-0000-0000-000000000014', 'taco shells', 8.0, 'whole'),
('00000000-0000-0000-0000-000000000014', 'cheddar cheese', 100.0, 'g'),
('00000000-0000-0000-0000-000000000014', 'onion', 1.0, 'whole'),
-- Oatmeal
('00000000-0000-0000-0000-000000000015', 'rolled oats', 1.0, 'cups'),
('00000000-0000-0000-0000-000000000015', 'milk', 2.0, 'cups'),
('00000000-0000-0000-0000-000000000015', 'brown sugar', 2.0, 'tbsp'),
('00000000-0000-0000-0000-000000000015', 'cinnamon', 0.5, 'tsp'),
-- Pasta Carbonara
('00000000-0000-0000-0000-000000000016', 'spaghetti', 200.0, 'g'),
('00000000-0000-0000-0000-000000000016', 'eggs', 3.0, 'whole'),
('00000000-0000-0000-0000-000000000016', 'parmesan', 80.0, 'g'),
('00000000-0000-0000-0000-000000000016', 'pancetta', 150.0, 'g'),
-- Vegetable Curry
('00000000-0000-0000-0000-000000000017', 'potato', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000017', 'cauliflower', 0.5, 'whole'),
('00000000-0000-0000-0000-000000000017', 'chickpeas', 400.0, 'g'),
('00000000-0000-0000-0000-000000000017', 'coconut milk', 400.0, 'ml'),
('00000000-0000-0000-0000-000000000017', 'onion', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000017', 'garlic', 3.0, 'whole'),
('00000000-0000-0000-0000-000000000017', 'rice', 2.0, 'cups'),
-- BLT Sandwich
('00000000-0000-0000-0000-000000000018', 'bread', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000018', 'bacon', 4.0, 'whole'),
('00000000-0000-0000-0000-000000000018', 'lettuce', 2.0, 'whole'),
('00000000-0000-0000-0000-000000000018', 'tomato', 1.0, 'whole'),
('00000000-0000-0000-0000-000000000018', 'mayonnaise', 2.0, 'tbsp'),
-- Lemon Garlic Shrimp
('00000000-0000-0000-0000-000000000019', 'shrimp', 400.0, 'g'),
('00000000-0000-0000-0000-000000000019', 'butter', 3.0, 'tbsp'),
('00000000-0000-0000-0000-000000000019', 'garlic', 4.0, 'whole'),
('00000000-0000-0000-0000-000000000019', 'lemon', 1.0, 'whole'),
-- Apple Pie
('00000000-0000-0000-0000-000000000020', 'apple', 6.0, 'whole'),
('00000000-0000-0000-0000-000000000020', 'flour', 2.5, 'cups'),
('00000000-0000-0000-0000-000000000020', 'butter', 1.0, 'cups'),
('00000000-0000-0000-0000-000000000020', 'sugar', 0.75, 'cups'),
('00000000-0000-0000-0000-000000000020', 'cinnamon', 1.0, 'tsp');

View File

@@ -0,0 +1,22 @@
import type { Knex } from 'knex';
export async function up(knex: Knex): Promise<void> {
await knex.schema.createTable('pantry_items', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.uuid('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
table.string('item_name', 255).notNullable();
table.string('item_name_lower', 255).notNullable();
table.integer('quantity').notNullable().checkPositive();
table.timestamp('last_modified', { useTz: true }).defaultTo(knex.fn.now());
table.timestamp('created_at', { useTz: true }).defaultTo(knex.fn.now());
table.timestamp('updated_at', { useTz: true }).defaultTo(knex.fn.now());
});
await knex.raw(`CREATE UNIQUE INDEX idx_pantry_user_item ON pantry_items (user_id, item_name_lower)`);
await knex.raw(`CREATE INDEX idx_pantry_user_id ON pantry_items (user_id)`);
await knex.raw(`CREATE INDEX idx_pantry_last_modified ON pantry_items (user_id, last_modified)`);
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTableIfExists('pantry_items');
}

View File

@@ -0,0 +1,30 @@
import type { Knex } from 'knex';
export async function up(knex: Knex): Promise<void> {
await knex.schema.createTable('recipes', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.string('name', 255).notNullable();
table.text('instructions').notNullable();
table.integer('servings').notNullable().checkPositive();
table.timestamp('created_at', { useTz: true }).defaultTo(knex.fn.now());
table.timestamp('updated_at', { useTz: true }).defaultTo(knex.fn.now());
});
await knex.schema.createTable('recipe_ingredients', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.uuid('recipe_id').notNullable().references('id').inTable('recipes').onDelete('CASCADE');
table.string('item_name', 255).notNullable();
table.string('item_name_lower', 255).notNullable();
table.decimal('quantity', 10, 4).notNullable().checkPositive();
table.string('unit', 50).notNullable();
table.timestamp('created_at', { useTz: true }).defaultTo(knex.fn.now());
});
await knex.raw(`CREATE INDEX idx_recipe_ingredients_recipe ON recipe_ingredients (recipe_id)`);
await knex.raw(`CREATE INDEX idx_recipe_ingredients_name ON recipe_ingredients (item_name_lower)`);
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTableIfExists('recipe_ingredients');
await knex.schema.dropTableIfExists('recipes');
}

View File

@@ -0,0 +1,36 @@
import type { Knex } from 'knex';
export async function up(knex: Knex): Promise<void> {
await knex.schema.createTable('shopping_lists', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.uuid('user_id').notNullable().references('id').inTable('users').onDelete('CASCADE');
table.string('list_name', 255).notNullable();
table.timestamp('last_modified', { useTz: true }).defaultTo(knex.fn.now());
table.timestamp('created_at', { useTz: true }).defaultTo(knex.fn.now());
table.timestamp('updated_at', { useTz: true }).defaultTo(knex.fn.now());
});
await knex.schema.createTable('shopping_list_items', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.uuid('shopping_list_id').notNullable().references('id').inTable('shopping_lists').onDelete('CASCADE');
table.string('item_name', 255).notNullable();
table.string('item_name_lower', 255).notNullable();
table.decimal('quantity', 10, 4).notNullable().checkPositive();
table.string('unit', 50).notNullable();
table.boolean('checked_off').defaultTo(false);
table.timestamp('last_modified', { useTz: true }).defaultTo(knex.fn.now());
table.timestamp('created_at', { useTz: true }).defaultTo(knex.fn.now());
table.timestamp('updated_at', { useTz: true }).defaultTo(knex.fn.now());
});
await knex.raw(`CREATE INDEX idx_shopping_lists_user ON shopping_lists (user_id)`);
await knex.raw(`CREATE INDEX idx_shopping_lists_last_modified ON shopping_lists (user_id, last_modified)`);
await knex.raw(`CREATE INDEX idx_list_items_list ON shopping_list_items (shopping_list_id)`);
await knex.raw(`CREATE INDEX idx_list_items_name_unit ON shopping_list_items (shopping_list_id, item_name_lower, unit)`);
await knex.raw(`CREATE INDEX idx_list_items_last_modified ON shopping_list_items (shopping_list_id, last_modified)`);
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTableIfExists('shopping_list_items');
await knex.schema.dropTableIfExists('shopping_lists');
}

View File

@@ -0,0 +1,17 @@
import type { Knex } from 'knex';
export async function up(knex: Knex): Promise<void> {
await knex.schema.createTable('deleted_records', (table) => {
table.uuid('id').primary().defaultTo(knex.raw('gen_random_uuid()'));
table.uuid('user_id').notNullable();
table.string('table_name', 50).notNullable();
table.uuid('record_id').notNullable();
table.timestamp('deleted_at', { useTz: true }).defaultTo(knex.fn.now());
});
await knex.raw(`CREATE INDEX idx_deleted_records_user_time ON deleted_records (user_id, deleted_at)`);
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTableIfExists('deleted_records');
}

164
src/db/seeds/001_recipes.ts Normal file
View File

@@ -0,0 +1,164 @@
import type { Knex } from 'knex';
const recipes = [
{
name: 'Chocolate Chip Cookies',
servings: 24,
instructions: '1. Preheat oven to 375°F.\n2. Cream butter and sugars.\n3. Beat in eggs and vanilla.\n4. Mix in flour, baking soda, and salt.\n5. Stir in chocolate chips.\n6. Drop by spoonfuls onto baking sheet.\n7. Bake 9-11 minutes until golden.',
ingredients: [
{ item_name: 'All-Purpose Flour', quantity: 2.25, unit: 'cups' },
{ item_name: 'Butter', quantity: 1, unit: 'cups' },
{ item_name: 'Granulated Sugar', quantity: 0.75, unit: 'cups' },
{ item_name: 'Brown Sugar', quantity: 0.75, unit: 'cups' },
{ item_name: 'Eggs', quantity: 2, unit: 'pieces' },
{ item_name: 'Vanilla Extract', quantity: 1, unit: 'tsp' },
{ item_name: 'Baking Soda', quantity: 1, unit: 'tsp' },
{ item_name: 'Chocolate Chips', quantity: 2, unit: 'cups' },
],
},
{
name: 'Classic Pancakes',
servings: 4,
instructions: '1. Mix dry ingredients.\n2. Whisk wet ingredients separately.\n3. Combine wet and dry.\n4. Cook on greased griddle over medium heat.\n5. Flip when bubbles form.',
ingredients: [
{ item_name: 'All-Purpose Flour', quantity: 1.5, unit: 'cups' },
{ item_name: 'Milk', quantity: 1.25, unit: 'cups' },
{ item_name: 'Eggs', quantity: 1, unit: 'pieces' },
{ item_name: 'Butter', quantity: 3, unit: 'tbsp' },
{ item_name: 'Baking Powder', quantity: 2, unit: 'tsp' },
{ item_name: 'Granulated Sugar', quantity: 1, unit: 'tbsp' },
{ item_name: 'Salt', quantity: 1, unit: 'tsp' },
],
},
{
name: 'Spaghetti Bolognese',
servings: 4,
instructions: '1. Brown ground beef.\n2. Add onion and garlic, cook until soft.\n3. Add tomatoes and simmer 30 minutes.\n4. Cook pasta.\n5. Serve sauce over pasta.',
ingredients: [
{ item_name: 'Spaghetti', quantity: 400, unit: 'g' },
{ item_name: 'Ground Beef', quantity: 500, unit: 'g' },
{ item_name: 'Onion', quantity: 1, unit: 'whole' },
{ item_name: 'Garlic', quantity: 3, unit: 'cloves' },
{ item_name: 'Canned Tomatoes', quantity: 2, unit: 'can' },
{ item_name: 'Olive Oil', quantity: 2, unit: 'tbsp' },
{ item_name: 'Salt', quantity: 1, unit: 'tsp' },
],
},
{
name: 'Caesar Salad',
servings: 2,
instructions: '1. Wash and chop romaine.\n2. Make dressing with garlic, lemon, and parmesan.\n3. Toss lettuce with dressing.\n4. Top with croutons and extra parmesan.',
ingredients: [
{ item_name: 'Romaine Lettuce', quantity: 1, unit: 'whole' },
{ item_name: 'Parmesan Cheese', quantity: 0.5, unit: 'cups' },
{ item_name: 'Garlic', quantity: 2, unit: 'cloves' },
{ item_name: 'Lemon', quantity: 1, unit: 'whole' },
{ item_name: 'Olive Oil', quantity: 3, unit: 'tbsp' },
{ item_name: 'Croutons', quantity: 1, unit: 'cups' },
],
},
{
name: 'Banana Bread',
servings: 8,
instructions: '1. Preheat oven to 350°F.\n2. Mash bananas.\n3. Mix wet ingredients.\n4. Fold in dry ingredients.\n5. Pour into loaf pan.\n6. Bake 60-65 minutes.',
ingredients: [
{ item_name: 'Ripe Bananas', quantity: 3, unit: 'whole' },
{ item_name: 'All-Purpose Flour', quantity: 1.5, unit: 'cups' },
{ item_name: 'Butter', quantity: 0.33, unit: 'cups' },
{ item_name: 'Granulated Sugar', quantity: 0.75, unit: 'cups' },
{ item_name: 'Eggs', quantity: 1, unit: 'pieces' },
{ item_name: 'Baking Soda', quantity: 1, unit: 'tsp' },
{ item_name: 'Salt', quantity: 0.25, unit: 'tsp' },
],
},
{
name: 'Chicken Stir Fry',
servings: 4,
instructions: '1. Slice chicken and vegetables.\n2. Heat oil in wok.\n3. Cook chicken until done.\n4. Add vegetables and stir fry.\n5. Add sauce and toss.\n6. Serve over rice.',
ingredients: [
{ item_name: 'Chicken Breast', quantity: 500, unit: 'g' },
{ item_name: 'Bell Pepper', quantity: 2, unit: 'whole' },
{ item_name: 'Broccoli', quantity: 2, unit: 'cups' },
{ item_name: 'Soy Sauce', quantity: 3, unit: 'tbsp' },
{ item_name: 'Garlic', quantity: 3, unit: 'cloves' },
{ item_name: 'Vegetable Oil', quantity: 2, unit: 'tbsp' },
{ item_name: 'Rice', quantity: 2, unit: 'cups' },
],
},
{
name: 'Guacamole',
servings: 4,
instructions: '1. Halve and pit avocados.\n2. Scoop flesh into bowl.\n3. Mash with fork.\n4. Add lime juice, salt, onion, cilantro.\n5. Mix and adjust seasoning.',
ingredients: [
{ item_name: 'Avocado', quantity: 3, unit: 'whole' },
{ item_name: 'Lime', quantity: 1, unit: 'whole' },
{ item_name: 'Red Onion', quantity: 0.25, unit: 'whole' },
{ item_name: 'Cilantro', quantity: 2, unit: 'tbsp' },
{ item_name: 'Salt', quantity: 0.5, unit: 'tsp' },
],
},
{
name: 'Tomato Soup',
servings: 4,
instructions: '1. Sauté onion and garlic.\n2. Add tomatoes and broth.\n3. Simmer 20 minutes.\n4. Blend until smooth.\n5. Season with salt and pepper.',
ingredients: [
{ item_name: 'Canned Tomatoes', quantity: 2, unit: 'can' },
{ item_name: 'Onion', quantity: 1, unit: 'whole' },
{ item_name: 'Garlic', quantity: 2, unit: 'cloves' },
{ item_name: 'Vegetable Broth', quantity: 2, unit: 'cups' },
{ item_name: 'Olive Oil', quantity: 2, unit: 'tbsp' },
{ item_name: 'Salt', quantity: 1, unit: 'tsp' },
],
},
{
name: 'French Toast',
servings: 2,
instructions: '1. Whisk eggs, milk, and cinnamon.\n2. Dip bread slices.\n3. Cook on buttered pan until golden.\n4. Serve with maple syrup.',
ingredients: [
{ item_name: 'Bread', quantity: 4, unit: 'slices' },
{ item_name: 'Eggs', quantity: 2, unit: 'pieces' },
{ item_name: 'Milk', quantity: 0.25, unit: 'cups' },
{ item_name: 'Butter', quantity: 1, unit: 'tbsp' },
{ item_name: 'Cinnamon', quantity: 0.5, unit: 'tsp' },
],
},
{
name: 'Oatmeal',
servings: 1,
instructions: '1. Bring water or milk to boil.\n2. Add oats.\n3. Cook 5 minutes stirring occasionally.\n4. Top with fruit and honey.',
ingredients: [
{ item_name: 'Rolled Oats', quantity: 0.5, unit: 'cups' },
{ item_name: 'Milk', quantity: 1, unit: 'cups' },
{ item_name: 'Honey', quantity: 1, unit: 'tbsp' },
{ item_name: 'Salt', quantity: 1, unit: 'pinch' },
],
},
];
export async function seed(knex: Knex): Promise<void> {
// Clear existing
await knex('recipe_ingredients').delete();
await knex('recipes').delete();
for (const recipe of recipes) {
const [inserted] = await knex('recipes')
.insert({
name: recipe.name,
servings: recipe.servings,
instructions: recipe.instructions,
})
.returning('id');
const recipeId = inserted.id;
await knex('recipe_ingredients').insert(
recipe.ingredients.map((ing) => ({
recipe_id: recipeId,
item_name: ing.item_name,
item_name_lower: ing.item_name.toLowerCase(),
quantity: ing.quantity,
unit: ing.unit,
}))
);
}
}

View File

@@ -1,36 +0,0 @@
'use strict';
const cron = require('node-cron');
const { getDb } = require('../db/knex');
/**
* Hard-deletes all user accounts whose deletion_scheduled_at has passed.
* CASCADE constraints handle pantry_items, shopping_lists, and all child records.
* Runs daily at 02:00 UTC.
*/
async function hardDeleteExpiredAccounts() {
const db = getDb();
const now = new Date();
try {
const deleted = await db('users')
.whereNotNull('deletion_scheduled_at')
.where('deletion_scheduled_at', '<=', now)
.delete()
.returning('id');
console.log(
`[CRON] Hard-deleted ${deleted.length} expired account(s) at ${now.toISOString()}`
);
} catch (err) {
console.error('[CRON] Error during account hard-delete job:', err);
}
}
function startCronJobs() {
// Daily at 02:00 UTC
cron.schedule('0 2 * * *', hardDeleteExpiredAccounts, { timezone: 'UTC' });
console.log('[CRON] Account cleanup job scheduled (daily 02:00 UTC)');
}
module.exports = { startCronJobs, hardDeleteExpiredAccounts };

34
src/jobs/cronJobs.ts Normal file
View File

@@ -0,0 +1,34 @@
import cron from 'node-cron';
import db from '../db/connection';
import { logger } from '../utils/logger';
import { syncService } from '../services/syncService';
let lastCronRun: Date | null = null;
export function getLastCronRun(): Date | null {
return lastCronRun;
}
export function startCronJobs(): void {
// Daily at 2:00 AM UTC — hard-delete expired accounts
cron.schedule('0 2 * * *', async () => {
logger.info('Running daily account hard-delete job...');
try {
const result = await db('users')
.where('deletion_scheduled_at', '<=', db.fn.now())
.whereNotNull('deletion_scheduled_at')
.delete();
logger.info({ deletedCount: result }, 'Hard-delete job complete.');
// Clean up old tombstones
await syncService.cleanupTombstones();
lastCronRun = new Date();
} catch (err) {
logger.error({ err }, 'Hard-delete cron job failed.');
}
});
logger.info('Cron jobs registered.');
}

View File

@@ -1,41 +0,0 @@
'use strict';
const express = require('express');
const cors = require('cors');
const { requestLogger } = require('../middleware/requestLogger');
const { errorHandler } = require('../middleware/errorHandler');
const authRoutes = require('../routes/auth');
const pantryRoutes = require('../routes/pantry');
const recipeRoutes = require('../routes/recipes');
const shoppingRoutes = require('../routes/shopping');
const syncRoutes = require('../routes/sync');
const app = express();
app.use(cors());
app.use(express.json());
app.use(requestLogger);
// Health check — no auth required
app.get('/health', (req, res) => {
res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() });
});
app.use('/v1/auth', authRoutes);
app.use('/v1/pantry', pantryRoutes);
app.use('/v1/recipes', recipeRoutes);
app.use('/v1/shopping-lists', shoppingRoutes);
app.use('/v1/sync', syncRoutes);
// 404 handler for unmatched routes
app.use((req, res) => {
res.status(404).json({
error: 'Route not found.',
code: 'NOT_FOUND',
timestamp: new Date().toISOString(),
});
});
app.use(errorHandler);
module.exports = app;

View File

@@ -1,15 +0,0 @@
'use strict';
require('dotenv').config();
const app = require('./app');
const { startCronJobs } = require('../jobs/cleanup');
const config = require('../config');
const PORT = config.port;
app.listen(PORT, () => {
console.log(`[SERVER] Pantree API listening on port ${PORT} (${config.nodeEnv})`);
startCronJobs();
});
module.exports = app;

57
src/middleware/auth.ts Normal file
View File

@@ -0,0 +1,57 @@
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { config } from '../config/env';
import { createError } from './errorHandler';
import db from '../db/connection';
export interface AuthenticatedRequest extends Request {
userId?: string;
}
export async function authMiddleware(
req: AuthenticatedRequest,
_res: Response,
next: NextFunction
): Promise<void> {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return next(createError('Missing or invalid Authorization header.', 401, 'UNAUTHORIZED'));
}
const token = authHeader.slice(7);
let payload: { userId: string };
try {
payload = jwt.verify(token, config.jwtSecret) as { userId: string };
} catch {
return next(createError('Invalid or expired token.', 401, 'UNAUTHORIZED'));
}
// Verify user still exists (including soft-deleted — they may be hitting /restore-account)
const user = await db('users')
.where({ id: payload.userId })
.select('id', 'deleted_at', 'deletion_scheduled_at')
.first();
if (!user) {
return next(createError('Invalid or expired token.', 401, 'UNAUTHORIZED'));
}
// Soft-deleted accounts may only access the restore-account route
if (user.deleted_at) {
const isRestorePath =
req.path === '/auth/restore-account' ||
req.path.endsWith('/restore-account');
if (!isRestorePath) {
return next(createError('Account is pending deletion.', 403, 'FORBIDDEN'));
}
}
req.userId = payload.userId;
next();
} catch (err) {
next(err);
}
}

View File

@@ -1,40 +0,0 @@
'use strict';
const jwt = require('jsonwebtoken');
const config = require('../config');
const { AppError } = require('../utils/errors');
/**
* JWT authentication middleware.
* Validates the Bearer token on every protected route.
* Attaches decoded payload to req.user.
* The token is not trusted until verified — no exceptions.
*/
function authenticate(req, res, next) {
const authHeader = req.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return next(new AppError(401, 'UNAUTHORIZED', 'Missing or malformed Authorization header.'));
}
const token = authHeader.slice(7).trim();
if (!token) {
return next(new AppError(401, 'UNAUTHORIZED', 'Missing token.'));
}
let payload;
try {
payload = jwt.verify(token, config.jwt.secret);
} catch (err) {
return next(new AppError(401, 'UNAUTHORIZED', 'Invalid or expired token.'));
}
if (!payload.sub) {
return next(new AppError(401, 'UNAUTHORIZED', 'Malformed token payload.'));
}
req.user = payload;
return next();
}
module.exports = { authenticate };

View File

@@ -1,42 +0,0 @@
'use strict';
/**
* Central error handler.
* All errors thrown in route handlers or services arrive here.
* Known AppErrors are mapped to their HTTP status.
* Everything else is a 500.
*/
function errorHandler(err, req, res, next) { // eslint-disable-line no-unused-vars
const timestamp = new Date().toISOString();
// Structured application error
if (err.isAppError) {
return res.status(err.status).json({
error: err.message,
code: err.code,
...(err.extra || {}),
timestamp,
});
}
// Zod validation error (surfaced via validate() helper)
if (err.zodError) {
return res.status(400).json({
error: err.message || 'Validation failed.',
code: 'VALIDATION_ERROR',
details: err.issues,
timestamp,
});
}
// Unexpected error — log it, return generic 500
console.error(`[ERROR] [${req.requestId || '-'}] ${err.stack || err.message}`);
return res.status(500).json({
error: 'An unexpected error occurred.',
code: 'INTERNAL_ERROR',
timestamp,
});
}
module.exports = { errorHandler };

View File

@@ -0,0 +1,47 @@
import { Request, Response, NextFunction } from 'express';
import { ZodError } from 'zod';
import { logger } from '../utils/logger';
export interface AppError extends Error {
statusCode?: number;
code?: string;
details?: unknown;
}
export function createError(message: string, statusCode: number, code: string): AppError {
const err: AppError = new Error(message);
err.statusCode = statusCode;
err.code = code;
return err;
}
export function errorHandler(
err: AppError,
_req: Request,
res: Response,
_next: NextFunction
): void {
const timestamp = new Date().toISOString();
if (err instanceof ZodError) {
res.status(400).json({
error: err.errors.map((e) => `${e.path.join('.')}: ${e.message}`).join('; '),
code: 'VALIDATION_ERROR',
timestamp,
});
return;
}
const statusCode = err.statusCode ?? 500;
const code = err.code ?? 'INTERNAL_ERROR';
if (statusCode >= 500) {
logger.error({ err }, 'Unhandled server error');
}
res.status(statusCode).json({
error: statusCode >= 500 ? 'An internal error occurred.' : err.message,
code,
timestamp,
});
}

View File

@@ -1,16 +0,0 @@
'use strict';
const { v4: uuidv4 } = require('uuid');
/**
* Attaches a unique request ID to every inbound request.
* Logs method + path for basic observability.
*/
function requestLogger(req, res, next) {
req.requestId = uuidv4();
res.setHeader('X-Request-Id', req.requestId);
console.log(`[${new Date().toISOString()}] [${req.requestId}] ${req.method} ${req.path}`);
next();
}
module.exports = { requestLogger };

View File

@@ -1,103 +0,0 @@
'use strict';
const express = require('express');
const router = express.Router();
const authService = require('../services/authService');
const { authenticate } = require('../middleware/authenticate');
const { validate } = require('../utils/validate');
const {
signupSchema,
signinSchema,
googleAuthSchema,
passwordResetRequestSchema,
passwordResetConfirmSchema,
restoreAccountSchema,
} = require('../utils/validation');
// POST /v1/auth/signup
router.post('/signup', async (req, res, next) => {
try {
const data = validate(signupSchema, req.body);
const result = await authService.signup(data);
return res.status(201).json(result);
} catch (err) {
return next(err);
}
});
// POST /v1/auth/signin
router.post('/signin', async (req, res, next) => {
try {
const data = validate(signinSchema, req.body);
const result = await authService.signin(data);
return res.status(200).json(result);
} catch (err) {
return next(err);
}
});
// POST /v1/auth/google
router.post('/google', async (req, res, next) => {
try {
const data = validate(googleAuthSchema, req.body);
const result = await authService.googleAuth(data);
const status = result.is_new_user ? 201 : 200;
// Strip internal flag from response
const { is_new_user, ...response } = result; // eslint-disable-line no-unused-vars
return res.status(status).json(response);
} catch (err) {
return next(err);
}
});
// POST /v1/auth/password-reset — request reset email
router.post('/password-reset', async (req, res, next) => {
try {
const data = validate(passwordResetRequestSchema, req.body);
await authService.requestPasswordReset(data);
// Always 200 — never reveal whether email exists
return res.status(200).json({
message: 'If an account exists with this email, a reset link has been sent.',
timestamp: new Date().toISOString(),
});
} catch (err) {
return next(err);
}
});
// PUT /v1/auth/password-reset — complete reset with token
router.put('/password-reset', async (req, res, next) => {
try {
const data = validate(passwordResetConfirmSchema, req.body);
await authService.confirmPasswordReset(data);
return res.status(200).json({
message: 'Password updated successfully.',
timestamp: new Date().toISOString(),
});
} catch (err) {
return next(err);
}
});
// DELETE /v1/auth/account — soft-delete authenticated user's account
router.delete('/account', authenticate, async (req, res, next) => {
try {
await authService.deleteAccount(req.user.sub);
return res.status(204).send();
} catch (err) {
return next(err);
}
});
// POST /v1/auth/restore-account — restore soft-deleted account
router.post('/restore-account', async (req, res, next) => {
try {
const data = validate(restoreAccountSchema, req.body);
const result = await authService.restoreAccount(data);
return res.status(200).json(result);
} catch (err) {
return next(err);
}
});
module.exports = router;

134
src/routes/auth.ts Normal file
View File

@@ -0,0 +1,134 @@
import { Router, Response, NextFunction } from 'express';
import { authService } from '../services/authService';
import { AuthenticatedRequest, authMiddleware } from '../middleware/auth';
import {
signupSchema,
signinSchema,
googleAuthSchema,
passwordResetRequestSchema,
passwordResetConfirmSchema,
} from '../utils/validators';
const router = Router();
// POST /auth/signup
router.post('/signup', async (req, res: Response, next: NextFunction) => {
try {
const { email, password, name } = signupSchema.parse(req.body);
const result = await authService.signup(email, password, name);
res.status(201).json(result);
} catch (err) {
next(err);
}
});
// POST /auth/signin
router.post('/signin', async (req, res: Response, next: NextFunction) => {
try {
const { email, password } = signinSchema.parse(req.body);
const result = await authService.signin(email, password);
res.status(200).json(result);
} catch (err: unknown) {
if (
err instanceof Error &&
(err as { code?: string }).code === 'ACCOUNT_PENDING_DELETION'
) {
const appErr = err as { code?: string; statusCode?: number; deletion_scheduled_at?: string };
res.status(403).json({
error: err.message,
code: appErr.code,
deletion_scheduled_at: appErr.deletion_scheduled_at,
timestamp: new Date().toISOString(),
});
return;
}
next(err);
}
});
// POST /auth/google
router.post('/google', async (req, res: Response, next: NextFunction) => {
try {
const { id_token } = googleAuthSchema.parse(req.body);
const result = await authService.googleAuth(id_token);
const statusCode = result.is_new_user ? 201 : 200;
res.status(statusCode).json(result);
} catch (err: unknown) {
if (
err instanceof Error &&
(err as { code?: string }).code === 'ACCOUNT_PENDING_DELETION'
) {
const appErr = err as { code?: string; statusCode?: number; deletion_scheduled_at?: string };
res.status(403).json({
error: err.message,
code: appErr.code,
deletion_scheduled_at: appErr.deletion_scheduled_at,
timestamp: new Date().toISOString(),
});
return;
}
next(err);
}
});
// POST /auth/password-reset
router.post('/password-reset', async (req, res: Response, next: NextFunction) => {
try {
const { email } = passwordResetRequestSchema.parse(req.body);
await authService.requestPasswordReset(email);
res.status(200).json({
message: 'If an account exists with this email, a reset link has been sent.',
timestamp: new Date().toISOString(),
});
} catch (err) {
next(err);
}
});
// PUT /auth/password-reset
router.put('/password-reset', async (req, res: Response, next: NextFunction) => {
try {
const { token, new_password } = passwordResetConfirmSchema.parse(req.body);
await authService.confirmPasswordReset(token, new_password);
res.status(200).json({
message: 'Password updated successfully.',
timestamp: new Date().toISOString(),
});
} catch (err) {
next(err);
}
});
// DELETE /auth/account (protected)
router.delete(
'/account',
authMiddleware,
async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
await authService.deleteAccount(req.userId!);
res.status(204).send();
} catch (err) {
next(err);
}
}
);
// POST /auth/restore-account (protected)
router.post(
'/restore-account',
authMiddleware,
async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const user = await authService.restoreAccount(req.userId!);
res.status(200).json({
user,
message: 'Account restored successfully.',
timestamp: new Date().toISOString(),
});
} catch (err) {
next(err);
}
}
);
export default router;

View File

@@ -1,58 +0,0 @@
'use strict';
const express = require('express');
const router = express.Router();
const pantryService = require('../services/pantryService');
const { authenticate } = require('../middleware/authenticate');
const { validate } = require('../utils/validate');
const { addPantryItemSchema, updatePantryItemSchema } = require('../utils/validation');
// All pantry routes require authentication
router.use(authenticate);
// GET /v1/pantry
router.get('/', async (req, res, next) => {
try {
const items = await pantryService.getPantryItems(req.user.sub);
return res.status(200).json({
items,
synced_at: new Date().toISOString(),
});
} catch (err) {
return next(err);
}
});
// POST /v1/pantry
router.post('/', async (req, res, next) => {
try {
const data = validate(addPantryItemSchema, req.body);
const item = await pantryService.addPantryItem(req.user.sub, data);
return res.status(201).json({ item });
} catch (err) {
return next(err);
}
});
// PUT /v1/pantry/:item_id
router.put('/:item_id', async (req, res, next) => {
try {
const data = validate(updatePantryItemSchema, req.body);
const item = await pantryService.updatePantryItem(req.user.sub, req.params.item_id, data);
return res.status(200).json({ item });
} catch (err) {
return next(err);
}
});
// DELETE /v1/pantry/:item_id
router.delete('/:item_id', async (req, res, next) => {
try {
await pantryService.deletePantryItem(req.user.sub, req.params.item_id);
return res.status(204).send();
} catch (err) {
return next(err);
}
});
module.exports = router;

51
src/routes/pantry.ts Normal file
View File

@@ -0,0 +1,51 @@
import { Router, Response, NextFunction } from 'express';
import { authMiddleware, AuthenticatedRequest } from '../middleware/auth';
import { pantryService } from '../services/pantryService';
import { addPantryItemSchema, updatePantryItemSchema } from '../utils/validators';
const router = Router();
router.use(authMiddleware);
// GET /pantry
router.get('/', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const items = await pantryService.getItems(req.userId!);
res.status(200).json({ items, synced_at: new Date().toISOString() });
} catch (err) {
next(err);
}
});
// POST /pantry
router.post('/', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { item_name, quantity } = addPantryItemSchema.parse(req.body);
const item = await pantryService.addItem(req.userId!, item_name, quantity);
res.status(201).json({ item, synced_at: new Date().toISOString() });
} catch (err) {
next(err);
}
});
// PUT /pantry/:item_id
router.put('/:item_id', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { quantity } = updatePantryItemSchema.parse(req.body);
const item = await pantryService.updateItem(req.userId!, req.params.item_id, quantity);
res.status(200).json({ item, synced_at: new Date().toISOString() });
} catch (err) {
next(err);
}
});
// DELETE /pantry/:item_id
router.delete('/:item_id', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
await pantryService.deleteItem(req.userId!, req.params.item_id);
res.status(204).send();
} catch (err) {
next(err);
}
});
export default router;

View File

@@ -1,42 +0,0 @@
'use strict';
const express = require('express');
const router = express.Router();
const recipeService = require('../services/recipeService');
const { authenticate } = require('../middleware/authenticate');
const { validate } = require('../utils/validate');
const { recipeQuerySchema } = require('../utils/validation');
// All recipe routes require authentication
router.use(authenticate);
// GET /v1/recipes?filter=all|available|partial&scale=1|2|3
router.get('/', async (req, res, next) => {
try {
const query = validate(recipeQuerySchema, req.query);
const recipes = await recipeService.getRecipes(req.user.sub, query);
return res.status(200).json({
recipes,
synced_at: new Date().toISOString(),
});
} catch (err) {
return next(err);
}
});
// GET /v1/recipes/:recipe_id?scale=1|2|3
router.get('/:recipe_id', async (req, res, next) => {
try {
const query = validate(recipeQuerySchema, req.query);
const recipe = await recipeService.getRecipeById(
req.user.sub,
req.params.recipe_id,
query
);
return res.status(200).json({ recipe });
} catch (err) {
return next(err);
}
});
module.exports = router;

31
src/routes/recipes.ts Normal file
View File

@@ -0,0 +1,31 @@
import { Router, Response, NextFunction } from 'express';
import { authMiddleware, AuthenticatedRequest } from '../middleware/auth';
import { recipeService } from '../services/recipeService';
import { recipeQuerySchema, recipeDetailQuerySchema } from '../utils/validators';
const router = Router();
router.use(authMiddleware);
// GET /recipes
router.get('/', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { filter, page, limit, search } = recipeQuerySchema.parse(req.query);
const result = await recipeService.getRecipes(req.userId!, filter, page, limit, search);
res.status(200).json({ ...result, synced_at: new Date().toISOString() });
} catch (err) {
next(err);
}
});
// GET /recipes/:recipe_id
router.get('/:recipe_id', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { scale } = recipeDetailQuerySchema.parse(req.query);
const recipe = await recipeService.getRecipeById(req.params.recipe_id, req.userId!, scale);
res.status(200).json({ recipe });
} catch (err) {
next(err);
}
});
export default router;

View File

@@ -1,128 +0,0 @@
'use strict';
const express = require('express');
const router = express.Router();
const shoppingService = require('../services/shoppingService');
const { authenticate } = require('../middleware/authenticate');
const { validate } = require('../utils/validate');
const {
createShoppingListSchema,
addShoppingListItemSchema,
updateShoppingListItemSchema,
addRecipesToListSchema,
} = require('../utils/validation');
// All shopping list routes require authentication
router.use(authenticate);
// GET /v1/shopping-lists
router.get('/', async (req, res, next) => {
try {
const lists = await shoppingService.getShoppingLists(req.user.sub);
return res.status(200).json({
shopping_lists: lists,
synced_at: new Date().toISOString(),
});
} catch (err) {
return next(err);
}
});
// POST /v1/shopping-lists
router.post('/', async (req, res, next) => {
try {
const data = validate(createShoppingListSchema, req.body);
const list = await shoppingService.createShoppingList(req.user.sub, data);
return res.status(201).json({ shopping_list: list });
} catch (err) {
return next(err);
}
});
// GET /v1/shopping-lists/:list_id
router.get('/:list_id', async (req, res, next) => {
try {
const list = await shoppingService.getShoppingListById(
req.user.sub,
req.params.list_id
);
return res.status(200).json({
shopping_list: list,
synced_at: new Date().toISOString(),
});
} catch (err) {
return next(err);
}
});
// DELETE /v1/shopping-lists/:list_id
router.delete('/:list_id', async (req, res, next) => {
try {
await shoppingService.deleteShoppingList(req.user.sub, req.params.list_id);
return res.status(204).send();
} catch (err) {
return next(err);
}
});
// POST /v1/shopping-lists/:list_id/items
router.post('/:list_id/items', async (req, res, next) => {
try {
const data = validate(addShoppingListItemSchema, req.body);
const result = await shoppingService.addItemToList(
req.user.sub,
req.params.list_id,
data
);
return res.status(201).json(result);
} catch (err) {
return next(err);
}
});
// POST /v1/shopping-lists/:list_id/add-recipes
router.post('/:list_id/add-recipes', async (req, res, next) => {
try {
const data = validate(addRecipesToListSchema, req.body);
const result = await shoppingService.addRecipesToList(
req.user.sub,
req.params.list_id,
data
);
return res.status(201).json(result);
} catch (err) {
return next(err);
}
});
// PUT /v1/shopping-lists/:list_id/items/:item_id
router.put('/:list_id/items/:item_id', async (req, res, next) => {
try {
const data = validate(updateShoppingListItemSchema, req.body);
const item = await shoppingService.updateListItem(
req.user.sub,
req.params.list_id,
req.params.item_id,
data
);
return res.status(200).json({ item });
} catch (err) {
return next(err);
}
});
// DELETE /v1/shopping-lists/:list_id/items/:item_id
router.delete('/:list_id/items/:item_id', async (req, res, next) => {
try {
await shoppingService.deleteListItem(
req.user.sub,
req.params.list_id,
req.params.item_id
);
return res.status(204).send();
} catch (err) {
return next(err);
}
});
module.exports = router;

118
src/routes/shoppingLists.ts Normal file
View File

@@ -0,0 +1,118 @@
import { Router, Response, NextFunction } from 'express';
import { authMiddleware, AuthenticatedRequest } from '../middleware/auth';
import { shoppingListService } from '../services/shoppingListService';
import {
createShoppingListSchema,
addShoppingListItemSchema,
updateShoppingListItemSchema,
addRecipesToListSchema,
} from '../utils/validators';
const router = Router();
router.use(authMiddleware);
// GET /shopping-lists
router.get('/', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const lists = await shoppingListService.getLists(req.userId!);
res.status(200).json({ shopping_lists: lists, synced_at: new Date().toISOString() });
} catch (err) {
next(err);
}
});
// POST /shopping-lists
router.post('/', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { list_name } = createShoppingListSchema.parse(req.body);
const list = await shoppingListService.createList(req.userId!, list_name);
res.status(201).json({ shopping_list: list });
} catch (err) {
next(err);
}
});
// GET /shopping-lists/:list_id
router.get('/:list_id', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const list = await shoppingListService.getListById(req.params.list_id, req.userId!);
res.status(200).json({ shopping_list: list, synced_at: new Date().toISOString() });
} catch (err) {
next(err);
}
});
// DELETE /shopping-lists/:list_id
router.delete('/:list_id', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
await shoppingListService.deleteList(req.params.list_id, req.userId!);
res.status(204).send();
} catch (err) {
next(err);
}
});
// POST /shopping-lists/:list_id/items
router.post('/:list_id/items', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { item_name, quantity, unit } = addShoppingListItemSchema.parse(req.body);
const result = await shoppingListService.addItem(
req.params.list_id,
req.userId!,
item_name,
quantity,
unit
);
res.status(201).json(result);
} catch (err) {
next(err);
}
});
// POST /shopping-lists/:list_id/add-recipes
router.post('/:list_id/add-recipes', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { recipe_ids, scale_factor } = addRecipesToListSchema.parse(req.body);
const result = await shoppingListService.addRecipesToList(
req.params.list_id,
req.userId!,
recipe_ids,
scale_factor
);
res.status(201).json(result);
} catch (err) {
next(err);
}
});
// PUT /shopping-lists/:list_id/items/:item_id
router.put('/:list_id/items/:item_id', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const updates = updateShoppingListItemSchema.parse(req.body);
const item = await shoppingListService.updateItem(
req.params.list_id,
req.params.item_id,
req.userId!,
updates
);
res.status(200).json({ item, synced_at: new Date().toISOString() });
} catch (err) {
next(err);
}
});
// DELETE /shopping-lists/:list_id/items/:item_id
router.delete('/:list_id/items/:item_id', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
await shoppingListService.deleteItem(
req.params.list_id,
req.params.item_id,
req.userId!
);
res.status(204).send();
} catch (err) {
next(err);
}
});
export default router;

View File

@@ -1,23 +0,0 @@
'use strict';
const express = require('express');
const router = express.Router();
const syncService = require('../services/syncService');
const { authenticate } = require('../middleware/authenticate');
const { validate } = require('../utils/validate');
const { syncQuerySchema } = require('../utils/validation');
router.use(authenticate);
// GET /v1/sync?since=<ISO8601>
router.get('/', async (req, res, next) => {
try {
const query = validate(syncQuerySchema, req.query);
const data = await syncService.getSyncData(req.user.sub, query.since || null);
return res.status(200).json(data);
} catch (err) {
return next(err);
}
});
module.exports = router;

20
src/routes/sync.ts Normal file
View File

@@ -0,0 +1,20 @@
import { Router, Response, NextFunction } from 'express';
import { authMiddleware, AuthenticatedRequest } from '../middleware/auth';
import { syncService } from '../services/syncService';
import { syncQuerySchema } from '../utils/validators';
const router = Router();
router.use(authMiddleware);
// GET /sync
router.get('/', async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
try {
const { since } = syncQuerySchema.parse(req.query);
const delta = await syncService.getDelta(req.userId!, since);
res.status(200).json(delta);
} catch (err) {
next(err);
}
});
export default router;

24
src/server.ts Normal file
View File

@@ -0,0 +1,24 @@
import { createApp } from './app';
import { config } from './config/env';
import { logger } from './utils/logger';
import { startCronJobs } from './jobs/cronJobs';
import db from './db/connection';
async function main() {
// Verify DB connection
await db.raw('SELECT 1');
logger.info('Database connection established.');
const app = createApp();
app.listen(config.port, () => {
logger.info(`Pantree API running on port ${config.port}`);
});
startCronJobs();
}
main().catch((err) => {
logger.error({ err }, 'Failed to start server');
process.exit(1);
});

View File

@@ -1,294 +0,0 @@
'use strict';
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const { getDb } = require('../db/knex');
const { AppError } = require('../utils/errors');
const { issueToken } = require('../utils/jwt');
const config = require('../config');
const SALT_ROUNDS = 12;
/**
* Formats a user row for API responses.
* Never exposes password_hash, google_id, or internal fields.
*/
function formatUser(row) {
return {
id: row.id,
email: row.email,
name: row.name,
profile_picture_url: row.profile_picture_url || null,
email_verified: row.email_verified || false,
deleted_at: row.deleted_at || null,
created_at: row.created_at,
};
}
/**
* Register a new user with email + password.
* Rejects duplicate emails (case-insensitive).
*/
async function signup({ email, password, name }) {
const db = getDb();
const normalizedEmail = email.toLowerCase().trim();
const existing = await db('users')
.whereRaw('LOWER(email) = ?', [normalizedEmail])
.first();
if (existing) {
throw new AppError(409, 'CONFLICT', 'Email already registered.');
}
const password_hash = await bcrypt.hash(password, SALT_ROUNDS);
const [user] = await db('users')
.insert({
email: normalizedEmail,
password_hash,
name: name.trim(),
email_verified: false,
})
.returning('*');
const { token, expires_at } = issueToken(user);
return { user: formatUser(user), token, expires_at };
}
/**
* Sign in with email + password.
* Returns 401 for any credential failure — no enumeration.
* Returns 403 if account is soft-deleted within the 15-day window.
*/
async function signin({ email, password }) {
const db = getDb();
const normalizedEmail = email.toLowerCase().trim();
const user = await db('users')
.whereRaw('LOWER(email) = ?', [normalizedEmail])
.first();
// Constant-time path: always attempt bcrypt compare to prevent timing attacks
const dummyHash = '$2b$12$invalidhashfortimingprotection000000000000000000000000';
const hashToCompare = user && user.password_hash ? user.password_hash : dummyHash;
const valid = await bcrypt.compare(password, hashToCompare);
if (!user || !user.password_hash || !valid) {
throw new AppError(401, 'UNAUTHORIZED', 'Invalid email or password.');
}
if (user.deleted_at) {
// Within 15-day window — allow sign-in but signal pending deletion
if (user.deletion_scheduled_at && new Date(user.deletion_scheduled_at) > new Date()) {
throw new AppError(403, 'ACCOUNT_PENDING_DELETION', 'Account is pending deletion.', {
deletion_scheduled_at: user.deletion_scheduled_at,
can_restore: true,
});
}
// Past window — should have been hard-deleted by cron, but guard anyway
throw new AppError(401, 'UNAUTHORIZED', 'Invalid email or password.');
}
const { token, expires_at } = issueToken(user);
return { user: formatUser(user), token, expires_at };
}
/**
* Sign in or register via Google ID token.
* Decodes the JWT payload — production should verify with Google's tokeninfo endpoint.
*/
async function googleAuth({ id_token }) {
let payload;
try {
const parts = id_token.split('.');
if (parts.length !== 3) throw new Error('Malformed JWT');
// Add padding for base64url decode
const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
payload = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
} catch {
throw new AppError(401, 'INVALID_TOKEN', 'Google token verification failed.');
}
if (!payload.sub || !payload.email) {
throw new AppError(401, 'INVALID_TOKEN', 'Google token verification failed.');
}
const db = getDb();
let user = await db('users').where({ google_id: payload.sub }).first();
let is_new_user = false;
if (!user) {
// Check if email already exists — link accounts
user = await db('users')
.whereRaw('LOWER(email) = ?', [payload.email.toLowerCase()])
.first();
if (user) {
const [updated] = await db('users')
.where({ id: user.id })
.update({
google_id: payload.sub,
profile_picture_url: payload.picture || user.profile_picture_url,
})
.returning('*');
user = updated;
} else {
is_new_user = true;
const [created] = await db('users')
.insert({
email: payload.email.toLowerCase(),
name: payload.name || payload.email,
profile_picture_url: payload.picture || null,
google_id: payload.sub,
email_verified: true, // Google accounts are pre-verified
})
.returning('*');
user = created;
}
}
const { token, expires_at } = issueToken(user);
return { user: formatUser(user), token, expires_at, is_new_user };
}
/**
* Request a password reset email.
* Always returns success — never reveals whether the email exists.
*/
async function requestPasswordReset({ email }) {
const db = getDb();
const normalizedEmail = email.toLowerCase().trim();
const user = await db('users')
.whereRaw('LOWER(email) = ?', [normalizedEmail])
.whereNull('deleted_at')
.first();
// Silent return — no enumeration
if (!user || !user.password_hash) return;
// Generate a cryptographically random token
const rawToken = crypto.randomBytes(32).toString('hex');
const token_hash = crypto.createHash('sha256').update(rawToken).digest('hex');
const expires_at = new Date(Date.now() + config.resetTokenExpiryHours * 60 * 60 * 1000);
await db('password_reset_tokens').insert({
user_id: user.id,
token_hash,
expires_at,
});
// Production: send email with link containing rawToken
// await emailService.sendPasswordReset(user.email, rawToken);
console.log(`[PASSWORD RESET] raw_token=${rawToken} user_id=${user.id}`);
}
/**
* Complete a password reset using the token from the email link.
* Token is SHA-256 hashed before DB lookup — raw token never stored.
*/
async function confirmPasswordReset({ token, new_password }) {
const db = getDb();
const token_hash = crypto.createHash('sha256').update(token).digest('hex');
const record = await db('password_reset_tokens').where({ token_hash }).first();
if (!record || record.used_at) {
throw new AppError(401, 'INVALID_TOKEN', 'Token is invalid or has already been used.');
}
if (new Date(record.expires_at) < new Date()) {
throw new AppError(401, 'INVALID_TOKEN', 'Token has expired.');
}
const password_hash = await bcrypt.hash(new_password, SALT_ROUNDS);
await db.transaction(async (trx) => {
await trx('users').where({ id: record.user_id }).update({ password_hash });
await trx('password_reset_tokens')
.where({ id: record.id })
.update({ used_at: new Date() });
});
}
/**
* Soft-delete a user account.
* Sets deleted_at and deletion_scheduled_at (now + 15 days).
* Hard delete is handled by the daily cron job.
*/
async function deleteAccount(userId) {
const db = getDb();
const now = new Date();
const deletion_scheduled_at = new Date(
now.getTime() + config.accountDeletionDays * 24 * 60 * 60 * 1000
);
await db('users').where({ id: userId }).update({
deleted_at: now,
deletion_scheduled_at,
});
}
/**
* Restore a soft-deleted account within the 15-day window.
* Requires valid credentials — the token from the 403 signin response is used.
*/
async function restoreAccount({ email, password }) {
const db = getDb();
const normalizedEmail = email.toLowerCase().trim();
const user = await db('users')
.whereRaw('LOWER(email) = ?', [normalizedEmail])
.first();
const dummyHash = '$2b$12$invalidhashfortimingprotection000000000000000000000000';
const hashToCompare = user && user.password_hash ? user.password_hash : dummyHash;
const valid = await bcrypt.compare(password, hashToCompare);
if (!user || !user.password_hash || !valid) {
throw new AppError(401, 'UNAUTHORIZED', 'Invalid credentials.');
}
// Past the 15-day window
if (
user.deletion_scheduled_at &&
new Date(user.deletion_scheduled_at) <= new Date()
) {
throw new AppError(410, 'GONE', 'Account has been permanently deleted.');
}
// Account was never deleted
if (!user.deleted_at) {
const { token, expires_at } = issueToken(user);
return {
user: formatUser(user),
token,
expires_at,
message: 'Account is active.',
};
}
const [restored] = await db('users')
.where({ id: user.id })
.update({ deleted_at: null, deletion_scheduled_at: null })
.returning('*');
const { token, expires_at } = issueToken(restored);
return {
user: formatUser(restored),
token,
expires_at,
message: 'Account restored successfully.',
};
}
module.exports = {
signup,
signin,
googleAuth,
requestPasswordReset,
confirmPasswordReset,
deleteAccount,
restoreAccount,
};

268
src/services/authService.ts Normal file
View File

@@ -0,0 +1,268 @@
import bcrypt from 'bcrypt';
import crypto from 'crypto';
import { OAuth2Client } from 'google-auth-library';
import db from '../db/connection';
import { config } from '../config/env';
import { signToken } from '../utils/jwt';
import { createError } from '../middleware/errorHandler';
import { BCRYPT_ROUNDS, ACCOUNT_DELETION_DAYS, PASSWORD_RESET_EXPIRES_HOURS } from '../config/constants';
import { emailService } from './emailService';
const googleClient = new OAuth2Client(config.googleClientId);
function formatUser(user: Record<string, unknown>) {
return {
id: user.id,
email: user.email,
name: user.name,
profile_picture_url: user.profile_picture_url ?? null,
deleted_at: user.deleted_at ?? null,
created_at: user.created_at,
};
}
/**
* Derive a fast, constant-length lookup key from a raw reset token.
* HMAC-SHA256 with the JWT secret as the key — not a secret in itself,
* but prevents offline dictionary attacks against the stored hashes.
*/
function hmacToken(rawToken: string): string {
return crypto
.createHmac('sha256', config.jwtSecret)
.update(rawToken)
.digest('hex');
}
export const authService = {
async signup(email: string, password: string, name: string) {
const existing = await db('users')
.whereRaw('LOWER(email) = LOWER(?)', [email])
.first();
if (existing) {
throw createError('Email already registered.', 409, 'CONFLICT');
}
const password_hash = await bcrypt.hash(password, BCRYPT_ROUNDS);
const [user] = await db('users')
.insert({
email: email.toLowerCase(),
password_hash,
name,
})
.returning('*');
const { token, expiresAt } = signToken(user.id);
return {
user: formatUser(user),
token,
expires_at: expiresAt.toISOString(),
};
},
async signin(email: string, password: string) {
const user = await db('users')
.whereRaw('LOWER(email) = LOWER(?)', [email])
.first();
if (!user) {
throw createError('Invalid credentials.', 401, 'UNAUTHORIZED');
}
if (!user.password_hash) {
throw createError('Invalid credentials.', 401, 'UNAUTHORIZED');
}
const valid = await bcrypt.compare(password, user.password_hash);
if (!valid) {
throw createError('Invalid credentials.', 401, 'UNAUTHORIZED');
}
if (user.deleted_at) {
const err = createError('Account is pending deletion.', 403, 'ACCOUNT_PENDING_DELETION');
(err as Record<string, unknown>).deletion_scheduled_at = user.deletion_scheduled_at;
throw err;
}
const { token, expiresAt } = signToken(user.id);
return {
user: formatUser(user),
token,
expires_at: expiresAt.toISOString(),
};
},
async googleAuth(idToken: string) {
let ticket;
try {
ticket = await googleClient.verifyIdToken({
idToken,
audience: config.googleClientId,
});
} catch {
throw createError('Google token verification failed.', 401, 'INVALID_GOOGLE_TOKEN');
}
const payload = ticket.getPayload();
if (!payload || !payload.email) {
throw createError('Google token verification failed.', 401, 'INVALID_GOOGLE_TOKEN');
}
const { sub: googleId, email, name = '', picture } = payload;
// Check for existing user by google_id or email
let user = await db('users')
.where({ google_id: googleId })
.orWhereRaw('LOWER(email) = LOWER(?)', [email])
.first();
if (user && user.deleted_at) {
const err = createError('Account is pending deletion.', 403, 'ACCOUNT_PENDING_DELETION');
(err as Record<string, unknown>).deletion_scheduled_at = user.deletion_scheduled_at;
throw err;
}
let isNewUser = false;
if (!user) {
[user] = await db('users')
.insert({
email: email.toLowerCase(),
google_id: googleId,
name,
profile_picture_url: picture ?? null,
email_verified: true,
})
.returning('*');
isNewUser = true;
} else if (!user.google_id) {
// Link google account to existing email account
[user] = await db('users')
.where({ id: user.id })
.update({
google_id: googleId,
profile_picture_url: user.profile_picture_url ?? picture ?? null,
email_verified: true,
updated_at: db.fn.now(),
})
.returning('*');
}
const { token, expiresAt } = signToken(user.id);
return {
user: formatUser(user),
token,
expires_at: expiresAt.toISOString(),
is_new_user: isNewUser,
};
},
async requestPasswordReset(email: string) {
const user = await db('users')
.whereRaw('LOWER(email) = LOWER(?)', [email])
.whereNull('deleted_at')
.first();
// Always return success — prevents email enumeration
if (!user) return;
// Invalidate any existing unused tokens
await db('password_reset_tokens')
.where({ user_id: user.id })
.whereNull('used_at')
.update({ used_at: db.fn.now() });
const rawToken = crypto.randomBytes(32).toString('hex');
const token_hash = await bcrypt.hash(rawToken, BCRYPT_ROUNDS);
const lookup_hash = hmacToken(rawToken);
const expires_at = new Date(
Date.now() + PASSWORD_RESET_EXPIRES_HOURS * 60 * 60 * 1000
).toISOString();
await db('password_reset_tokens').insert({
user_id: user.id,
token_hash,
lookup_hash,
expires_at,
});
await emailService.sendPasswordReset(user.email, rawToken);
},
async confirmPasswordReset(rawToken: string, newPassword: string) {
// Derive the lookup key and fetch the single matching row — no full-table scan
const lookup_hash = hmacToken(rawToken);
const candidate = await db('password_reset_tokens')
.where({ lookup_hash })
.whereNull('used_at')
.where('expires_at', '>', db.fn.now())
.first();
if (!candidate) {
throw createError('Token is invalid or has expired.', 401, 'INVALID_TOKEN');
}
// bcrypt-verify the raw token against the stored hash
const valid = await bcrypt.compare(rawToken, candidate.token_hash);
if (!valid) {
throw createError('Token is invalid or has expired.', 401, 'INVALID_TOKEN');
}
const password_hash = await bcrypt.hash(newPassword, BCRYPT_ROUNDS);
await db.transaction(async (trx) => {
await trx('users')
.where({ id: candidate.user_id })
.update({ password_hash, updated_at: trx.fn.now() });
await trx('password_reset_tokens')
.where({ id: candidate.id })
.update({ used_at: trx.fn.now() });
});
},
async deleteAccount(userId: string) {
const deletionScheduledAt = new Date(
Date.now() + ACCOUNT_DELETION_DAYS * 24 * 60 * 60 * 1000
).toISOString();
await db('users').where({ id: userId }).update({
deleted_at: db.fn.now(),
deletion_scheduled_at: deletionScheduledAt,
updated_at: db.fn.now(),
});
},
async restoreAccount(userId: string) {
const user = await db('users').where({ id: userId }).first();
if (!user) {
throw createError('Account not found.', 410, 'GONE');
}
if (!user.deleted_at) {
// Not deleted — nothing to restore, just return user
return formatUser(user);
}
if (user.deletion_scheduled_at && new Date(user.deletion_scheduled_at) <= new Date()) {
throw createError('Account restoration window has expired.', 410, 'GONE');
}
const [restored] = await db('users')
.where({ id: userId })
.update({
deleted_at: null,
deletion_scheduled_at: null,
updated_at: db.fn.now(),
})
.returning('*');
return formatUser(restored);
},
};

View File

@@ -0,0 +1,29 @@
import { config } from '../config/env';
import { logger } from '../utils/logger';
export const emailService = {
async sendPasswordReset(toEmail: string, rawToken: string): Promise<void> {
const resetUrl = `${config.passwordResetUrl}?token=${rawToken}`;
if (config.isTest || !config.sendgridApiKey) {
logger.info({ toEmail, resetUrl }, 'Password reset email (not sent in test/dev without key)');
return;
}
try {
const sgMail = await import('@sendgrid/mail');
sgMail.default.setApiKey(config.sendgridApiKey);
await sgMail.default.send({
to: toEmail,
from: config.sendgridFromEmail,
subject: 'Reset your Pantree password',
text: `Click the link to reset your password: ${resetUrl}\n\nThis link expires in 1 hour.`,
html: `<p>Click the link to reset your password:</p><p><a href="${resetUrl}">${resetUrl}</a></p><p>This link expires in 1 hour.</p>`,
});
} catch (err) {
logger.error({ err }, 'Failed to send password reset email');
// Do not throw — prevents email enumeration via timing
}
},
};

View File

@@ -1,112 +0,0 @@
'use strict';
const { getDb } = require('../db/knex');
const { AppError } = require('../utils/errors');
function formatItem(row) {
return {
id: row.id,
item_name: row.item_name,
quantity: row.quantity,
last_modified: row.last_modified,
created_at: row.created_at,
};
}
/**
* Returns all pantry items for the authenticated user, ordered alphabetically.
*/
async function getPantryItems(userId) {
const db = getDb();
const items = await db('pantry_items')
.where({ user_id: userId })
.orderBy('item_name_lower', 'asc');
return items.map(formatItem);
}
/**
* Adds a new pantry item.
* Rejects with 409 if an item with the same name already exists (case-insensitive).
* Auto-merge is intentionally not performed — explicit > implicit.
*/
async function addPantryItem(userId, { item_name, quantity }) {
const db = getDb();
const trimmedName = item_name.trim();
const existing = await db('pantry_items')
.where({ user_id: userId })
.whereRaw('item_name_lower = LOWER(?)', [trimmedName])
.first();
if (existing) {
throw new AppError(
409,
'DUPLICATE_ITEM',
`'${existing.item_name}' already exists in your pantry.`,
{ existing_item: formatItem(existing) }
);
}
const [item] = await db('pantry_items')
.insert({ user_id: userId, item_name: trimmedName, quantity })
.returning('*');
return formatItem(item);
}
/**
* Updates the quantity of an existing pantry item.
* Server sets last_modified = NOW() — server clock is authoritative.
* Verifies ownership: item must belong to the requesting user.
*/
async function updatePantryItem(userId, itemId, { quantity }) {
const db = getDb();
const existing = await db('pantry_items')
.where({ id: itemId, user_id: userId })
.first();
if (!existing) {
throw new AppError(404, 'NOT_FOUND', 'Pantry item not found.');
}
const now = new Date();
const [item] = await db('pantry_items')
.where({ id: itemId, user_id: userId })
.update({ quantity, last_modified: now, updated_at: now })
.returning('*');
return formatItem(item);
}
/**
* Deletes a pantry item and records a tombstone for sync.
* Verifies ownership before deletion.
*/
async function deletePantryItem(userId, itemId) {
const db = getDb();
const existing = await db('pantry_items')
.where({ id: itemId, user_id: userId })
.first();
if (!existing) {
throw new AppError(404, 'NOT_FOUND', 'Pantry item not found.');
}
await db.transaction(async (trx) => {
await trx('pantry_items').where({ id: itemId, user_id: userId }).delete();
await trx('deleted_records').insert({
user_id: userId,
record_type: 'pantry_item',
record_id: itemId,
});
});
}
module.exports = {
getPantryItems,
addPantryItem,
updatePantryItem,
deletePantryItem,
};

View File

@@ -0,0 +1,73 @@
import db from '../db/connection';
import { createError } from '../middleware/errorHandler';
export const pantryService = {
async getItems(userId: string) {
const items = await db('pantry_items')
.where({ user_id: userId })
.select('id', 'item_name', 'quantity', 'last_modified', 'created_at')
.orderBy('item_name_lower', 'asc');
return items;
},
async addItem(userId: string, itemName: string, quantity: number) {
const existing = await db('pantry_items')
.where({ user_id: userId, item_name_lower: itemName.toLowerCase() })
.first();
if (existing) {
throw createError(
`Item '${itemName}' already exists in your pantry.`,
409,
'DUPLICATE_ITEM'
);
}
const [item] = await db('pantry_items')
.insert({
user_id: userId,
item_name: itemName,
item_name_lower: itemName.toLowerCase(),
quantity,
last_modified: db.fn.now(),
})
.returning(['id', 'item_name', 'quantity', 'last_modified', 'created_at']);
return item;
},
async updateItem(userId: string, itemId: string, quantity: number) {
const [item] = await db('pantry_items')
.where({ id: itemId, user_id: userId })
.update({
quantity,
last_modified: db.fn.now(),
updated_at: db.fn.now(),
})
.returning(['id', 'item_name', 'quantity', 'last_modified', 'created_at']);
if (!item) {
throw createError('Pantry item not found.', 404, 'NOT_FOUND');
}
return item;
},
async deleteItem(userId: string, itemId: string) {
const deleted = await db('pantry_items')
.where({ id: itemId, user_id: userId })
.delete();
if (!deleted) {
throw createError('Pantry item not found.', 404, 'NOT_FOUND');
}
// Record tombstone for sync
await db('deleted_records').insert({
user_id: userId,
table_name: 'pantry_items',
record_id: itemId,
});
},
};

View File

@@ -1,152 +0,0 @@
'use strict';
const { getDb } = require('../db/knex');
const { AppError } = require('../utils/errors');
/**
* Computes availability status for a recipe given the user's pantry.
* Matching is case-insensitive via item_name_lower.
*/
function computeAvailability(ingredients, pantryNameSet) {
const total = ingredients.length;
let available = 0;
const missing = [];
for (const ing of ingredients) {
if (pantryNameSet.has(ing.item_name_lower)) {
available++;
} else {
missing.push(ing.item_name);
}
}
let status;
if (total === 0) {
status = 'can_make';
} else if (available === total) {
status = 'can_make';
} else if (available > 0) {
status = 'partial';
} else {
status = 'missing_all';
}
return { status, available_count: available, total_count: total, missing_ingredients: missing };
}
/**
* Formats a recipe row with its ingredients for the list endpoint.
* Returns a summary (no instructions).
*/
function formatRecipeSummary(recipe, ingredients, pantryNameSet) {
const availability = computeAvailability(ingredients, pantryNameSet);
return {
id: recipe.id,
name: recipe.name,
servings: recipe.servings,
ingredient_count: ingredients.length,
availability,
};
}
/**
* Formats a full recipe detail with scaled ingredients and pantry status.
*/
function formatRecipeDetail(recipe, ingredients, pantryNameSet, scale) {
const scaledIngredients = ingredients.map((ing) => ({
id: ing.id,
item_name: ing.item_name,
quantity: parseFloat((parseFloat(ing.quantity) * scale).toFixed(4)),
unit: ing.unit,
in_pantry: pantryNameSet.has(ing.item_name_lower),
}));
const availability = computeAvailability(ingredients, pantryNameSet);
return {
id: recipe.id,
name: recipe.name,
servings: recipe.servings,
scaled_servings: recipe.servings * scale,
instructions: recipe.instructions,
ingredients: scaledIngredients,
availability,
};
}
/**
* Returns all recipes with pantry-based availability.
* Supports filter: 'all' | 'available' | 'partial'
* Supports scale: 1 | 2 | 3
*/
async function getRecipes(userId, { filter = 'all', scale = 1 }) {
const db = getDb();
// Fetch user's pantry as a Set of lowercase names for O(1) lookup
const pantryRows = await db('pantry_items')
.where({ user_id: userId })
.select('item_name_lower');
const pantryNameSet = new Set(pantryRows.map((r) => r.item_name_lower));
// Fetch all recipes with their ingredients in one query
const recipes = await db('recipes').orderBy('name', 'asc');
const recipeIds = recipes.map((r) => r.id);
let ingredientRows = [];
if (recipeIds.length > 0) {
ingredientRows = await db('recipe_ingredients')
.whereIn('recipe_id', recipeIds)
.orderBy('item_name_lower', 'asc');
}
// Group ingredients by recipe_id
const ingredientsByRecipe = {};
for (const ing of ingredientRows) {
if (!ingredientsByRecipe[ing.recipe_id]) {
ingredientsByRecipe[ing.recipe_id] = [];
}
ingredientsByRecipe[ing.recipe_id].push(ing);
}
let result = recipes.map((recipe) => {
const ingredients = ingredientsByRecipe[recipe.id] || [];
return formatRecipeSummary(recipe, ingredients, pantryNameSet);
});
// Apply filter
if (filter === 'available') {
result = result.filter((r) => r.availability.status === 'can_make');
} else if (filter === 'partial') {
result = result.filter(
(r) => r.availability.status === 'can_make' || r.availability.status === 'partial'
);
}
return result;
}
/**
* Returns full recipe detail for a single recipe.
* Verifies the recipe exists — recipes are global (not user-scoped).
*/
async function getRecipeById(userId, recipeId, { scale = 1 }) {
const db = getDb();
const recipe = await db('recipes').where({ id: recipeId }).first();
if (!recipe) {
throw new AppError(404, 'NOT_FOUND', 'Recipe not found.');
}
const ingredients = await db('recipe_ingredients')
.where({ recipe_id: recipeId })
.orderBy('item_name_lower', 'asc');
const pantryRows = await db('pantry_items')
.where({ user_id: userId })
.select('item_name_lower');
const pantryNameSet = new Set(pantryRows.map((r) => r.item_name_lower));
return formatRecipeDetail(recipe, ingredients, pantryNameSet, scale);
}
module.exports = { getRecipes, getRecipeById };

View File

@@ -0,0 +1,136 @@
import db from '../db/connection';
import { createError } from '../middleware/errorHandler';
import { DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT } from '../config/constants';
export const recipeService = {
async getRecipes(
userId: string,
filter: 'all' | 'can_make' | 'can_partially_make',
page: number,
limit: number,
search?: string
) {
const safeLimit = Math.min(limit, MAX_PAGE_LIMIT);
const offset = (page - 1) * safeLimit;
// Get user's pantry item names (lowercase)
const pantryItems = await db('pantry_items')
.where({ user_id: userId })
.pluck('item_name_lower');
const pantrySet = new Set(pantryItems);
// Base query
let query = db('recipes').select('recipes.*');
if (search) {
query = query.whereRaw('LOWER(recipes.name) LIKE ?', [`%${search.toLowerCase()}%`]);
}
const allRecipes = await query.orderBy('recipes.name', 'asc');
// Get ingredients for all recipes in one query
const recipeIds = allRecipes.map((r) => r.id);
const allIngredients = recipeIds.length
? await db('recipe_ingredients').whereIn('recipe_id', recipeIds)
: [];
const ingredientsByRecipe = new Map<string, typeof allIngredients>();
for (const ing of allIngredients) {
if (!ingredientsByRecipe.has(ing.recipe_id)) {
ingredientsByRecipe.set(ing.recipe_id, []);
}
ingredientsByRecipe.get(ing.recipe_id)!.push(ing);
}
// Compute availability for each recipe
const enriched = allRecipes.map((recipe) => {
const ingredients = ingredientsByRecipe.get(recipe.id) ?? [];
const ingredientCount = ingredients.length;
const availableCount = ingredients.filter((i) =>
pantrySet.has(i.item_name_lower)
).length;
const canMake = ingredientCount > 0 && availableCount === ingredientCount;
const canPartiallyMake = availableCount > 0 && availableCount < ingredientCount;
const availabilityPct =
ingredientCount > 0
? parseFloat(((availableCount / ingredientCount) * 100).toFixed(2))
: 0;
return {
id: recipe.id,
name: recipe.name,
servings: recipe.servings,
ingredient_count: ingredientCount,
available_ingredient_count: availableCount,
can_make: canMake,
can_partially_make: canPartiallyMake,
availability_percentage: availabilityPct,
};
});
// Apply filter
let filtered = enriched;
if (filter === 'can_make') {
filtered = enriched.filter((r) => r.can_make);
} else if (filter === 'can_partially_make') {
filtered = enriched.filter((r) => r.can_partially_make);
}
const total = filtered.length;
const totalPages = Math.ceil(total / safeLimit);
const paginated = filtered.slice(offset, offset + safeLimit);
return {
recipes: paginated,
pagination: {
page,
limit: safeLimit,
total,
total_pages: totalPages,
},
};
},
async getRecipeById(recipeId: string, userId: string, scaleFactor: number) {
const recipe = await db('recipes').where({ id: recipeId }).first();
if (!recipe) {
throw createError('Recipe not found.', 404, 'NOT_FOUND');
}
const ingredients = await db('recipe_ingredients').where({ recipe_id: recipeId });
const pantryItems = await db('pantry_items')
.where({ user_id: userId })
.pluck('item_name_lower');
const pantrySet = new Set(pantryItems);
const scaledIngredients = ingredients.map((ing) => ({
id: ing.id,
item_name: ing.item_name,
quantity: parseFloat((parseFloat(ing.quantity) * scaleFactor).toFixed(4)),
original_quantity: parseFloat(ing.quantity),
unit: ing.unit,
in_pantry: pantrySet.has(ing.item_name_lower),
}));
const availableCount = scaledIngredients.filter((i) => i.in_pantry).length;
const canMake =
scaledIngredients.length > 0 && availableCount === scaledIngredients.length;
return {
id: recipe.id,
name: recipe.name,
servings: recipe.servings,
scaled_servings: recipe.servings * scaleFactor,
scale_factor: scaleFactor,
instructions: recipe.instructions,
ingredients: scaledIngredients,
can_make: canMake,
available_ingredient_count: availableCount,
ingredient_count: scaledIngredients.length,
};
},
};

View File

@@ -0,0 +1,267 @@
import db from '../db/connection';
import { createError } from '../middleware/errorHandler';
async function getListForUser(listId: string, userId: string) {
const list = await db('shopping_lists')
.where({ id: listId, user_id: userId })
.first();
if (!list) {
throw createError('Shopping list not found.', 404, 'NOT_FOUND');
}
return list;
}
export const shoppingListService = {
async getLists(userId: string) {
const lists = await db('shopping_lists')
.where({ user_id: userId })
.select('id', 'list_name', 'last_modified', 'created_at')
.orderBy('created_at', 'desc');
// Get item counts in one query
const listIds = lists.map((l) => l.id);
const counts = listIds.length
? await db('shopping_list_items')
.whereIn('shopping_list_id', listIds)
.select('shopping_list_id')
.count('id as item_count')
.sum(db.raw('CASE WHEN checked_off THEN 1 ELSE 0 END as checked_count'))
.groupBy('shopping_list_id')
: [];
const countMap = new Map(
counts.map((c) => [
c.shopping_list_id,
{ item_count: parseInt(String(c.item_count), 10), checked_count: parseInt(String(c.checked_count), 10) },
])
);
return lists.map((l) => ({
...l,
item_count: countMap.get(l.id)?.item_count ?? 0,
checked_count: countMap.get(l.id)?.checked_count ?? 0,
}));
},
async createList(userId: string, listName: string) {
const [list] = await db('shopping_lists')
.insert({ user_id: userId, list_name: listName })
.returning(['id', 'list_name', 'last_modified', 'created_at']);
return { ...list, item_count: 0, checked_count: 0 };
},
async getListById(listId: string, userId: string) {
const list = await getListForUser(listId, userId);
const items = await db('shopping_list_items')
.where({ shopping_list_id: listId })
.select('id', 'item_name', 'quantity', 'unit', 'checked_off', 'last_modified')
.orderBy('item_name_lower', 'asc');
return {
id: list.id,
list_name: list.list_name,
last_modified: list.last_modified,
created_at: list.created_at,
items,
};
},
async deleteList(listId: string, userId: string) {
const deleted = await db('shopping_lists')
.where({ id: listId, user_id: userId })
.delete();
if (!deleted) {
throw createError('Shopping list not found.', 404, 'NOT_FOUND');
}
await db('deleted_records').insert({
user_id: userId,
table_name: 'shopping_lists',
record_id: listId,
});
},
async addItem(
listId: string,
userId: string,
itemName: string,
quantity: number,
unit: string
) {
await getListForUser(listId, userId);
const existing = await db('shopping_list_items')
.where({
shopping_list_id: listId,
item_name_lower: itemName.toLowerCase(),
unit,
})
.first();
if (existing) {
const previousQuantity = parseFloat(existing.quantity);
const newQuantity = previousQuantity + quantity;
const [updated] = await db('shopping_list_items')
.where({ id: existing.id })
.update({
quantity: newQuantity,
last_modified: db.fn.now(),
updated_at: db.fn.now(),
})
.returning(['id', 'item_name', 'quantity', 'unit', 'checked_off', 'last_modified']);
// Update list last_modified
await db('shopping_lists')
.where({ id: listId })
.update({ last_modified: db.fn.now(), updated_at: db.fn.now() });
return { item: updated, merged: true, previous_quantity: previousQuantity };
}
const [item] = await db('shopping_list_items')
.insert({
shopping_list_id: listId,
item_name: itemName,
item_name_lower: itemName.toLowerCase(),
quantity,
unit,
last_modified: db.fn.now(),
})
.returning(['id', 'item_name', 'quantity', 'unit', 'checked_off', 'last_modified']);
await db('shopping_lists')
.where({ id: listId })
.update({ last_modified: db.fn.now(), updated_at: db.fn.now() });
return { item, merged: false };
},
async addRecipesToList(
listId: string,
userId: string,
recipeIds: string[],
scaleFactor: number
) {
await getListForUser(listId, userId);
// Validate all recipes exist
const recipes = await db('recipes').whereIn('id', recipeIds).select('id');
if (recipes.length !== recipeIds.length) {
throw createError('One or more recipes not found.', 404, 'NOT_FOUND');
}
const ingredients = await db('recipe_ingredients').whereIn('recipe_id', recipeIds);
let itemsMerged = 0;
let itemsCreated = 0;
await db.transaction(async (trx) => {
for (const ing of ingredients) {
const scaledQty = parseFloat(ing.quantity) * scaleFactor;
const existing = await trx('shopping_list_items')
.where({
shopping_list_id: listId,
item_name_lower: ing.item_name_lower,
unit: ing.unit,
})
.first();
if (existing) {
await trx('shopping_list_items')
.where({ id: existing.id })
.update({
quantity: parseFloat(existing.quantity) + scaledQty,
last_modified: trx.fn.now(),
updated_at: trx.fn.now(),
});
itemsMerged++;
} else {
await trx('shopping_list_items').insert({
shopping_list_id: listId,
item_name: ing.item_name,
item_name_lower: ing.item_name_lower,
quantity: scaledQty,
unit: ing.unit,
last_modified: trx.fn.now(),
});
itemsCreated++;
}
}
await trx('shopping_lists')
.where({ id: listId })
.update({ last_modified: trx.fn.now(), updated_at: trx.fn.now() });
});
const updatedList = await this.getListById(listId, userId);
return {
shopping_list: updatedList,
recipes_added: recipeIds.length,
items_merged: itemsMerged,
items_created: itemsCreated,
};
},
async updateItem(
listId: string,
itemId: string,
userId: string,
updates: { quantity?: number; unit?: string; checked_off?: boolean }
) {
await getListForUser(listId, userId);
const updateData: Record<string, unknown> = {
last_modified: db.fn.now(),
updated_at: db.fn.now(),
};
if (updates.quantity !== undefined) updateData.quantity = updates.quantity;
if (updates.unit !== undefined) updateData.unit = updates.unit;
if (updates.checked_off !== undefined) updateData.checked_off = updates.checked_off;
const [item] = await db('shopping_list_items')
.where({ id: itemId, shopping_list_id: listId })
.update(updateData)
.returning(['id', 'item_name', 'quantity', 'unit', 'checked_off', 'last_modified']);
if (!item) {
throw createError('Shopping list item not found.', 404, 'NOT_FOUND');
}
await db('shopping_lists')
.where({ id: listId })
.update({ last_modified: db.fn.now(), updated_at: db.fn.now() });
return item;
},
async deleteItem(listId: string, itemId: string, userId: string) {
await getListForUser(listId, userId);
const deleted = await db('shopping_list_items')
.where({ id: itemId, shopping_list_id: listId })
.delete();
if (!deleted) {
throw createError('Shopping list item not found.', 404, 'NOT_FOUND');
}
await db('deleted_records').insert({
user_id: userId,
table_name: 'shopping_list_items',
record_id: itemId,
});
await db('shopping_lists')
.where({ id: listId })
.update({ last_modified: db.fn.now(), updated_at: db.fn.now() });
},
};

View File

@@ -1,340 +0,0 @@
'use strict';
const { getDb } = require('../db/knex');
const { AppError } = require('../utils/errors');
function formatListSummary(row) {
return {
id: row.id,
list_name: row.list_name,
item_count: parseInt(row.item_count || 0, 10),
checked_count: parseInt(row.checked_count || 0, 10),
last_modified: row.last_modified,
created_at: row.created_at,
};
}
function formatItem(row) {
return {
id: row.id,
item_name: row.item_name,
quantity: parseFloat(row.quantity),
unit: row.unit,
checked_off: row.checked_off,
last_modified: row.last_modified,
};
}
/**
* Returns all shopping lists for the user with item/checked counts.
*/
async function getShoppingLists(userId) {
const db = getDb();
const lists = await db('shopping_lists as sl')
.leftJoin('shopping_list_items as sli', 'sl.id', 'sli.shopping_list_id')
.where('sl.user_id', userId)
.groupBy('sl.id')
.select(
'sl.id',
'sl.list_name',
'sl.last_modified',
'sl.created_at',
db.raw('COUNT(sli.id) AS item_count'),
db.raw('COUNT(sli.id) FILTER (WHERE sli.checked_off = true) AS checked_count')
)
.orderBy('sl.created_at', 'desc');
return lists.map(formatListSummary);
}
/**
* Creates a new empty shopping list.
*/
async function createShoppingList(userId, { list_name }) {
const db = getDb();
const [list] = await db('shopping_lists')
.insert({ user_id: userId, list_name: list_name.trim() })
.returning('*');
return {
id: list.id,
list_name: list.list_name,
item_count: 0,
checked_count: 0,
last_modified: list.last_modified,
created_at: list.created_at,
};
}
/**
* Returns a shopping list with all its items.
* Verifies ownership.
*/
async function getShoppingListById(userId, listId) {
const db = getDb();
const list = await db('shopping_lists')
.where({ id: listId, user_id: userId })
.first();
if (!list) {
throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.');
}
const items = await db('shopping_list_items')
.where({ shopping_list_id: listId })
.orderBy('item_name_lower', 'asc');
return {
id: list.id,
list_name: list.list_name,
last_modified: list.last_modified,
created_at: list.created_at,
items: items.map(formatItem),
};
}
/**
* Deletes a shopping list and all its items.
* Records tombstones for sync.
* Verifies ownership.
*/
async function deleteShoppingList(userId, listId) {
const db = getDb();
const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first();
if (!list) {
throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.');
}
await db.transaction(async (trx) => {
const items = await trx('shopping_list_items')
.where({ shopping_list_id: listId })
.select('id');
for (const item of items) {
await trx('deleted_records').insert({
user_id: userId,
record_type: 'shopping_list_item',
record_id: item.id,
});
}
await trx('shopping_lists').where({ id: listId, user_id: userId }).delete();
await trx('deleted_records').insert({
user_id: userId,
record_type: 'shopping_list',
record_id: listId,
});
});
}
/**
* Adds an item to a shopping list.
* Merge logic: same name (case-insensitive) AND same unit → sum quantities.
* Different units → separate line items.
* Verifies list ownership.
*/
async function addItemToList(userId, listId, { item_name, quantity, unit }) {
const db = getDb();
const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first();
if (!list) {
throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.');
}
const trimmedName = item_name.trim();
const now = new Date();
const existing = await db('shopping_list_items')
.where({ shopping_list_id: listId, unit })
.whereRaw('item_name_lower = LOWER(?)', [trimmedName])
.first();
if (existing) {
const newQty = parseFloat((parseFloat(existing.quantity) + quantity).toFixed(4));
const previousQuantity = parseFloat(existing.quantity);
const [updated] = await db('shopping_list_items')
.where({ id: existing.id })
.update({ quantity: newQty, last_modified: now, updated_at: now })
.returning('*');
await db('shopping_lists')
.where({ id: listId })
.update({ last_modified: now, updated_at: now });
return { item: formatItem(updated), merged: true, previous_quantity: previousQuantity };
}
const [item] = await db('shopping_list_items')
.insert({ shopping_list_id: listId, item_name: trimmedName, quantity, unit })
.returning('*');
await db('shopping_lists')
.where({ id: listId })
.update({ last_modified: now, updated_at: now });
return { item: formatItem(item), merged: false };
}
/**
* Updates a shopping list item (quantity, unit, checked_off).
* All fields are optional — only provided fields are patched.
* Verifies list ownership and item membership.
*/
async function updateListItem(userId, listId, itemId, updates) {
const db = getDb();
const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first();
if (!list) {
throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.');
}
const item = await db('shopping_list_items')
.where({ id: itemId, shopping_list_id: listId })
.first();
if (!item) {
throw new AppError(404, 'NOT_FOUND', 'Shopping list item not found.');
}
const now = new Date();
const patch = { last_modified: now, updated_at: now };
if (updates.quantity !== undefined) patch.quantity = updates.quantity;
if (updates.unit !== undefined) patch.unit = updates.unit;
if (updates.checked_off !== undefined) patch.checked_off = updates.checked_off;
const [updated] = await db('shopping_list_items')
.where({ id: itemId })
.update(patch)
.returning('*');
await db('shopping_lists')
.where({ id: listId })
.update({ last_modified: now, updated_at: now });
return formatItem(updated);
}
/**
* Deletes a shopping list item and records a tombstone for sync.
* Verifies list ownership and item membership.
*/
async function deleteListItem(userId, listId, itemId) {
const db = getDb();
const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first();
if (!list) {
throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.');
}
const item = await db('shopping_list_items')
.where({ id: itemId, shopping_list_id: listId })
.first();
if (!item) {
throw new AppError(404, 'NOT_FOUND', 'Shopping list item not found.');
}
const now = new Date();
await db.transaction(async (trx) => {
await trx('shopping_list_items').where({ id: itemId }).delete();
await trx('deleted_records').insert({
user_id: userId,
record_type: 'shopping_list_item',
record_id: itemId,
});
await trx('shopping_lists')
.where({ id: listId })
.update({ last_modified: now, updated_at: now });
});
}
/**
* Adds ingredients from one or more recipes to a shopping list.
* Merge logic: same name (case-insensitive) + same unit → sum quantities.
* Different units → separate line items.
* scale: 1 | 2 | 3 — multiplies all ingredient quantities.
*/
async function addRecipesToList(userId, listId, { recipe_ids, scale = 1 }) {
const db = getDb();
const list = await db('shopping_lists').where({ id: listId, user_id: userId }).first();
if (!list) {
throw new AppError(404, 'NOT_FOUND', 'Shopping list not found.');
}
// Validate all recipes exist before touching the list
const recipes = await db('recipes').whereIn('id', recipe_ids);
if (recipes.length !== recipe_ids.length) {
throw new AppError(404, 'NOT_FOUND', 'One or more recipes not found.');
}
const recipeIngredients = await db('recipe_ingredients').whereIn('recipe_id', recipe_ids);
let itemsMerged = 0;
let itemsCreated = 0;
const now = new Date();
await db.transaction(async (trx) => {
for (const ing of recipeIngredients) {
const scaledQty = parseFloat((parseFloat(ing.quantity) * scale).toFixed(4));
const existing = await trx('shopping_list_items')
.where({ shopping_list_id: listId, unit: ing.unit })
.whereRaw('item_name_lower = LOWER(?)', [ing.item_name])
.first();
if (existing) {
const newQty = parseFloat((parseFloat(existing.quantity) + scaledQty).toFixed(4));
await trx('shopping_list_items')
.where({ id: existing.id })
.update({ quantity: newQty, last_modified: now, updated_at: now });
itemsMerged++;
} else {
await trx('shopping_list_items').insert({
shopping_list_id: listId,
item_name: ing.item_name,
quantity: scaledQty,
unit: ing.unit,
});
itemsCreated++;
}
}
await trx('shopping_lists')
.where({ id: listId })
.update({ last_modified: now, updated_at: now });
});
const updatedItems = await db('shopping_list_items')
.where({ shopping_list_id: listId })
.orderBy('item_name_lower', 'asc');
return {
shopping_list: {
id: list.id,
list_name: list.list_name,
last_modified: now,
items: updatedItems.map(formatItem),
},
recipes_added: recipes.length,
items_merged: itemsMerged,
items_created: itemsCreated,
};
}
module.exports = {
getShoppingLists,
createShoppingList,
getShoppingListById,
deleteShoppingList,
addItemToList,
updateListItem,
deleteListItem,
addRecipesToList,
};

View File

@@ -1,106 +0,0 @@
'use strict';
const { getDb } = require('../db/knex');
/**
* Returns all data modified since `since` timestamp.
* If `since` is null, returns everything (full sync).
* Includes tombstone records so the client can remove deleted items from cache.
*/
async function getSyncData(userId, since) {
const db = getDb();
const serverTimestamp = new Date().toISOString();
const isFullSync = !since;
// ── Pantry ──────────────────────────────────────────────────────────────────
let pantryQuery = db('pantry_items').where({ user_id: userId });
if (since) {
pantryQuery = pantryQuery.where('last_modified', '>', since);
}
const pantryItems = await pantryQuery.orderBy('item_name_lower', 'asc');
let deletedPantryIds = [];
if (since) {
const tombstones = await db('deleted_records')
.where({ user_id: userId, record_type: 'pantry_item' })
.where('deleted_at', '>', since)
.select('record_id');
deletedPantryIds = tombstones.map((r) => r.record_id);
}
// ── Shopping Lists ───────────────────────────────────────────────────────────
let listsQuery = db('shopping_lists').where({ user_id: userId });
if (since) {
listsQuery = listsQuery.where('last_modified', '>', since);
}
const lists = await listsQuery.orderBy('created_at', 'asc');
const listIds = lists.map((l) => l.id);
let listItems = [];
if (listIds.length > 0) {
listItems = await db('shopping_list_items')
.whereIn('shopping_list_id', listIds)
.orderBy('item_name_lower', 'asc');
}
// Group items by list
const itemsByList = {};
for (const item of listItems) {
if (!itemsByList[item.shopping_list_id]) {
itemsByList[item.shopping_list_id] = [];
}
itemsByList[item.shopping_list_id].push({
id: item.id,
item_name: item.item_name,
quantity: parseFloat(item.quantity),
unit: item.unit,
checked_off: item.checked_off,
last_modified: item.last_modified,
deleted: false,
});
}
let deletedListIds = [];
let deletedItemIds = [];
if (since) {
const deletedLists = await db('deleted_records')
.where({ user_id: userId, record_type: 'shopping_list' })
.where('deleted_at', '>', since)
.select('record_id');
deletedListIds = deletedLists.map((r) => r.record_id);
const deletedItems = await db('deleted_records')
.where({ user_id: userId, record_type: 'shopping_list_item' })
.where('deleted_at', '>', since)
.select('record_id');
deletedItemIds = deletedItems.map((r) => r.record_id);
}
return {
pantry: {
items: pantryItems.map((p) => ({
id: p.id,
item_name: p.item_name,
quantity: p.quantity,
last_modified: p.last_modified,
deleted: false,
})),
deleted_ids: deletedPantryIds,
},
shopping_lists: {
lists: lists.map((l) => ({
id: l.id,
list_name: l.list_name,
last_modified: l.last_modified,
deleted: false,
items: itemsByList[l.id] || [],
})),
deleted_list_ids: deletedListIds,
deleted_item_ids: deletedItemIds,
},
server_timestamp: serverTimestamp,
full_sync: isFullSync,
};
}
module.exports = { getSyncData };

View File

@@ -0,0 +1,75 @@
import db from '../db/connection';
import { TOMBSTONE_RETENTION_DAYS } from '../config/constants';
export const syncService = {
async getDelta(userId: string, since: string) {
const serverTimestamp = new Date().toISOString();
// Pantry: updated items
const updatedPantry = await db('pantry_items')
.where({ user_id: userId })
.where('last_modified', '>', since)
.select('id', 'item_name', 'quantity', 'last_modified');
// Pantry: deleted items
const deletedPantry = await db('deleted_records')
.where({ user_id: userId, table_name: 'pantry_items' })
.where('deleted_at', '>', since)
.pluck('record_id');
// Shopping lists: updated
const updatedLists = await db('shopping_lists')
.where({ user_id: userId })
.where('last_modified', '>', since)
.select('id', 'list_name', 'last_modified');
// For each updated list, get updated/deleted items
const listsWithItems = await Promise.all(
updatedLists.map(async (list) => {
const updatedItems = await db('shopping_list_items')
.where({ shopping_list_id: list.id })
.where('last_modified', '>', since)
.select('id', 'item_name', 'quantity', 'unit', 'checked_off', 'last_modified');
const deletedItems = await db('deleted_records')
.where({ user_id: userId, table_name: 'shopping_list_items' })
.where('deleted_at', '>', since)
.pluck('record_id');
return {
...list,
items: {
updated: updatedItems,
deleted: deletedItems,
},
};
})
);
// Deleted shopping lists
const deletedLists = await db('deleted_records')
.where({ user_id: userId, table_name: 'shopping_lists' })
.where('deleted_at', '>', since)
.pluck('record_id');
return {
server_timestamp: serverTimestamp,
pantry: {
updated: updatedPantry,
deleted: deletedPantry,
},
shopping_lists: {
updated: listsWithItems,
deleted: deletedLists,
},
};
},
async cleanupTombstones() {
const cutoff = new Date(
Date.now() - TOMBSTONE_RETENTION_DAYS * 24 * 60 * 60 * 1000
).toISOString();
await db('deleted_records').where('deleted_at', '<', cutoff).delete();
},
};

37
src/test/helpers.ts Normal file
View File

@@ -0,0 +1,37 @@
import db from '../db/connection';
import bcrypt from 'bcrypt';
export async function createTestUser(overrides: Partial<{
email: string;
password: string;
name: string;
deleted_at: string | null;
deletion_scheduled_at: string | null;
}> = {}) {
const email = overrides.email ?? `test_${Date.now()}@example.com`;
const password = overrides.password ?? 'password123';
const name = overrides.name ?? 'Test User';
const password_hash = await bcrypt.hash(password, 4); // Low rounds for test speed
const [user] = await db('users')
.insert({
email: email.toLowerCase(),
password_hash,
name,
deleted_at: overrides.deleted_at ?? null,
deletion_scheduled_at: overrides.deletion_scheduled_at ?? null,
})
.returning('*');
return { user, password };
}
export async function cleanupTestData() {
await db('deleted_records').delete();
await db('shopping_list_items').delete();
await db('shopping_lists').delete();
await db('pantry_items').delete();
await db('password_reset_tokens').delete();
await db('users').delete();
}

View File

@@ -0,0 +1,184 @@
import request from 'supertest';
import { createApp } from '../../app';
import db from '../../db/connection';
import { createTestUser, cleanupTestData } from '../helpers';
import { signToken } from '../../utils/jwt';
const app = createApp();
beforeEach(async () => {
await cleanupTestData();
});
afterAll(async () => {
await cleanupTestData();
await db.destroy();
});
describe('POST /v1/auth/signup', () => {
it('creates a new user and returns token', async () => {
const res = await request(app).post('/v1/auth/signup').send({
email: 'newuser@example.com',
password: 'password123',
name: 'New User',
});
expect(res.status).toBe(201);
expect(res.body.user.email).toBe('newuser@example.com');
expect(res.body.token).toBeDefined();
expect(res.body.expires_at).toBeDefined();
});
it('returns 409 for duplicate email', async () => {
await createTestUser({ email: 'dup@example.com' });
const res = await request(app).post('/v1/auth/signup').send({
email: 'dup@example.com',
password: 'password123',
name: 'Dup User',
});
expect(res.status).toBe(409);
expect(res.body.code).toBe('CONFLICT');
});
it('returns 400 for invalid email', async () => {
const res = await request(app).post('/v1/auth/signup').send({
email: 'not-an-email',
password: 'password123',
name: 'User',
});
expect(res.status).toBe(400);
expect(res.body.code).toBe('VALIDATION_ERROR');
});
it('returns 400 for short password', async () => {
const res = await request(app).post('/v1/auth/signup').send({
email: 'user@example.com',
password: 'short',
name: 'User',
});
expect(res.status).toBe(400);
});
});
describe('POST /v1/auth/signin', () => {
it('signs in with valid credentials', async () => {
await createTestUser({ email: 'signin@example.com', password: 'mypassword1' });
const res = await request(app).post('/v1/auth/signin').send({
email: 'signin@example.com',
password: 'mypassword1',
});
expect(res.status).toBe(200);
expect(res.body.token).toBeDefined();
});
it('returns 401 for wrong password', async () => {
await createTestUser({ email: 'wrong@example.com', password: 'correctpass1' });
const res = await request(app).post('/v1/auth/signin').send({
email: 'wrong@example.com',
password: 'wrongpassword1',
});
expect(res.status).toBe(401);
expect(res.body.code).toBe('UNAUTHORIZED');
});
it('returns 401 for non-existent user', async () => {
const res = await request(app).post('/v1/auth/signin').send({
email: 'nobody@example.com',
password: 'password123',
});
expect(res.status).toBe(401);
});
it('returns 403 for soft-deleted account', async () => {
const futureDate = new Date(Date.now() + 10 * 24 * 60 * 60 * 1000).toISOString();
await createTestUser({
email: 'deleted@example.com',
password: 'password123',
deleted_at: new Date().toISOString(),
deletion_scheduled_at: futureDate,
});
const res = await request(app).post('/v1/auth/signin').send({
email: 'deleted@example.com',
password: 'password123',
});
expect(res.status).toBe(403);
expect(res.body.code).toBe('ACCOUNT_PENDING_DELETION');
expect(res.body.deletion_scheduled_at).toBeDefined();
});
});
describe('DELETE /v1/auth/account', () => {
it('soft-deletes the authenticated user', async () => {
const { user } = await createTestUser();
const { token } = signToken(user.id);
const res = await request(app)
.delete('/v1/auth/account')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(204);
const updated = await db('users').where({ id: user.id }).first();
expect(updated.deleted_at).not.toBeNull();
expect(updated.deletion_scheduled_at).not.toBeNull();
});
it('returns 401 without token', async () => {
const res = await request(app).delete('/v1/auth/account');
expect(res.status).toBe(401);
});
});
describe('POST /v1/auth/restore-account', () => {
it('restores a soft-deleted account', async () => {
const futureDate = new Date(Date.now() + 10 * 24 * 60 * 60 * 1000).toISOString();
const { user } = await createTestUser({
deleted_at: new Date().toISOString(),
deletion_scheduled_at: futureDate,
});
const { token } = signToken(user.id);
// Temporarily bypass the auth middleware deleted_at check for restore
// by directly calling the endpoint (auth middleware allows restore-account path)
const res = await request(app)
.post('/v1/auth/restore-account')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.user.deleted_at).toBeNull();
});
});
describe('POST /v1/auth/password-reset', () => {
it('always returns 200 regardless of email existence', async () => {
const res = await request(app)
.post('/v1/auth/password-reset')
.send({ email: 'nonexistent@example.com' });
expect(res.status).toBe(200);
expect(res.body.message).toContain('If an account exists');
});
it('returns 400 for invalid email', async () => {
const res = await request(app)
.post('/v1/auth/password-reset')
.send({ email: 'not-valid' });
expect(res.status).toBe(400);
});
});
describe('GET /health', () => {
it('returns 200 with status ok', async () => {
const res = await request(app).get('/health');
expect(res.status).toBe(200);
expect(res.body.status).toBe('ok');
});
});

View File

@@ -0,0 +1,163 @@
import request from 'supertest';
import { createApp } from '../../app';
import db from '../../db/connection';
import { createTestUser, cleanupTestData } from '../helpers';
import { signToken } from '../../utils/jwt';
const app = createApp();
let userId: string;
let token: string;
beforeEach(async () => {
await cleanupTestData();
const { user } = await createTestUser();
userId = user.id;
token = signToken(userId).token;
});
afterAll(async () => {
await cleanupTestData();
await db.destroy();
});
describe('GET /v1/pantry', () => {
it('returns empty pantry for new user', async () => {
const res = await request(app)
.get('/v1/pantry')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.items).toEqual([]);
expect(res.body.synced_at).toBeDefined();
});
it('returns 401 without token', async () => {
const res = await request(app).get('/v1/pantry');
expect(res.status).toBe(401);
});
});
describe('POST /v1/pantry', () => {
it('adds a new pantry item', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 5 });
expect(res.status).toBe(201);
expect(res.body.item.item_name).toBe('Flour');
expect(res.body.item.quantity).toBe(5);
});
it('returns 409 for duplicate item (case-insensitive)', async () => {
await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 5 });
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 3 });
expect(res.status).toBe(409);
expect(res.body.code).toBe('DUPLICATE_ITEM');
});
it('returns 400 for invalid quantity', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 0 });
expect(res.status).toBe(400);
});
it('returns 400 for fractional quantity', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 1.5 });
expect(res.status).toBe(400);
});
});
describe('PUT /v1/pantry/:item_id', () => {
it('updates pantry item quantity', async () => {
const createRes = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Butter', quantity: 2 });
const itemId = createRes.body.item.id;
const res = await request(app)
.put(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${token}`)
.send({ quantity: 7 });
expect(res.status).toBe(200);
expect(res.body.item.quantity).toBe(7);
});
it('returns 404 for non-existent item', async () => {
const res = await request(app)
.put('/v1/pantry/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`)
.send({ quantity: 5 });
expect(res.status).toBe(404);
});
it('cannot update another user\'s item', async () => {
const { user: otherUser } = await createTestUser({ email: 'other@example.com' });
const otherToken = signToken(otherUser.id).token;
const createRes = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Sugar', quantity: 3 });
const itemId = createRes.body.item.id;
const res = await request(app)
.put(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${otherToken}`)
.send({ quantity: 10 });
expect(res.status).toBe(404);
});
});
describe('DELETE /v1/pantry/:item_id', () => {
it('deletes a pantry item', async () => {
const createRes = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Salt', quantity: 1 });
const itemId = createRes.body.item.id;
const res = await request(app)
.delete(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(204);
// Verify tombstone created
const tombstone = await db('deleted_records')
.where({ record_id: itemId, table_name: 'pantry_items' })
.first();
expect(tombstone).toBeDefined();
});
it('returns 404 for non-existent item', async () => {
const res = await request(app)
.delete('/v1/pantry/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
});
});

View File

@@ -0,0 +1,148 @@
import request from 'supertest';
import { createApp } from '../../app';
import db from '../../db/connection';
import { createTestUser, cleanupTestData } from '../helpers';
import { signToken } from '../../utils/jwt';
const app = createApp();
let userId: string;
let token: string;
beforeAll(async () => {
await cleanupTestData();
// Seed a test recipe
const [recipe] = await db('recipes')
.insert({
name: 'Test Cookies',
servings: 12,
instructions: 'Mix and bake.',
})
.returning('*');
await db('recipe_ingredients').insert([
{ recipe_id: recipe.id, item_name: 'Flour', item_name_lower: 'flour', quantity: 2, unit: 'cups' },
{ recipe_id: recipe.id, item_name: 'Sugar', item_name_lower: 'sugar', quantity: 1, unit: 'cups' },
{ recipe_id: recipe.id, item_name: 'Butter', item_name_lower: 'butter', quantity: 0.5, unit: 'cups' },
]);
});
beforeEach(async () => {
await db('pantry_items').delete();
await db('users').delete();
const { user } = await createTestUser();
userId = user.id;
token = signToken(userId).token;
});
afterAll(async () => {
await cleanupTestData();
await db.destroy();
});
describe('GET /v1/recipes', () => {
it('returns all recipes with pagination', async () => {
const res = await request(app)
.get('/v1/recipes')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(Array.isArray(res.body.recipes)).toBe(true);
expect(res.body.pagination).toBeDefined();
expect(res.body.synced_at).toBeDefined();
});
it('returns 401 without token', async () => {
const res = await request(app).get('/v1/recipes');
expect(res.status).toBe(401);
});
it('filters can_make correctly when pantry has all ingredients', async () => {
// Add all ingredients to pantry
await db('pantry_items').insert([
{ user_id: userId, item_name: 'Flour', item_name_lower: 'flour', quantity: 5 },
{ user_id: userId, item_name: 'Sugar', item_name_lower: 'sugar', quantity: 3 },
{ user_id: userId, item_name: 'Butter', item_name_lower: 'butter', quantity: 2 },
]);
const res = await request(app)
.get('/v1/recipes?filter=can_make')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
const testRecipe = res.body.recipes.find((r: { name: string }) => r.name === 'Test Cookies');
expect(testRecipe).toBeDefined();
expect(testRecipe.can_make).toBe(true);
});
it('filters can_partially_make correctly', async () => {
// Add only one ingredient
await db('pantry_items').insert([
{ user_id: userId, item_name: 'Flour', item_name_lower: 'flour', quantity: 5 },
]);
const res = await request(app)
.get('/v1/recipes?filter=can_partially_make')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
const testRecipe = res.body.recipes.find((r: { name: string }) => r.name === 'Test Cookies');
expect(testRecipe).toBeDefined();
expect(testRecipe.can_make).toBe(false);
});
it('returns 400 for invalid filter', async () => {
const res = await request(app)
.get('/v1/recipes?filter=invalid')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
});
describe('GET /v1/recipes/:recipe_id', () => {
it('returns recipe detail with scaling', async () => {
const recipe = await db('recipes').where({ name: 'Test Cookies' }).first();
const res = await request(app)
.get(`/v1/recipes/${recipe.id}?scale=2`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.recipe.scale_factor).toBe(2);
expect(res.body.recipe.scaled_servings).toBe(24);
const flourIng = res.body.recipe.ingredients.find((i: { item_name: string }) => i.item_name === 'Flour');
expect(flourIng.quantity).toBe(4); // 2 * 2
expect(flourIng.original_quantity).toBe(2);
});
it('returns 404 for non-existent recipe', async () => {
const res = await request(app)
.get('/v1/recipes/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
});
it('returns 400 for invalid scale factor', async () => {
const recipe = await db('recipes').where({ name: 'Test Cookies' }).first();
const res = await request(app)
.get(`/v1/recipes/${recipe.id}?scale=5`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
it('marks in_pantry correctly', async () => {
await db('pantry_items').insert([
{ user_id: userId, item_name: 'Flour', item_name_lower: 'flour', quantity: 5 },
]);
const recipe = await db('recipes').where({ name: 'Test Cookies' }).first();
const res = await request(app)
.get(`/v1/recipes/${recipe.id}`)
.set('Authorization', `Bearer ${token}`);
const flourIng = res.body.recipe.ingredients.find((i: { item_name: string }) => i.item_name === 'Flour');
const sugarIng = res.body.recipe.ingredients.find((i: { item_name: string }) => i.item_name === 'Sugar');
expect(flourIng.in_pantry).toBe(true);
expect(sugarIng.in_pantry).toBe(false);
});
});

View File

@@ -0,0 +1,277 @@
import request from 'supertest';
import { createApp } from '../../app';
import db from '../../db/connection';
import { createTestUser, cleanupTestData } from '../helpers';
import { signToken } from '../../utils/jwt';
const app = createApp();
let userId: string;
let token: string;
beforeEach(async () => {
await cleanupTestData();
const { user } = await createTestUser();
userId = user.id;
token = signToken(userId).token;
});
afterAll(async () => {
await cleanupTestData();
await db.destroy();
});
async function createList(name = 'Test List') {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: name });
return res.body.shopping_list;
}
describe('GET /v1/shopping-lists', () => {
it('returns empty list for new user', async () => {
const res = await request(app)
.get('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.shopping_lists).toEqual([]);
});
});
describe('POST /v1/shopping-lists', () => {
it('creates a new shopping list', async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: 'Groceries' });
expect(res.status).toBe(201);
expect(res.body.shopping_list.list_name).toBe('Groceries');
expect(res.body.shopping_list.item_count).toBe(0);
});
it('returns 400 for empty list name', async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: '' });
expect(res.status).toBe(400);
});
});
describe('GET /v1/shopping-lists/:list_id', () => {
it('returns list with items', async () => {
const list = await createList();
const res = await request(app)
.get(`/v1/shopping-lists/${list.id}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.shopping_list.id).toBe(list.id);
expect(res.body.shopping_list.items).toEqual([]);
});
it('returns 404 for non-existent list', async () => {
const res = await request(app)
.get('/v1/shopping-lists/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
});
it('cannot access another user\'s list', async () => {
const { user: other } = await createTestUser({ email: 'other2@example.com' });
const otherToken = signToken(other.id).token;
const list = await createList();
const res = await request(app)
.get(`/v1/shopping-lists/${list.id}`)
.set('Authorization', `Bearer ${otherToken}`);
expect(res.status).toBe(404);
});
});
describe('POST /v1/shopping-lists/:list_id/items', () => {
it('adds an item to the list', async () => {
const list = await createList();
const res = await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Milk', quantity: 2, unit: 'cups' });
expect(res.status).toBe(201);
expect(res.body.item.item_name).toBe('Milk');
expect(res.body.merged).toBe(false);
});
it('merges items with same name and unit', async () => {
const list = await createList();
await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Milk', quantity: 2, unit: 'cups' });
const res = await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'milk', quantity: 1, unit: 'cups' });
expect(res.status).toBe(201);
expect(res.body.merged).toBe(true);
expect(parseFloat(res.body.item.quantity)).toBe(3);
expect(res.body.previous_quantity).toBe(2);
});
it('does NOT merge items with same name but different unit', async () => {
const list = await createList();
await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 2, unit: 'cups' });
const res = await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 250, unit: 'g' });
expect(res.status).toBe(201);
expect(res.body.merged).toBe(false);
const listRes = await request(app)
.get(`/v1/shopping-lists/${list.id}`)
.set('Authorization', `Bearer ${token}`);
expect(listRes.body.shopping_list.items.length).toBe(2);
});
it('returns 400 for invalid unit', async () => {
const list = await createList();
const res = await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Milk', quantity: 2, unit: 'gallons' });
expect(res.status).toBe(400);
});
});
describe('PUT /v1/shopping-lists/:list_id/items/:item_id', () => {
it('updates item checked_off status', async () => {
const list = await createList();
const addRes = await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Eggs', quantity: 6, unit: 'pieces' });
const itemId = addRes.body.item.id;
const res = await request(app)
.put(`/v1/shopping-lists/${list.id}/items/${itemId}`)
.set('Authorization', `Bearer ${token}`)
.send({ checked_off: true });
expect(res.status).toBe(200);
expect(res.body.item.checked_off).toBe(true);
});
it('returns 400 when no fields provided', async () => {
const list = await createList();
const addRes = await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Eggs', quantity: 6, unit: 'pieces' });
const itemId = addRes.body.item.id;
const res = await request(app)
.put(`/v1/shopping-lists/${list.id}/items/${itemId}`)
.set('Authorization', `Bearer ${token}`)
.send({});
expect(res.status).toBe(400);
});
});
describe('DELETE /v1/shopping-lists/:list_id', () => {
it('deletes a shopping list', async () => {
const list = await createList();
const res = await request(app)
.delete(`/v1/shopping-lists/${list.id}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(204);
});
it('returns 404 for non-existent list', async () => {
const res = await request(app)
.delete('/v1/shopping-lists/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
});
});
describe('DELETE /v1/shopping-lists/:list_id/items/:item_id', () => {
it('deletes an item from the list', async () => {
const list = await createList();
const addRes = await request(app)
.post(`/v1/shopping-lists/${list.id}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Butter', quantity: 1, unit: 'cups' });
const itemId = addRes.body.item.id;
const res = await request(app)
.delete(`/v1/shopping-lists/${list.id}/items/${itemId}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(204);
});
});
describe('POST /v1/shopping-lists/:list_id/add-recipes', () => {
it('adds recipe ingredients to list', async () => {
const [recipe] = await db('recipes')
.insert({ name: 'Simple Recipe', servings: 2, instructions: 'Cook it.' })
.returning('*');
await db('recipe_ingredients').insert([
{ recipe_id: recipe.id, item_name: 'Flour', item_name_lower: 'flour', quantity: 1, unit: 'cups' },
{ recipe_id: recipe.id, item_name: 'Water', item_name_lower: 'water', quantity: 0.5, unit: 'cups' },
]);
const list = await createList();
const res = await request(app)
.post(`/v1/shopping-lists/${list.id}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [recipe.id], scale_factor: 2 });
expect(res.status).toBe(201);
expect(res.body.recipes_added).toBe(1);
expect(res.body.items_created).toBe(2);
const flourItem = res.body.shopping_list.items.find((i: { item_name: string }) => i.item_name === 'Flour');
expect(parseFloat(flourItem.quantity)).toBe(2); // 1 * scale 2
});
it('returns 400 for empty recipe_ids', async () => {
const list = await createList();
const res = await request(app)
.post(`/v1/shopping-lists/${list.id}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [] });
expect(res.status).toBe(400);
});
it('returns 404 for non-existent recipe', async () => {
const list = await createList();
const res = await request(app)
.post(`/v1/shopping-lists/${list.id}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: ['00000000-0000-0000-0000-000000000000'] });
expect(res.status).toBe(404);
});
});

View File

@@ -0,0 +1,87 @@
import request from 'supertest';
import { createApp } from '../../app';
import db from '../../db/connection';
import { createTestUser, cleanupTestData } from '../helpers';
import { signToken } from '../../utils/jwt';
const app = createApp();
let userId: string;
let token: string;
beforeEach(async () => {
await cleanupTestData();
const { user } = await createTestUser();
userId = user.id;
token = signToken(userId).token;
});
afterAll(async () => {
await cleanupTestData();
await db.destroy();
});
describe('GET /v1/sync', () => {
it('returns delta since epoch (full sync)', async () => {
// Add a pantry item
await db('pantry_items').insert({
user_id: userId,
item_name: 'Flour',
item_name_lower: 'flour',
quantity: 5,
});
const res = await request(app)
.get('/v1/sync?since=1970-01-01T00:00:00.000Z')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.server_timestamp).toBeDefined();
expect(res.body.pantry.updated.length).toBe(1);
expect(res.body.pantry.updated[0].item_name).toBe('Flour');
expect(Array.isArray(res.body.pantry.deleted)).toBe(true);
expect(Array.isArray(res.body.shopping_lists.updated)).toBe(true);
expect(Array.isArray(res.body.shopping_lists.deleted)).toBe(true);
});
it('returns only items modified since timestamp', async () => {
const since = new Date().toISOString();
// Wait a tick then add item
await new Promise((r) => setTimeout(r, 10));
await db('pantry_items').insert({
user_id: userId,
item_name: 'Sugar',
item_name_lower: 'sugar',
quantity: 2,
});
const res = await request(app)
.get(`/v1/sync?since=${encodeURIComponent(since)}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.pantry.updated.length).toBe(1);
expect(res.body.pantry.updated[0].item_name).toBe('Sugar');
});
it('returns 400 for missing since parameter', async () => {
const res = await request(app)
.get('/v1/sync')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
it('returns 400 for invalid since parameter', async () => {
const res = await request(app)
.get('/v1/sync?since=not-a-date')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
it('returns 401 without token', async () => {
const res = await request(app).get('/v1/sync?since=1970-01-01T00:00:00.000Z');
expect(res.status).toBe(401);
});
});

4
src/test/setup.ts Normal file
View File

@@ -0,0 +1,4 @@
process.env.NODE_ENV = 'test';
process.env.DATABASE_URL = process.env.TEST_DATABASE_URL ?? 'postgresql://postgres:postgres@localhost:5432/pantree_test';
process.env.JWT_SECRET = 'test_jwt_secret_that_is_long_enough_for_testing_purposes_only';
process.env.GOOGLE_CLIENT_ID = 'test_google_client_id';

27
src/test/utils.test.ts Normal file
View File

@@ -0,0 +1,27 @@
import { createError } from '../../middleware/errorHandler';
import { signToken } from '../../utils/jwt';
import jwt from 'jsonwebtoken';
describe('createError', () => {
it('creates an error with statusCode and code', () => {
const err = createError('Something went wrong', 404, 'NOT_FOUND');
expect(err.message).toBe('Something went wrong');
expect(err.statusCode).toBe(404);
expect(err.code).toBe('NOT_FOUND');
});
});
describe('signToken', () => {
it('returns a token and expiry date', () => {
const { token, expiresAt } = signToken('test-user-id');
expect(typeof token).toBe('string');
expect(expiresAt).toBeInstanceOf(Date);
expect(expiresAt.getTime()).toBeGreaterThan(Date.now());
});
it('encodes userId in the token', () => {
const { token } = signToken('my-user-id');
const decoded = jwt.decode(token) as { userId: string };
expect(decoded.userId).toBe('my-user-id');
});
});

158
src/test/validators.test.ts Normal file
View File

@@ -0,0 +1,158 @@
import { signupSchema, signinSchema, addPantryItemSchema, updatePantryItemSchema, addShoppingListItemSchema, updateShoppingListItemSchema, addRecipesToListSchema, recipeQuerySchema, syncQuerySchema } from '../../utils/validators';
describe('Validators', () => {
describe('signupSchema', () => {
it('accepts valid signup data', () => {
const result = signupSchema.safeParse({ email: 'user@example.com', password: 'password123', name: 'Jane' });
expect(result.success).toBe(true);
});
it('rejects invalid email', () => {
const result = signupSchema.safeParse({ email: 'not-an-email', password: 'password123', name: 'Jane' });
expect(result.success).toBe(false);
});
it('rejects short password', () => {
const result = signupSchema.safeParse({ email: 'user@example.com', password: 'short', name: 'Jane' });
expect(result.success).toBe(false);
});
it('rejects non-alphanumeric password', () => {
const result = signupSchema.safeParse({ email: 'user@example.com', password: 'pass!word', name: 'Jane' });
expect(result.success).toBe(false);
});
it('rejects empty name', () => {
const result = signupSchema.safeParse({ email: 'user@example.com', password: 'password123', name: '' });
expect(result.success).toBe(false);
});
});
describe('addPantryItemSchema', () => {
it('accepts valid pantry item', () => {
const result = addPantryItemSchema.safeParse({ item_name: 'Flour', quantity: 5 });
expect(result.success).toBe(true);
});
it('rejects zero quantity', () => {
const result = addPantryItemSchema.safeParse({ item_name: 'Flour', quantity: 0 });
expect(result.success).toBe(false);
});
it('rejects negative quantity', () => {
const result = addPantryItemSchema.safeParse({ item_name: 'Flour', quantity: -1 });
expect(result.success).toBe(false);
});
it('rejects fractional quantity', () => {
const result = addPantryItemSchema.safeParse({ item_name: 'Flour', quantity: 1.5 });
expect(result.success).toBe(false);
});
it('rejects empty item name', () => {
const result = addPantryItemSchema.safeParse({ item_name: '', quantity: 5 });
expect(result.success).toBe(false);
});
});
describe('updatePantryItemSchema', () => {
it('accepts valid update', () => {
const result = updatePantryItemSchema.safeParse({ quantity: 3 });
expect(result.success).toBe(true);
});
it('accepts update with last_modified', () => {
const result = updatePantryItemSchema.safeParse({ quantity: 3, last_modified: '2024-01-15T10:30:00.000Z' });
expect(result.success).toBe(true);
});
});
describe('addShoppingListItemSchema', () => {
it('accepts valid item', () => {
const result = addShoppingListItemSchema.safeParse({ item_name: 'Milk', quantity: 2, unit: 'cups' });
expect(result.success).toBe(true);
});
it('rejects invalid unit', () => {
const result = addShoppingListItemSchema.safeParse({ item_name: 'Milk', quantity: 2, unit: 'gallons' });
expect(result.success).toBe(false);
});
it('accepts fractional quantity', () => {
const result = addShoppingListItemSchema.safeParse({ item_name: 'Flour', quantity: 2.5, unit: 'cups' });
expect(result.success).toBe(true);
});
});
describe('updateShoppingListItemSchema', () => {
it('accepts partial update', () => {
const result = updateShoppingListItemSchema.safeParse({ checked_off: true });
expect(result.success).toBe(true);
});
it('rejects empty object', () => {
const result = updateShoppingListItemSchema.safeParse({});
expect(result.success).toBe(false);
});
});
describe('addRecipesToListSchema', () => {
it('accepts valid recipe ids', () => {
const result = addRecipesToListSchema.safeParse({
recipe_ids: ['123e4567-e89b-12d3-a456-426614174000'],
scale_factor: 2,
});
expect(result.success).toBe(true);
});
it('rejects empty recipe_ids', () => {
const result = addRecipesToListSchema.safeParse({ recipe_ids: [] });
expect(result.success).toBe(false);
});
it('rejects scale_factor > 3', () => {
const result = addRecipesToListSchema.safeParse({
recipe_ids: ['123e4567-e89b-12d3-a456-426614174000'],
scale_factor: 4,
});
expect(result.success).toBe(false);
});
it('defaults scale_factor to 1', () => {
const result = addRecipesToListSchema.safeParse({
recipe_ids: ['123e4567-e89b-12d3-a456-426614174000'],
});
expect(result.success).toBe(true);
if (result.success) expect(result.data.scale_factor).toBe(1);
});
});
describe('recipeQuerySchema', () => {
it('defaults to all filter, page 1, limit 20', () => {
const result = recipeQuerySchema.safeParse({});
expect(result.success).toBe(true);
if (result.success) {
expect(result.data.filter).toBe('all');
expect(result.data.page).toBe(1);
expect(result.data.limit).toBe(20);
}
});
it('rejects limit > 50', () => {
const result = recipeQuerySchema.safeParse({ limit: '51' });
expect(result.success).toBe(false);
});
});
describe('syncQuerySchema', () => {
it('accepts valid ISO timestamp', () => {
const result = syncQuerySchema.safeParse({ since: '2024-01-15T10:30:00.000Z' });
expect(result.success).toBe(true);
});
it('rejects invalid timestamp', () => {
const result = syncQuerySchema.safeParse({ since: 'not-a-date' });
expect(result.success).toBe(false);
});
});
});

View File

@@ -1,21 +0,0 @@
'use strict';
/**
* Application-level error.
* status — HTTP status code
* code — machine-readable error code
* message — human-readable message
* extra — optional additional fields merged into the response body
*/
class AppError extends Error {
constructor(status, code, message, extra = null) {
super(message);
this.name = 'AppError';
this.status = status;
this.code = code;
this.isAppError = true;
this.extra = extra;
}
}
module.exports = { AppError };

View File

@@ -1,26 +0,0 @@
'use strict';
const jwt = require('jsonwebtoken');
const config = require('../config');
/**
* Issues a signed JWT for the given user record.
* Returns { token, expires_at }.
*/
function issueToken(user) {
const payload = {
sub: user.id,
email: user.email,
};
const token = jwt.sign(payload, config.jwt.secret, {
expiresIn: config.jwt.expiresIn,
});
const decoded = jwt.decode(token);
const expires_at = new Date(decoded.exp * 1000).toISOString();
return { token, expires_at };
}
module.exports = { issueToken };

17
src/utils/jwt.ts Normal file
View File

@@ -0,0 +1,17 @@
import jwt from 'jsonwebtoken';
import { config } from '../config/env';
export interface TokenPayload {
userId: string;
}
export function signToken(userId: string): { token: string; expiresAt: Date } {
const expiresIn = config.jwtExpiresIn;
const token = jwt.sign({ userId }, config.jwtSecret, { expiresIn } as jwt.SignOptions);
// Calculate expiry date
const decoded = jwt.decode(token) as { exp: number };
const expiresAt = new Date(decoded.exp * 1000);
return { token, expiresAt };
}

15
src/utils/logger.ts Normal file
View File

@@ -0,0 +1,15 @@
import pino from 'pino';
import pinoHttp from 'pino-http';
import { config } from '../config/env';
export const logger = pino({
level: config.isTest ? 'silent' : 'info',
transport: config.isDev
? { target: 'pino-pretty', options: { colorize: true } }
: undefined,
});
export const httpLogger = pinoHttp({
logger,
autoLogging: !config.isTest,
});

View File

@@ -1,21 +0,0 @@
'use strict';
const { AppError } = require('./errors');
/**
* Validates data against a Zod schema.
* Throws a structured AppError on failure so the central error handler
* can format it consistently.
*/
function validate(schema, data) {
const result = schema.safeParse(data);
if (!result.success) {
const err = new AppError(400, 'VALIDATION_ERROR', 'Validation failed.');
err.zodError = true;
err.issues = result.error.issues;
throw err;
}
return result.data;
}
module.exports = { validate };

View File

@@ -1,134 +0,0 @@
'use strict';
const { z } = require('zod');
// ─── Auth ────────────────────────────────────────────────────────────────────
const signupSchema = z.object({
email: z.string().email('Invalid email format.').max(255),
password: z
.string()
.min(8, 'Password must be at least 8 characters.')
.regex(/^[a-zA-Z0-9]+$/, 'Password must be alphanumeric.'),
name: z.string().min(1, 'Name is required.').max(100, 'Name must be 100 characters or fewer.'),
});
const signinSchema = z.object({
email: z.string().email('Invalid email format.'),
password: z.string().min(1, 'Password is required.'),
});
const googleAuthSchema = z.object({
id_token: z.string().min(1, 'id_token is required.'),
});
const passwordResetRequestSchema = z.object({
email: z.string().email('Invalid email format.'),
});
const passwordResetConfirmSchema = z.object({
token: z.string().min(1, 'Token is required.'),
new_password: z
.string()
.min(8, 'Password must be at least 8 characters.')
.regex(/^[a-zA-Z0-9]+$/, 'Password must be alphanumeric.'),
});
const restoreAccountSchema = z.object({
email: z.string().email('Invalid email format.'),
password: z.string().min(1, 'Password is required.'),
});
// ─── Pantry ──────────────────────────────────────────────────────────────────
const addPantryItemSchema = z.object({
item_name: z
.string()
.min(1, 'Item name is required.')
.max(200, 'Item name must be 200 characters or fewer.')
.transform((v) => v.trim())
.refine((v) => v.length > 0, 'Item name cannot be blank.'),
quantity: z
.number({ invalid_type_error: 'Quantity must be a number.' })
.int('Quantity must be a whole number.')
.positive('Quantity must be positive.'),
});
const updatePantryItemSchema = z.object({
quantity: z
.number({ invalid_type_error: 'Quantity must be a number.' })
.int('Quantity must be a whole number.')
.positive('Quantity must be positive.'),
last_modified: z.string().datetime({ offset: true }).optional(),
});
// ─── Shopping Lists ───────────────────────────────────────────────────────────
const createShoppingListSchema = z.object({
list_name: z
.string()
.min(1, 'List name is required.')
.max(200, 'List name must be 200 characters or fewer.'),
});
const addShoppingListItemSchema = z.object({
item_name: z
.string()
.min(1, 'Item name is required.')
.max(200, 'Item name must be 200 characters or fewer.'),
quantity: z
.number({ invalid_type_error: 'Quantity must be a number.' })
.positive('Quantity must be positive.'),
unit: z.string().min(1, 'Unit is required.').max(50, 'Unit must be 50 characters or fewer.'),
});
const updateShoppingListItemSchema = z
.object({
quantity: z
.number({ invalid_type_error: 'Quantity must be a number.' })
.positive('Quantity must be positive.')
.optional(),
unit: z.string().min(1).max(50).optional(),
checked_off: z.boolean().optional(),
})
.refine(
(d) => d.quantity !== undefined || d.unit !== undefined || d.checked_off !== undefined,
{ message: 'At least one field (quantity, unit, checked_off) must be provided.' }
);
const addRecipesToListSchema = z.object({
recipe_ids: z
.array(z.string().uuid('Each recipe_id must be a valid UUID.'))
.min(1, 'At least one recipe_id is required.'),
scale: z.number().int().min(1).max(3).optional().default(1),
});
// ─── Recipes ─────────────────────────────────────────────────────────────────
const recipeQuerySchema = z.object({
filter: z.enum(['all', 'available', 'partial']).optional().default('all'),
scale: z.coerce.number().int().min(1).max(3).optional().default(1),
});
// ─── Sync ─────────────────────────────────────────────────────────────────────
const syncQuerySchema = z.object({
since: z.string().datetime({ offset: true }).optional(),
});
module.exports = {
signupSchema,
signinSchema,
googleAuthSchema,
passwordResetRequestSchema,
passwordResetConfirmSchema,
restoreAccountSchema,
addPantryItemSchema,
updatePantryItemSchema,
createShoppingListSchema,
addShoppingListItemSchema,
updateShoppingListItemSchema,
addRecipesToListSchema,
recipeQuerySchema,
syncQuerySchema,
};

97
src/utils/validators.ts Normal file
View File

@@ -0,0 +1,97 @@
import { z } from 'zod';
import { ALLOWED_UNITS } from '../config/constants';
export const signupSchema = z.object({
email: z.string().email('Invalid email format.'),
password: z
.string()
.min(8, 'Password must be at least 8 characters.')
.regex(/^[a-zA-Z0-9]+$/, 'Password must be alphanumeric.'),
name: z.string().min(1, 'Name is required.').max(255),
});
export const signinSchema = z.object({
email: z.string().email('Invalid email format.'),
password: z.string().min(1, 'Password is required.'),
});
export const googleAuthSchema = z.object({
id_token: z.string().min(1, 'id_token is required.'),
});
export const passwordResetRequestSchema = z.object({
email: z.string().email('Invalid email format.'),
});
export const passwordResetConfirmSchema = z.object({
token: z.string().min(1, 'Token is required.'),
new_password: z
.string()
.min(8, 'Password must be at least 8 characters.')
.regex(/^[a-zA-Z0-9]+$/, 'Password must be alphanumeric.'),
});
export const addPantryItemSchema = z.object({
item_name: z.string().min(1, 'Item name is required.').max(255),
quantity: z
.number()
.int('Quantity must be a whole number.')
.positive('Quantity must be positive.'),
});
export const updatePantryItemSchema = z.object({
quantity: z
.number()
.int('Quantity must be a whole number.')
.positive('Quantity must be positive.'),
last_modified: z.string().datetime().optional(),
});
export const createShoppingListSchema = z.object({
list_name: z.string().min(1, 'List name is required.').max(255),
});
export const addShoppingListItemSchema = z.object({
item_name: z.string().min(1, 'Item name is required.').max(255),
quantity: z.number().positive('Quantity must be positive.'),
unit: z.enum(ALLOWED_UNITS as [string, ...string[]], {
errorMap: () => ({ message: `Unit must be one of: ${ALLOWED_UNITS.join(', ')}` }),
}),
});
export const updateShoppingListItemSchema = z
.object({
quantity: z.number().positive('Quantity must be positive.').optional(),
unit: z
.enum(ALLOWED_UNITS as [string, ...string[]], {
errorMap: () => ({ message: `Unit must be one of: ${ALLOWED_UNITS.join(', ')}` }),
})
.optional(),
checked_off: z.boolean().optional(),
})
.refine(
(data) => Object.keys(data).length > 0,
{ message: 'At least one field must be provided.' }
);
export const addRecipesToListSchema = z.object({
recipe_ids: z
.array(z.string().uuid('Each recipe_id must be a valid UUID.'))
.min(1, 'At least one recipe_id is required.'),
scale_factor: z.number().int().min(1).max(3).optional().default(1),
});
export const recipeQuerySchema = z.object({
filter: z.enum(['all', 'can_make', 'can_partially_make']).optional().default('all'),
page: z.coerce.number().int().positive().optional().default(1),
limit: z.coerce.number().int().positive().max(50).optional().default(20),
search: z.string().optional(),
});
export const recipeDetailQuerySchema = z.object({
scale: z.coerce.number().int().min(1).max(3).optional().default(1),
});
export const syncQuerySchema = z.object({
since: z.string().datetime('since must be a valid ISO 8601 timestamp.'),
});

View File

@@ -1,240 +0,0 @@
'use strict';
const request = require('supertest');
const app = require('../../src/main/app');
const { setDb } = require('../../src/db/knex');
const { createTestDb } = require('../helpers/testDb');
describe('Auth Routes', () => {
let db;
beforeEach(() => {
db = createTestDb();
setDb(db);
});
// ── POST /v1/auth/signup ────────────────────────────────────────────────────
describe('POST /v1/auth/signup', () => {
it('creates a new user and returns token', async () => {
const res = await request(app)
.post('/v1/auth/signup')
.send({ email: 'jane@example.com', password: 'password1', name: 'Jane Doe' });
expect(res.status).toBe(201);
expect(res.body.user.email).toBe('jane@example.com');
expect(res.body.user.name).toBe('Jane Doe');
expect(res.body.token).toBeDefined();
expect(res.body.expires_at).toBeDefined();
// password_hash must never appear in response
expect(res.body.user.password_hash).toBeUndefined();
});
it('lowercases email on storage', async () => {
const res = await request(app)
.post('/v1/auth/signup')
.send({ email: 'JANE@EXAMPLE.COM', password: 'password1', name: 'Jane' });
expect(res.status).toBe(201);
expect(res.body.user.email).toBe('jane@example.com');
});
it('returns 409 when email already registered', async () => {
await request(app)
.post('/v1/auth/signup')
.send({ email: 'jane@example.com', password: 'password1', name: 'Jane' });
const res = await request(app)
.post('/v1/auth/signup')
.send({ email: 'jane@example.com', password: 'password1', name: 'Jane Again' });
expect(res.status).toBe(409);
expect(res.body.code).toBe('CONFLICT');
});
it('returns 409 for case-insensitive duplicate email', async () => {
await request(app)
.post('/v1/auth/signup')
.send({ email: 'jane@example.com', password: 'password1', name: 'Jane' });
const res = await request(app)
.post('/v1/auth/signup')
.send({ email: 'JANE@EXAMPLE.COM', password: 'password1', name: 'Jane' });
expect(res.status).toBe(409);
});
it('returns 400 for invalid email', async () => {
const res = await request(app)
.post('/v1/auth/signup')
.send({ email: 'not-an-email', password: 'password1', name: 'Jane' });
expect(res.status).toBe(400);
expect(res.body.code).toBe('VALIDATION_ERROR');
});
it('returns 400 for password shorter than 8 chars', async () => {
const res = await request(app)
.post('/v1/auth/signup')
.send({ email: 'jane@example.com', password: 'short', name: 'Jane' });
expect(res.status).toBe(400);
});
it('returns 400 for non-alphanumeric password', async () => {
const res = await request(app)
.post('/v1/auth/signup')
.send({ email: 'jane@example.com', password: 'p@ssword1', name: 'Jane' });
expect(res.status).toBe(400);
});
it('returns 400 when name is missing', async () => {
const res = await request(app)
.post('/v1/auth/signup')
.send({ email: 'jane@example.com', password: 'password1' });
expect(res.status).toBe(400);
});
it('returns 400 when body is empty', async () => {
const res = await request(app).post('/v1/auth/signup').send({});
expect(res.status).toBe(400);
});
});
// ── POST /v1/auth/signin ────────────────────────────────────────────────────
describe('POST /v1/auth/signin', () => {
beforeEach(async () => {
await request(app)
.post('/v1/auth/signup')
.send({ email: 'jane@example.com', password: 'password1', name: 'Jane' });
});
it('returns token on valid credentials', async () => {
const res = await request(app)
.post('/v1/auth/signin')
.send({ email: 'jane@example.com', password: 'password1' });
expect(res.status).toBe(200);
expect(res.body.token).toBeDefined();
expect(res.body.user.email).toBe('jane@example.com');
});
it('is case-insensitive for email', async () => {
const res = await request(app)
.post('/v1/auth/signin')
.send({ email: 'JANE@EXAMPLE.COM', password: 'password1' });
expect(res.status).toBe(200);
});
it('returns 401 for wrong password', async () => {
const res = await request(app)
.post('/v1/auth/signin')
.send({ email: 'jane@example.com', password: 'wrongpass' });
expect(res.status).toBe(401);
expect(res.body.code).toBe('UNAUTHORIZED');
});
it('returns 401 for unknown email', async () => {
const res = await request(app)
.post('/v1/auth/signin')
.send({ email: 'nobody@example.com', password: 'password1' });
expect(res.status).toBe(401);
});
it('returns 400 when fields are missing', async () => {
const res = await request(app)
.post('/v1/auth/signin')
.send({ email: 'jane@example.com' });
expect(res.status).toBe(400);
});
});
// ── POST /v1/auth/password-reset ────────────────────────────────────────────
describe('POST /v1/auth/password-reset', () => {
it('always returns 200 regardless of email existence', async () => {
const res = await request(app)
.post('/v1/auth/password-reset')
.send({ email: 'nobody@example.com' });
expect(res.status).toBe(200);
expect(res.body.message).toMatch(/reset link/i);
});
it('returns 400 for invalid email', async () => {
const res = await request(app)
.post('/v1/auth/password-reset')
.send({ email: 'not-an-email' });
expect(res.status).toBe(400);
});
});
// ── DELETE /v1/auth/account ─────────────────────────────────────────────────
describe('DELETE /v1/auth/account', () => {
it('soft-deletes the authenticated user account', async () => {
const signupRes = await request(app)
.post('/v1/auth/signup')
.send({ email: 'delete@example.com', password: 'password1', name: 'Delete Me' });
const token = signupRes.body.token;
const res = await request(app)
.delete('/v1/auth/account')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(204);
// Verify account is soft-deleted
const users = db.getTable('users');
const user = users.find((u) => u.email === 'delete@example.com');
expect(user.deleted_at).toBeDefined();
expect(user.deletion_scheduled_at).toBeDefined();
});
it('returns 401 without token', async () => {
const res = await request(app).delete('/v1/auth/account');
expect(res.status).toBe(401);
});
});
// ── POST /v1/auth/restore-account ──────────────────────────────────────────
describe('POST /v1/auth/restore-account', () => {
it('restores a soft-deleted account', async () => {
const signupRes = await request(app)
.post('/v1/auth/signup')
.send({ email: 'restore@example.com', password: 'password1', name: 'Restore Me' });
const token = signupRes.body.token;
await request(app)
.delete('/v1/auth/account')
.set('Authorization', `Bearer ${token}`);
const res = await request(app)
.post('/v1/auth/restore-account')
.send({ email: 'restore@example.com', password: 'password1' });
expect(res.status).toBe(200);
expect(res.body.user.deleted_at).toBeNull();
expect(res.body.message).toMatch(/restored/i);
});
it('returns 401 for wrong credentials', async () => {
const res = await request(app)
.post('/v1/auth/restore-account')
.send({ email: 'nobody@example.com', password: 'password1' });
expect(res.status).toBe(401);
});
});
});

View File

@@ -1,305 +0,0 @@
'use strict';
/**
* In-memory database stub for tests.
* Replaces the real Knex/PostgreSQL connection with a lightweight
* object that simulates table operations using plain JS Maps.
*
* Usage: const db = createTestDb(); setDb(db);
*/
function makeTable(rows = []) {
return [...rows];
}
/**
* Creates a minimal Knex-like query builder stub backed by in-memory arrays.
* Supports: insert, where, whereRaw, whereIn, whereNull, whereNotNull,
* first, select, update, delete, returning, orderBy,
* leftJoin, groupBy, raw, transaction.
*/
function createTestDb(initialData = {}) {
const tables = {};
function getTable(name) {
if (!tables[name]) tables[name] = [];
return tables[name];
}
function seedTable(name, rows) {
tables[name] = [...rows];
}
// Seed initial data
for (const [name, rows] of Object.entries(initialData)) {
seedTable(name, rows);
}
// ── Query Builder ────────────────────────────────────────────────────────────
function queryBuilder(tableName) {
let _rows = null; // lazy — resolved on terminal op
let _filters = [];
let _insertData = null;
let _updateData = null;
let _doDelete = false;
let _returning = false;
let _orderByField = null;
let _orderByDir = 'asc';
let _selectFields = null;
let _limit1 = false;
let _joins = [];
let _groupByField = null;
let _rawSelects = [];
function getRows() {
if (_rows !== null) return _rows;
return getTable(tableName);
}
function applyFilters(rows) {
return rows.filter((row) => {
for (const f of _filters) {
if (!f(row)) return false;
}
return true;
});
}
const qb = {
where(condOrField, val) {
if (typeof condOrField === 'object') {
for (const [k, v] of Object.entries(condOrField)) {
_filters.push((row) => row[k] === v);
}
} else {
_filters.push((row) => row[condOrField] === val);
}
return qb;
},
whereRaw(expr, params) {
// Support: 'LOWER(email) = ?' and 'item_name_lower = LOWER(?)'
const lowerEmailMatch = expr.match(/LOWER\((\w+)\)\s*=\s*\?/i);
const lowerFieldMatch = expr.match(/(\w+)\s*=\s*LOWER\(\?\)/i);
if (lowerEmailMatch) {
const field = lowerEmailMatch[1];
const val = params[0].toLowerCase();
_filters.push((row) => (row[field] || '').toLowerCase() === val);
} else if (lowerFieldMatch) {
const field = lowerFieldMatch[1];
const val = params[0].toLowerCase();
_filters.push((row) => (row[field] || '') === val);
}
return qb;
},
whereIn(field, vals) {
_filters.push((row) => vals.includes(row[field]));
return qb;
},
whereNull(field) {
_filters.push((row) => row[field] == null);
return qb;
},
whereNotNull(field) {
_filters.push((row) => row[field] != null);
return qb;
},
select(...fields) {
_selectFields = fields.flat();
return qb;
},
orderBy(field, dir = 'asc') {
_orderByField = field;
_orderByDir = dir;
return qb;
},
groupBy() {
_groupByField = true;
return qb;
},
leftJoin(otherTable, leftKey, rightKey) {
_joins.push({ otherTable, leftKey, rightKey });
return qb;
},
raw(sql) {
_rawSelects.push(sql);
return sql; // knex.raw returns the string in our stub
},
insert(data) {
_insertData = Array.isArray(data) ? data : [data];
return qb;
},
update(data) {
_updateData = data;
return qb;
},
delete() {
_doDelete = true;
return qb;
},
returning() {
_returning = true;
return qb;
},
first() {
_limit1 = true;
return qb;
},
// Terminal: await qb
then(resolve, reject) {
try {
resolve(execute());
} catch (e) {
reject(e);
}
},
};
function execute() {
const table = getTable(tableName);
if (_insertData) {
const inserted = _insertData.map((d) => {
const row = {
id: d.id || require('uuid').v4(),
...d,
created_at: d.created_at || new Date().toISOString(),
updated_at: d.updated_at || new Date().toISOString(),
last_modified: d.last_modified || new Date().toISOString(),
};
// Compute generated columns
if (row.item_name !== undefined) {
row.item_name_lower = row.item_name.toLowerCase();
}
table.push(row);
return row;
});
return _returning ? inserted : inserted.length;
}
if (_doDelete) {
const before = table.length;
const toDelete = applyFilters(table);
for (const row of toDelete) {
const idx = table.indexOf(row);
if (idx !== -1) table.splice(idx, 1);
}
return _returning ? toDelete : before - table.length;
}
if (_updateData) {
const matched = applyFilters(table);
const updated = matched.map((row) => {
Object.assign(row, _updateData, {
updated_at: new Date().toISOString(),
});
if (row.item_name !== undefined) {
row.item_name_lower = row.item_name.toLowerCase();
}
return row;
});
return _returning ? updated : updated.length;
}
// SELECT
let rows = applyFilters(table);
// Apply joins (simplified — just attach joined fields)
for (const join of _joins) {
const otherRows = getTable(join.otherTable);
const [leftTable, leftField] = join.leftKey.split('.');
const [, rightField] = join.rightKey.split('.');
rows = rows.map((row) => {
const matches = otherRows.filter((o) => o[rightField] === row[leftField || 'id']);
if (matches.length === 0) return { ...row, _joined: [] };
return matches.map((m) => ({ ...row, ...m, _joined: true }));
}).flat();
}
if (_orderByField) {
rows = [...rows].sort((a, b) => {
const av = a[_orderByField] || '';
const bv = b[_orderByField] || '';
const cmp = String(av).localeCompare(String(bv));
return _orderByDir === 'desc' ? -cmp : cmp;
});
}
// Aggregate for groupBy (count)
if (_groupByField) {
const grouped = {};
for (const row of rows) {
const key = row.id;
if (!grouped[key]) {
grouped[key] = { ...row, item_count: 0, checked_count: 0 };
}
if (row._joined) {
grouped[key].item_count++;
if (row.checked_off) grouped[key].checked_count++;
}
}
rows = Object.values(grouped);
}
if (_limit1) return rows[0] || null;
return rows;
}
return qb;
}
// ── Transaction stub ─────────────────────────────────────────────────────────
async function transaction(fn) {
// Pass the same db proxy as the transaction context
return fn(proxy);
}
// ── Raw stub ─────────────────────────────────────────────────────────────────
function raw(sql) {
return sql;
}
const proxy = new Proxy(
{ transaction, raw, _tables: tables, seedTable, getTable },
{
get(target, prop) {
if (prop in target) return target[prop];
return (tableName) => queryBuilder(tableName || prop);
},
apply(target, thisArg, args) {
return queryBuilder(args[0]);
},
}
);
// Make proxy callable as a function: db('tableName')
return new Proxy(function () {}, {
apply(target, thisArg, args) {
return queryBuilder(args[0]);
},
get(target, prop) {
if (prop === 'transaction') return transaction;
if (prop === 'raw') return raw;
if (prop === '_tables') return tables;
if (prop === 'seedTable') return seedTable;
if (prop === 'getTable') return getTable;
return (tableName) => queryBuilder(tableName || prop);
},
});
}
module.exports = { createTestDb };

View File

@@ -1,308 +0,0 @@
'use strict';
const request = require('supertest');
const app = require('../../src/main/app');
const { setDb } = require('../../src/db/knex');
const { createTestDb } = require('../helpers/testDb');
const { issueToken } = require('../../src/utils/jwt');
function makeUser(overrides = {}) {
return {
id: require('uuid').v4(),
email: 'jane@example.com',
name: 'Jane Doe',
profile_picture_url: null,
email_verified: true,
deleted_at: null,
deletion_scheduled_at: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...overrides,
};
}
describe('Pantry Routes', () => {
let db;
let user;
let token;
beforeEach(() => {
user = makeUser();
db = createTestDb({ users: [user] });
setDb(db);
token = issueToken(user).token;
});
// ── GET /v1/pantry ──────────────────────────────────────────────────────────
describe('GET /v1/pantry', () => {
it('returns empty items array for new user', async () => {
const res = await request(app)
.get('/v1/pantry')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.items).toEqual([]);
expect(res.body.synced_at).toBeDefined();
});
it('returns pantry items for authenticated user', async () => {
db.seedTable('pantry_items', [
{
id: 'item-1',
user_id: user.id,
item_name: 'Flour',
item_name_lower: 'flour',
quantity: 5,
last_modified: new Date().toISOString(),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
},
]);
const res = await request(app)
.get('/v1/pantry')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.items).toHaveLength(1);
expect(res.body.items[0].item_name).toBe('Flour');
});
it('returns 401 without token', async () => {
const res = await request(app).get('/v1/pantry');
expect(res.status).toBe(401);
});
it('does not return items belonging to other users', async () => {
const otherUser = makeUser({ id: 'other-user-id', email: 'other@example.com' });
db.seedTable('pantry_items', [
{
id: 'item-other',
user_id: otherUser.id,
item_name: 'Sugar',
item_name_lower: 'sugar',
quantity: 2,
last_modified: new Date().toISOString(),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
},
]);
const res = await request(app)
.get('/v1/pantry')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.items).toHaveLength(0);
});
});
// ── POST /v1/pantry ─────────────────────────────────────────────────────────
describe('POST /v1/pantry', () => {
it('adds a new pantry item', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 5 });
expect(res.status).toBe(201);
expect(res.body.item.item_name).toBe('Flour');
expect(res.body.item.quantity).toBe(5);
expect(res.body.item.id).toBeDefined();
});
it('returns 409 for duplicate item (case-insensitive)', async () => {
await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 5 });
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 3 });
expect(res.status).toBe(409);
expect(res.body.code).toBe('DUPLICATE_ITEM');
});
it('returns 409 for duplicate with different capitalisation', async () => {
await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Protein Powder', quantity: 1 });
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'PROTEIN POWDER', quantity: 1 });
expect(res.status).toBe(409);
});
it('returns 400 for zero quantity', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 0 });
expect(res.status).toBe(400);
});
it('returns 400 for negative quantity', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: -1 });
expect(res.status).toBe(400);
});
it('returns 400 for fractional quantity', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 1.5 });
expect(res.status).toBe(400);
});
it('returns 400 for missing item_name', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ quantity: 5 });
expect(res.status).toBe(400);
});
it('returns 400 for blank item_name', async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: ' ', quantity: 5 });
expect(res.status).toBe(400);
});
it('returns 401 without token', async () => {
const res = await request(app)
.post('/v1/pantry')
.send({ item_name: 'Flour', quantity: 5 });
expect(res.status).toBe(401);
});
});
// ── PUT /v1/pantry/:item_id ─────────────────────────────────────────────────
describe('PUT /v1/pantry/:item_id', () => {
let itemId;
beforeEach(async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 5 });
itemId = res.body.item.id;
});
it('updates quantity of existing item', async () => {
const res = await request(app)
.put(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${token}`)
.send({ quantity: 10 });
expect(res.status).toBe(200);
expect(res.body.item.quantity).toBe(10);
});
it('returns 404 for non-existent item', async () => {
const res = await request(app)
.put('/v1/pantry/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`)
.send({ quantity: 10 });
expect(res.status).toBe(404);
});
it('returns 404 for item belonging to another user', async () => {
const otherUser = makeUser({ id: 'other-id', email: 'other@example.com' });
const otherToken = issueToken(otherUser).token;
const res = await request(app)
.put(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${otherToken}`)
.send({ quantity: 10 });
expect(res.status).toBe(404);
});
it('returns 400 for invalid quantity', async () => {
const res = await request(app)
.put(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${token}`)
.send({ quantity: -5 });
expect(res.status).toBe(400);
});
});
// ── DELETE /v1/pantry/:item_id ──────────────────────────────────────────────
describe('DELETE /v1/pantry/:item_id', () => {
let itemId;
beforeEach(async () => {
const res = await request(app)
.post('/v1/pantry')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Butter', quantity: 2 });
itemId = res.body.item.id;
});
it('deletes an existing pantry item', async () => {
const res = await request(app)
.delete(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(204);
// Verify item is gone
const getRes = await request(app)
.get('/v1/pantry')
.set('Authorization', `Bearer ${token}`);
expect(getRes.body.items).toHaveLength(0);
});
it('records a tombstone for sync', async () => {
await request(app)
.delete(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${token}`);
const tombstones = db.getTable('deleted_records');
expect(tombstones.some((t) => t.record_id === itemId)).toBe(true);
});
it('returns 404 for non-existent item', async () => {
const res = await request(app)
.delete('/v1/pantry/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
});
it('returns 404 for item belonging to another user', async () => {
const otherUser = makeUser({ id: 'other-id', email: 'other@example.com' });
const otherToken = issueToken(otherUser).token;
const res = await request(app)
.delete(`/v1/pantry/${itemId}`)
.set('Authorization', `Bearer ${otherToken}`);
expect(res.status).toBe(404);
});
});
});

View File

@@ -1,220 +0,0 @@
'use strict';
const request = require('supertest');
const app = require('../../src/main/app');
const { setDb } = require('../../src/db/knex');
const { createTestDb } = require('../helpers/testDb');
const { issueToken } = require('../../src/utils/jwt');
const { v4: uuidv4 } = require('uuid');
function makeUser(overrides = {}) {
return {
id: uuidv4(),
email: 'jane@example.com',
name: 'Jane Doe',
profile_picture_url: null,
email_verified: true,
deleted_at: null,
deletion_scheduled_at: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...overrides,
};
}
const RECIPE_ID = '00000000-0000-0000-0000-000000000001';
function makeRecipe(overrides = {}) {
return {
id: RECIPE_ID,
name: 'Classic Pancakes',
instructions: '1. Mix. 2. Cook.',
servings: 4,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...overrides,
};
}
function makeIngredients(recipeId = RECIPE_ID) {
return [
{
id: uuidv4(),
recipe_id: recipeId,
item_name: 'flour',
item_name_lower: 'flour',
quantity: '2.0000',
unit: 'cups',
},
{
id: uuidv4(),
recipe_id: recipeId,
item_name: 'milk',
item_name_lower: 'milk',
quantity: '1.5000',
unit: 'cups',
},
{
id: uuidv4(),
recipe_id: recipeId,
item_name: 'eggs',
item_name_lower: 'eggs',
quantity: '2.0000',
unit: 'whole',
},
];
}
describe('Recipe Routes', () => {
let db;
let user;
let token;
beforeEach(() => {
user = makeUser();
db = createTestDb({
users: [user],
recipes: [makeRecipe()],
recipe_ingredients: makeIngredients(),
pantry_items: [],
});
setDb(db);
token = issueToken(user).token;
});
// ── GET /v1/recipes ─────────────────────────────────────────────────────────
describe('GET /v1/recipes', () => {
it('returns all recipes with availability', async () => {
const res = await request(app)
.get('/v1/recipes')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.recipes).toHaveLength(1);
expect(res.body.recipes[0].name).toBe('Classic Pancakes');
expect(res.body.recipes[0].availability).toBeDefined();
expect(res.body.synced_at).toBeDefined();
});
it('shows missing_all when pantry is empty', async () => {
const res = await request(app)
.get('/v1/recipes')
.set('Authorization', `Bearer ${token}`);
expect(res.body.recipes[0].availability.status).toBe('missing_all');
expect(res.body.recipes[0].availability.available_count).toBe(0);
expect(res.body.recipes[0].availability.total_count).toBe(3);
});
it('shows can_make when all ingredients are in pantry', async () => {
db.seedTable('pantry_items', [
{ id: uuidv4(), user_id: user.id, item_name: 'flour', item_name_lower: 'flour', quantity: 5, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() },
{ id: uuidv4(), user_id: user.id, item_name: 'milk', item_name_lower: 'milk', quantity: 2, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() },
{ id: uuidv4(), user_id: user.id, item_name: 'eggs', item_name_lower: 'eggs', quantity: 6, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() },
]);
const res = await request(app)
.get('/v1/recipes')
.set('Authorization', `Bearer ${token}`);
expect(res.body.recipes[0].availability.status).toBe('can_make');
expect(res.body.recipes[0].availability.available_count).toBe(3);
});
it('shows partial when some ingredients are in pantry', async () => {
db.seedTable('pantry_items', [
{ id: uuidv4(), user_id: user.id, item_name: 'flour', item_name_lower: 'flour', quantity: 5, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() },
]);
const res = await request(app)
.get('/v1/recipes')
.set('Authorization', `Bearer ${token}`);
expect(res.body.recipes[0].availability.status).toBe('partial');
expect(res.body.recipes[0].availability.available_count).toBe(1);
expect(res.body.recipes[0].availability.missing_ingredients).toContain('milk');
});
it('filters to available only with ?filter=available', async () => {
const res = await request(app)
.get('/v1/recipes?filter=available')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.recipes).toHaveLength(0); // pantry is empty
});
it('returns 401 without token', async () => {
const res = await request(app).get('/v1/recipes');
expect(res.status).toBe(401);
});
it('returns 400 for invalid scale', async () => {
const res = await request(app)
.get('/v1/recipes?scale=5')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
});
// ── GET /v1/recipes/:recipe_id ──────────────────────────────────────────────
describe('GET /v1/recipes/:recipe_id', () => {
it('returns full recipe detail', async () => {
const res = await request(app)
.get(`/v1/recipes/${RECIPE_ID}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.recipe.name).toBe('Classic Pancakes');
expect(res.body.recipe.instructions).toBeDefined();
expect(res.body.recipe.ingredients).toHaveLength(3);
expect(res.body.recipe.scaled_servings).toBe(4);
});
it('scales ingredient quantities with ?scale=2', async () => {
const res = await request(app)
.get(`/v1/recipes/${RECIPE_ID}?scale=2`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.recipe.scaled_servings).toBe(8);
const flour = res.body.recipe.ingredients.find((i) => i.item_name === 'flour');
expect(flour.quantity).toBe(4.0);
});
it('marks in_pantry correctly', async () => {
db.seedTable('pantry_items', [
{ id: uuidv4(), user_id: user.id, item_name: 'flour', item_name_lower: 'flour', quantity: 5, last_modified: new Date().toISOString(), created_at: new Date().toISOString(), updated_at: new Date().toISOString() },
]);
const res = await request(app)
.get(`/v1/recipes/${RECIPE_ID}`)
.set('Authorization', `Bearer ${token}`);
const flour = res.body.recipe.ingredients.find((i) => i.item_name === 'flour');
const milk = res.body.recipe.ingredients.find((i) => i.item_name === 'milk');
expect(flour.in_pantry).toBe(true);
expect(milk.in_pantry).toBe(false);
});
it('returns 404 for non-existent recipe', async () => {
const res = await request(app)
.get('/v1/recipes/00000000-0000-0000-0000-999999999999')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
expect(res.body.code).toBe('NOT_FOUND');
});
it('returns 400 for invalid scale value', async () => {
const res = await request(app)
.get(`/v1/recipes/${RECIPE_ID}?scale=10`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
});
});

View File

@@ -1,525 +0,0 @@
'use strict';
const request = require('supertest');
const app = require('../../src/main/app');
const { setDb } = require('../../src/db/knex');
const { createTestDb } = require('../helpers/testDb');
const { issueToken } = require('../../src/utils/jwt');
const { v4: uuidv4 } = require('uuid');
function makeUser(overrides = {}) {
return {
id: uuidv4(),
email: 'jane@example.com',
name: 'Jane Doe',
profile_picture_url: null,
email_verified: true,
deleted_at: null,
deletion_scheduled_at: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...overrides,
};
}
const RECIPE_ID = '00000000-0000-0000-0000-000000000001';
describe('Shopping List Routes', () => {
let db;
let user;
let token;
beforeEach(() => {
user = makeUser();
db = createTestDb({
users: [user],
shopping_lists: [],
shopping_list_items: [],
deleted_records: [],
recipes: [
{
id: RECIPE_ID,
name: 'Pancakes',
instructions: '1. Mix. 2. Cook.',
servings: 4,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
},
],
recipe_ingredients: [
{
id: uuidv4(),
recipe_id: RECIPE_ID,
item_name: 'flour',
item_name_lower: 'flour',
quantity: '2.0000',
unit: 'cups',
},
{
id: uuidv4(),
recipe_id: RECIPE_ID,
item_name: 'milk',
item_name_lower: 'milk',
quantity: '1.5000',
unit: 'cups',
},
],
});
setDb(db);
token = issueToken(user).token;
});
// ── GET /v1/shopping-lists ──────────────────────────────────────────────────
describe('GET /v1/shopping-lists', () => {
it('returns empty array for new user', async () => {
const res = await request(app)
.get('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.shopping_lists).toEqual([]);
expect(res.body.synced_at).toBeDefined();
});
it('returns 401 without token', async () => {
const res = await request(app).get('/v1/shopping-lists');
expect(res.status).toBe(401);
});
});
// ── POST /v1/shopping-lists ─────────────────────────────────────────────────
describe('POST /v1/shopping-lists', () => {
it('creates a new shopping list', async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: 'Weekly Groceries' });
expect(res.status).toBe(201);
expect(res.body.shopping_list.list_name).toBe('Weekly Groceries');
expect(res.body.shopping_list.item_count).toBe(0);
expect(res.body.shopping_list.id).toBeDefined();
});
it('returns 400 for missing list_name', async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({});
expect(res.status).toBe(400);
});
it('returns 400 for empty list_name', async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: '' });
expect(res.status).toBe(400);
});
it('returns 401 without token', async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.send({ list_name: 'Test' });
expect(res.status).toBe(401);
});
});
// ── GET /v1/shopping-lists/:list_id ────────────────────────────────────────
describe('GET /v1/shopping-lists/:list_id', () => {
let listId;
beforeEach(async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: 'My List' });
listId = res.body.shopping_list.id;
});
it('returns list with items', async () => {
const res = await request(app)
.get(`/v1/shopping-lists/${listId}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.shopping_list.id).toBe(listId);
expect(res.body.shopping_list.items).toEqual([]);
});
it('returns 404 for non-existent list', async () => {
const res = await request(app)
.get('/v1/shopping-lists/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
});
it('returns 404 for list belonging to another user', async () => {
const otherUser = makeUser({ id: uuidv4(), email: 'other@example.com' });
const otherToken = issueToken(otherUser).token;
const res = await request(app)
.get(`/v1/shopping-lists/${listId}`)
.set('Authorization', `Bearer ${otherToken}`);
expect(res.status).toBe(404);
});
});
// ── DELETE /v1/shopping-lists/:list_id ─────────────────────────────────────
describe('DELETE /v1/shopping-lists/:list_id', () => {
let listId;
beforeEach(async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: 'Delete Me' });
listId = res.body.shopping_list.id;
});
it('deletes the shopping list', async () => {
const res = await request(app)
.delete(`/v1/shopping-lists/${listId}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(204);
const getRes = await request(app)
.get(`/v1/shopping-lists/${listId}`)
.set('Authorization', `Bearer ${token}`);
expect(getRes.status).toBe(404);
});
it('records tombstone for sync', async () => {
await request(app)
.delete(`/v1/shopping-lists/${listId}`)
.set('Authorization', `Bearer ${token}`);
const tombstones = db.getTable('deleted_records');
expect(tombstones.some((t) => t.record_id === listId)).toBe(true);
});
it('returns 404 for non-existent list', async () => {
const res = await request(app)
.delete('/v1/shopping-lists/00000000-0000-0000-0000-000000000000')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
});
});
// ── POST /v1/shopping-lists/:list_id/items ──────────────────────────────────
describe('POST /v1/shopping-lists/:list_id/items', () => {
let listId;
beforeEach(async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: 'Groceries' });
listId = res.body.shopping_list.id;
});
it('adds an item to the list', async () => {
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 2.0, unit: 'cups' });
expect(res.status).toBe(201);
expect(res.body.item.item_name).toBe('flour');
expect(res.body.item.quantity).toBe(2.0);
expect(res.body.merged).toBe(false);
});
it('merges quantities for same name and unit', async () => {
await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 2.0, unit: 'cups' });
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 1.5, unit: 'cups' });
expect(res.status).toBe(201);
expect(res.body.merged).toBe(true);
expect(res.body.item.quantity).toBe(3.5);
expect(res.body.previous_quantity).toBe(2.0);
});
it('merges case-insensitively', async () => {
await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'Flour', quantity: 2.0, unit: 'cups' });
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'FLOUR', quantity: 1.0, unit: 'cups' });
expect(res.body.merged).toBe(true);
expect(res.body.item.quantity).toBe(3.0);
});
it('creates separate items for same name but different unit', async () => {
await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 2.0, unit: 'cups' });
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 100.0, unit: 'g' });
expect(res.body.merged).toBe(false);
const listRes = await request(app)
.get(`/v1/shopping-lists/${listId}`)
.set('Authorization', `Bearer ${token}`);
expect(listRes.body.shopping_list.items).toHaveLength(2);
});
it('returns 400 for missing unit', async () => {
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 2.0 });
expect(res.status).toBe(400);
});
it('returns 400 for zero quantity', async () => {
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 0, unit: 'cups' });
expect(res.status).toBe(400);
});
it('returns 404 for non-existent list', async () => {
const res = await request(app)
.post('/v1/shopping-lists/00000000-0000-0000-0000-000000000000/items')
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'flour', quantity: 2.0, unit: 'cups' });
expect(res.status).toBe(404);
});
});
// ── PUT /v1/shopping-lists/:list_id/items/:item_id ──────────────────────────
describe('PUT /v1/shopping-lists/:list_id/items/:item_id', () => {
let listId;
let itemId;
beforeEach(async () => {
const listRes = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: 'Update Test' });
listId = listRes.body.shopping_list.id;
const itemRes = await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'butter', quantity: 1.0, unit: 'cups' });
itemId = itemRes.body.item.id;
});
it('updates checked_off status', async () => {
const res = await request(app)
.put(`/v1/shopping-lists/${listId}/items/${itemId}`)
.set('Authorization', `Bearer ${token}`)
.send({ checked_off: true });
expect(res.status).toBe(200);
expect(res.body.item.checked_off).toBe(true);
});
it('updates quantity', async () => {
const res = await request(app)
.put(`/v1/shopping-lists/${listId}/items/${itemId}`)
.set('Authorization', `Bearer ${token}`)
.send({ quantity: 3.5 });
expect(res.status).toBe(200);
expect(res.body.item.quantity).toBe(3.5);
});
it('returns 400 when no fields provided', async () => {
const res = await request(app)
.put(`/v1/shopping-lists/${listId}/items/${itemId}`)
.set('Authorization', `Bearer ${token}`)
.send({});
expect(res.status).toBe(400);
});
it('returns 404 for non-existent item', async () => {
const res = await request(app)
.put(`/v1/shopping-lists/${listId}/items/00000000-0000-0000-0000-000000000000`)
.set('Authorization', `Bearer ${token}`)
.send({ checked_off: true });
expect(res.status).toBe(404);
});
});
// ── DELETE /v1/shopping-lists/:list_id/items/:item_id ───────────────────────
describe('DELETE /v1/shopping-lists/:list_id/items/:item_id', () => {
let listId;
let itemId;
beforeEach(async () => {
const listRes = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: 'Delete Item Test' });
listId = listRes.body.shopping_list.id;
const itemRes = await request(app)
.post(`/v1/shopping-lists/${listId}/items`)
.set('Authorization', `Bearer ${token}`)
.send({ item_name: 'sugar', quantity: 1.0, unit: 'cups' });
itemId = itemRes.body.item.id;
});
it('deletes the item', async () => {
const res = await request(app)
.delete(`/v1/shopping-lists/${listId}/items/${itemId}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(204);
const listRes = await request(app)
.get(`/v1/shopping-lists/${listId}`)
.set('Authorization', `Bearer ${token}`);
expect(listRes.body.shopping_list.items).toHaveLength(0);
});
it('records tombstone for sync', async () => {
await request(app)
.delete(`/v1/shopping-lists/${listId}/items/${itemId}`)
.set('Authorization', `Bearer ${token}`);
const tombstones = db.getTable('deleted_records');
expect(tombstones.some((t) => t.record_id === itemId)).toBe(true);
});
it('returns 404 for non-existent item', async () => {
const res = await request(app)
.delete(`/v1/shopping-lists/${listId}/items/00000000-0000-0000-0000-000000000000`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(404);
});
});
// ── POST /v1/shopping-lists/:list_id/add-recipes ────────────────────────────
describe('POST /v1/shopping-lists/:list_id/add-recipes', () => {
let listId;
beforeEach(async () => {
const res = await request(app)
.post('/v1/shopping-lists')
.set('Authorization', `Bearer ${token}`)
.send({ list_name: 'Recipe List' });
listId = res.body.shopping_list.id;
});
it('adds recipe ingredients to the list', async () => {
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [RECIPE_ID], scale: 1 });
expect(res.status).toBe(201);
expect(res.body.recipes_added).toBe(1);
expect(res.body.items_created).toBe(2); // flour + milk
expect(res.body.shopping_list.items).toHaveLength(2);
});
it('merges quantities when adding same recipe twice', async () => {
await request(app)
.post(`/v1/shopping-lists/${listId}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [RECIPE_ID], scale: 1 });
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [RECIPE_ID], scale: 1 });
expect(res.status).toBe(201);
expect(res.body.items_merged).toBe(2);
expect(res.body.items_created).toBe(0);
const flour = res.body.shopping_list.items.find((i) => i.item_name === 'flour');
expect(flour.quantity).toBe(4.0); // 2 + 2
});
it('scales ingredient quantities', async () => {
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [RECIPE_ID], scale: 2 });
expect(res.status).toBe(201);
const flour = res.body.shopping_list.items.find((i) => i.item_name === 'flour');
expect(flour.quantity).toBe(4.0); // 2 * 2
});
it('returns 400 for empty recipe_ids', async () => {
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [] });
expect(res.status).toBe(400);
});
it('returns 400 for invalid scale', async () => {
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [RECIPE_ID], scale: 5 });
expect(res.status).toBe(400);
});
it('returns 404 for non-existent recipe', async () => {
const res = await request(app)
.post(`/v1/shopping-lists/${listId}/add-recipes`)
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: ['00000000-0000-0000-0000-999999999999'] });
expect(res.status).toBe(404);
});
it('returns 404 for non-existent list', async () => {
const res = await request(app)
.post('/v1/shopping-lists/00000000-0000-0000-0000-000000000000/add-recipes')
.set('Authorization', `Bearer ${token}`)
.send({ recipe_ids: [RECIPE_ID] });
expect(res.status).toBe(404);
});
});
});

View File

@@ -1,166 +0,0 @@
'use strict';
const request = require('supertest');
const app = require('../../src/main/app');
const { setDb } = require('../../src/db/knex');
const { createTestDb } = require('../helpers/testDb');
const { issueToken } = require('../../src/utils/jwt');
const { v4: uuidv4 } = require('uuid');
function makeUser(overrides = {}) {
return {
id: uuidv4(),
email: 'jane@example.com',
name: 'Jane Doe',
profile_picture_url: null,
email_verified: true,
deleted_at: null,
deletion_scheduled_at: null,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
...overrides,
};
}
describe('Sync Route', () => {
let db;
let user;
let token;
beforeEach(() => {
user = makeUser();
db = createTestDb({
users: [user],
pantry_items: [],
shopping_lists: [],
shopping_list_items: [],
deleted_records: [],
});
setDb(db);
token = issueToken(user).token;
});
describe('GET /v1/sync', () => {
it('returns full sync when no since param', async () => {
const res = await request(app)
.get('/v1/sync')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.full_sync).toBe(true);
expect(res.body.server_timestamp).toBeDefined();
expect(res.body.pantry).toBeDefined();
expect(res.body.shopping_lists).toBeDefined();
});
it('returns delta sync when since param provided', async () => {
const since = new Date(Date.now() - 60000).toISOString(); // 1 minute ago
const res = await request(app)
.get(`/v1/sync?since=${encodeURIComponent(since)}`)
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(200);
expect(res.body.full_sync).toBe(false);
});
it('includes pantry items in full sync', async () => {
db.seedTable('pantry_items', [
{
id: uuidv4(),
user_id: user.id,
item_name: 'Flour',
item_name_lower: 'flour',
quantity: 5,
last_modified: new Date().toISOString(),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
},
]);
const res = await request(app)
.get('/v1/sync')
.set('Authorization', `Bearer ${token}`);
expect(res.body.pantry.items).toHaveLength(1);
expect(res.body.pantry.items[0].item_name).toBe('Flour');
expect(res.body.pantry.items[0].deleted).toBe(false);
});
it('includes shopping lists in full sync', async () => {
const listId = uuidv4();
db.seedTable('shopping_lists', [
{
id: listId,
user_id: user.id,
list_name: 'Weekly',
last_modified: new Date().toISOString(),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
},
]);
const res = await request(app)
.get('/v1/sync')
.set('Authorization', `Bearer ${token}`);
expect(res.body.shopping_lists.lists).toHaveLength(1);
expect(res.body.shopping_lists.lists[0].list_name).toBe('Weekly');
});
it('includes deleted_ids for tombstoned pantry items', async () => {
const deletedId = uuidv4();
const since = new Date(Date.now() - 60000).toISOString();
db.seedTable('deleted_records', [
{
id: uuidv4(),
user_id: user.id,
record_type: 'pantry_item',
record_id: deletedId,
deleted_at: new Date().toISOString(),
},
]);
const res = await request(app)
.get(`/v1/sync?since=${encodeURIComponent(since)}`)
.set('Authorization', `Bearer ${token}`);
expect(res.body.pantry.deleted_ids).toContain(deletedId);
});
it('returns 401 without token', async () => {
const res = await request(app).get('/v1/sync');
expect(res.status).toBe(401);
});
it('returns 400 for invalid since timestamp', async () => {
const res = await request(app)
.get('/v1/sync?since=not-a-date')
.set('Authorization', `Bearer ${token}`);
expect(res.status).toBe(400);
});
it('does not return data belonging to other users', async () => {
const otherUser = makeUser({ id: uuidv4(), email: 'other@example.com' });
db.seedTable('pantry_items', [
{
id: uuidv4(),
user_id: otherUser.id,
item_name: 'Sugar',
item_name_lower: 'sugar',
quantity: 3,
last_modified: new Date().toISOString(),
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
},
]);
const res = await request(app)
.get('/v1/sync')
.set('Authorization', `Bearer ${token}`);
expect(res.body.pantry.items).toHaveLength(0);
});
});
});

19
tsconfig.json Normal file
View File

@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}