164 lines
5.3 KiB
JavaScript
164 lines
5.3 KiB
JavaScript
'use strict';
|
|
|
|
const { db } = require('./db');
|
|
|
|
const USER_AGENT = 'Counter/1.0 (self-hosted calorie tracker)';
|
|
const BASE_URL = (process.env.OFF_BASE_URL || 'https://world.openfoodfacts.org').replace(/\/$/, '');
|
|
const CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
const FIELDS = [
|
|
'code', 'product_name', 'product_name_en', 'generic_name', 'brands',
|
|
'image_front_small_url', 'image_front_url', 'serving_size', 'serving_quantity',
|
|
'quantity', 'nutriments',
|
|
].join(',');
|
|
|
|
function serviceError(message, cause) {
|
|
const err = new Error(message);
|
|
err.status = 502;
|
|
if (cause) err.cause = cause;
|
|
return err;
|
|
}
|
|
|
|
async function getJson(url) {
|
|
let res;
|
|
try {
|
|
res = await fetch(url, {
|
|
headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' },
|
|
signal: AbortSignal.timeout(Number(process.env.OFF_TIMEOUT_MS) || 8000),
|
|
});
|
|
} catch (err) {
|
|
throw serviceError('Could not reach Open Food Facts. Check the connection and try again.', err);
|
|
}
|
|
if (!res.ok) throw serviceError(`Open Food Facts responded with HTTP ${res.status}.`);
|
|
try {
|
|
return await res.json();
|
|
} catch (err) {
|
|
throw serviceError('Open Food Facts returned a response we could not read.', err);
|
|
}
|
|
}
|
|
|
|
function toNumber(value) {
|
|
const n = Number(value);
|
|
return Number.isFinite(n) && n > 0 ? n : 0;
|
|
}
|
|
|
|
function round1(n) {
|
|
return Math.round(n * 10) / 10;
|
|
}
|
|
|
|
function normalizeProduct(product) {
|
|
if (!product || typeof product !== 'object') return null;
|
|
|
|
const nut = product.nutriments && typeof product.nutriments === 'object' ? product.nutriments : {};
|
|
const energyKj = toNumber(nut.energy_100g) || toNumber(nut['energy-kj_100g']);
|
|
let kcal100 = toNumber(nut['energy-kcal_100g']);
|
|
if (!kcal100 && energyKj) kcal100 = energyKj / 4.184;
|
|
if (!kcal100) return null;
|
|
|
|
const name = [product.product_name_en, product.product_name, product.generic_name]
|
|
.find((value) => typeof value === 'string' && value.trim()) || '';
|
|
const code = String(product.code || '').trim();
|
|
if (!name && !code) return null;
|
|
|
|
const sodium100g = toNumber(nut.sodium_100g) || toNumber(nut.salt_100g) / 2.5;
|
|
const servingGrams = toNumber(product.serving_quantity) || parseFloat(product.serving_quantity) || null;
|
|
|
|
return {
|
|
code,
|
|
name: (name || `Product ${code}`).trim().slice(0, 160),
|
|
brand: String(product.brands || '').split(',')[0].trim().slice(0, 80),
|
|
image: product.image_front_small_url || product.image_front_url || null,
|
|
quantity: product.quantity || null,
|
|
servingLabel: product.serving_size || null,
|
|
servingGrams: servingGrams && servingGrams > 0 ? round1(servingGrams) : null,
|
|
per100g: {
|
|
kcal: Math.round(kcal100),
|
|
protein_g: round1(toNumber(nut.proteins_100g)),
|
|
carbs_g: round1(toNumber(nut.carbohydrates_100g)),
|
|
fat_g: round1(toNumber(nut.fat_100g)),
|
|
fiber_g: round1(toNumber(nut.fiber_100g)),
|
|
sugar_g: round1(toNumber(nut.sugars_100g)),
|
|
sodium_mg: Math.round(sodium100g * 1000),
|
|
},
|
|
source: 'Open Food Facts',
|
|
};
|
|
}
|
|
|
|
function readCache(code) {
|
|
const row = db.prepare('SELECT payload, fetched_at FROM food_cache WHERE barcode = ?').get(code);
|
|
if (!row) return null;
|
|
|
|
let payload;
|
|
try {
|
|
payload = JSON.parse(row.payload);
|
|
} catch {
|
|
return null;
|
|
}
|
|
|
|
const age = Date.now() - Date.parse(row.fetched_at);
|
|
return { payload, stale: !(Number.isFinite(age) && age < CACHE_TTL_MS) };
|
|
}
|
|
|
|
function writeCache(code, product) {
|
|
db.prepare(
|
|
`INSERT INTO food_cache (barcode, payload, fetched_at) VALUES (?, ?, ?)
|
|
ON CONFLICT(barcode) DO UPDATE SET payload = excluded.payload, fetched_at = excluded.fetched_at`
|
|
).run(code, JSON.stringify(product), new Date().toISOString());
|
|
}
|
|
|
|
async function getProduct(barcode) {
|
|
const code = String(barcode || '').trim();
|
|
if (!/^\d{6,14}$/.test(code)) {
|
|
const err = new Error('A barcode is 6 to 14 digits.');
|
|
err.status = 400;
|
|
throw err;
|
|
}
|
|
|
|
const cached = readCache(code);
|
|
if (cached && !cached.stale) {
|
|
const product = normalizeProduct(cached.payload);
|
|
if (product) return product;
|
|
}
|
|
|
|
try {
|
|
const data = await getJson(
|
|
`${BASE_URL}/api/v2/product/${encodeURIComponent(code)}.json?fields=${FIELDS}`
|
|
);
|
|
if (!data || data.status !== 1 || !data.product) return null;
|
|
writeCache(code, data.product);
|
|
return normalizeProduct(data.product);
|
|
} catch (err) {
|
|
// A slightly stale cached product beats a failed scan.
|
|
if (cached) {
|
|
const product = normalizeProduct(cached.payload);
|
|
if (product) return product;
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
async function searchFoods(query) {
|
|
const url = new URL('/cgi/search.pl', BASE_URL);
|
|
url.searchParams.set('search_terms', query);
|
|
url.searchParams.set('search_simple', '1');
|
|
url.searchParams.set('action', 'process');
|
|
url.searchParams.set('json', '1');
|
|
url.searchParams.set('page_size', '24');
|
|
url.searchParams.set('fields', FIELDS);
|
|
|
|
const data = await getJson(url.toString());
|
|
const raw = Array.isArray(data.products) ? data.products : [];
|
|
const seen = new Set();
|
|
const products = [];
|
|
|
|
for (const item of raw) {
|
|
const product = normalizeProduct(item);
|
|
if (!product || !product.code || seen.has(product.code)) continue;
|
|
seen.add(product.code);
|
|
products.push(product);
|
|
}
|
|
|
|
return products;
|
|
}
|
|
|
|
module.exports = { getProduct, searchFoods, normalizeProduct, getJson };
|