All files / src/lib/graphql/resolvers/recipe utils.ts

0% Statements 0/32
0% Branches 0/59
0% Functions 0/11
0% Lines 0/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192                                                                                                                                                                                                                                                                                                                                                                                               
import { Prisma } from '@prisma/client';
import { METADATA } from '@/lib/data/metadata';
import { prisma } from '@/lib/prisma/prisma';
import { ErrorTypes } from '@/lib/validation/errorCatalog';
import { throwCustomError } from '@/lib/validation/throwCustomError';
import type { GraphQLContext } from '@/types/graphql/context';
 
import type { MetaInputPartial, RecipeInputBase } from './types';
 
/* ─── Assertion Helper ───────────────────────── */
 
type ErrorType = (typeof ErrorTypes)[keyof typeof ErrorTypes];
 
export const assertPresent: <T>(
  value: T,
  message: string,
  errorType: ErrorType,
) => asserts value is NonNullable<T> = (value, message, errorType) => {
  if (value == null) {
    throwCustomError(message, errorType);
  }
};
 
/* ─── Auth Guard ─────────────────────────────── */
 
export const resolveAuthenticatedUser = async (context: GraphQLContext) => {
  if (!context.userId) {
    throwCustomError('Unauthenticated', ErrorTypes.UNAUTHORIZED);
  }
 
  const user = await prisma.user.findUnique({
    where: { id: context.userId },
  });
 
  assertPresent(user, 'User not found', ErrorTypes.UNAUTHORIZED);
 
  return user;
};
 
/* ─── Input Validation ───────────────────────── */
 
export const validateRequiredFields = (input: RecipeInputBase) => {
  const {
    title,
    ingredients,
    preparationSteps,
    category,
    cookingTime,
    difficultyLevel,
    servings,
  } = input;
 
  if (
    !title ||
    !ingredients ||
    !preparationSteps ||
    !category ||
    !cookingTime ||
    !difficultyLevel ||
    !servings
  ) {
    throwCustomError(
      'All required fields must be provided',
      ErrorTypes.BAD_REQUEST,
    );
  }
};
 
/* ─── Metadata Resolution ────────────────────── */
 
/**
 * Since the Metadata model was removed from the database,
 * metadata is now taken directly from input
 * and stored as JSON within the recipe.
 */
export const resolveRecipeMetadata = async (input: RecipeInputBase) => {
  const {
    category,
    difficultyLevel,
    labels = [],
    cuisine,
    servingUnit,
    dietaryFlags = [],
    allergens = [],
    equipment = [],
    costLevel,
  } = input;
 
  return {
    categoryFromInput: category,
    difficultyLevelFromInput: difficultyLevel,
    labelsFromInput: labels,
    cuisineFromInput: cuisine,
    servingUnitFromInput: servingUnit,
    dietaryFlagsFromInput: dietaryFlags,
    allergensFromInput: allergens,
    equipmentFromInput: equipment,
    costLevelFromInput: costLevel,
  };
};
 
/* ─── Data Mapping ───────────────────────────── */
 
const mapMetadataToJson = (m: MetaInputPartial, type: string) => {
  const existing = METADATA.find(
    (entry) =>
      entry.type === type && (entry.key === m.value || entry.name === m.value),
  );
 
  return {
    id: existing?.id || null,
    name: m.value,
    key: existing?.key || m.value,
    label: m.label,
    type,
  };
};
 
export const buildRecipeData = (
  input: RecipeInputBase,
  metadata: Awaited<ReturnType<typeof resolveRecipeMetadata>>,
) => {
  const {
    categoryFromInput,
    difficultyLevelFromInput,
    labelsFromInput,
    cuisineFromInput,
    servingUnitFromInput,
    dietaryFlagsFromInput,
    allergensFromInput,
    equipmentFromInput,
    costLevelFromInput,
  } = metadata;
 
  // Compute totalTimeMinutes from time breakdown
  const prep = input.prepTimeMinutes ?? 0;
  const cook = input.cookTimeMinutes ?? 0;
  const rest = input.restTimeMinutes ?? 0;
  const hasTimes =
    input.prepTimeMinutes != null ||
    input.cookTimeMinutes != null ||
    input.restTimeMinutes != null;
  const totalTimeMinutes = hasTimes ? prep + cook + rest : null;
 
  return {
    title: input.title,
    description: input.description,
    category: mapMetadataToJson(categoryFromInput, 'CATEGORY'),
    difficultyLevel: mapMetadataToJson(
      difficultyLevelFromInput,
      'DIFFICULTY_LEVEL',
    ),
    labels: labelsFromInput.map((l) => mapMetadataToJson(l, 'LABEL')),
    imgSrc: input.imgSrc,
    cookingTime: input.cookingTime,
    servings: input.servings,
    youtubeLink: input.youtubeLink,
 
    // Time fields
    prepTimeMinutes: input.prepTimeMinutes ?? null,
    cookTimeMinutes: input.cookTimeMinutes ?? null,
    restTimeMinutes: input.restTimeMinutes ?? null,
    totalTimeMinutes,
 
    // Metadata fields
    servingUnit: servingUnitFromInput
      ? mapMetadataToJson(servingUnitFromInput, 'SERVING_UNIT')
      : Prisma.DbNull,
    cuisine: cuisineFromInput
      ? mapMetadataToJson(cuisineFromInput, 'CUISINE')
      : Prisma.DbNull,
    dietaryFlags: dietaryFlagsFromInput.map((d) =>
      mapMetadataToJson(d, 'DIET'),
    ),
    allergens: allergensFromInput.map((a) => mapMetadataToJson(a, 'ALLERGEN')),
    equipment: equipmentFromInput.map((e) => mapMetadataToJson(e, 'EQUIPMENT')),
    costLevel: costLevelFromInput
      ? mapMetadataToJson(costLevelFromInput, 'COST_LEVEL')
      : Prisma.DbNull,
 
    // Text fields
    tips: input.tips ?? null,
    substitutions: input.substitutions ?? null,
 
    // SEO fields
    slug: input.slug ?? null,
    seoTitle: input.seoTitle ?? null,
    seoDescription: input.seoDescription ?? null,
    socialImage: input.socialImage ?? null,
  };
};