openvibers/openvibe.markets serverdeals.js

deals.js

main 2.7 KB · 50 lines · javascript

1'use strict';
2/**
3 * Deals' offers, the first source Markets searches (plan §L.1: "Deals keeps the one product graph … No second
4 * catalogue"). GET {DEALS_URL}/api/v1/search (Deals #380): every offer with its latest observation, a price only "as of"
5 * its time. Deals down or slow is said plainly; the marketplaces' links still work.
6 *
7 * createDeals({ baseUrl, fetchImpl, timeoutMs }) → { search(q, { limit }) → { ok, total, results, error? } }
8 * results: [{ title, url, store, price, currency, observed_at, source, image }]
9 */
10const take = (v) => (v == null ? null : v);
11
12function resultOf(o) {
13 const obs = o.latest_observation || {};
14 const feed = o.feed || {};
15 const price = feed.price ? Number(feed.price.amount) : (obs.price != null ? Number(obs.price) : NaN);
16 const thumb = feed.media && feed.media.thumb;
17 return {
18 title: String(o.title || '').slice(0, 200),
19 url: String(o.url || ''),
20 store: take(feed.store) || take(o.store && (o.store.name || o.store.domain)) || take(o.seller),
21 price: Number.isFinite(price) ? price : null,
22 was: Number.isFinite(Number(feed.was)) && feed.was != null ? Number(feed.was) : null,
23 currency: take(feed.price && feed.price.currency) || take(obs.currency),
24 observed_at: take(obs.observed_at),
25 condition: take(obs.condition),
26 image: typeof thumb === 'string' && /^https:\/\//.test(thumb) ? thumb : null,
27 source: 'OpenVibe Deals',
28 };
29}
30
31function createDeals({ baseUrl, fetchImpl = globalThis.fetch, timeoutMs = 5000 } = {}) {
32 const base = String(baseUrl || '').replace(/\/+$/, '');
33 async function search(q, { limit = 20 } = {}) {
34 if (!base) return { ok: false, total: 0, results: [], error: 'Deals is not connected here.' };
35 try {
36 const res = await fetchImpl(`${base}/api/v1/search?q=${encodeURIComponent(q)}&limit=${Math.min(50, Math.max(1, limit))}`, {
37 headers: { accept: 'application/json', 'user-agent': 'OpenVibe.Markets' }, signal: AbortSignal.timeout(timeoutMs), redirect: 'error',
38 });
39 const body = await res.json().catch(() => null);
40 if (!res.ok || !body || !Array.isArray(body.offers)) return { ok: false, total: 0, results: [], error: `Deals answered ${res.status}.` };
41 return { ok: true, total: Number(body.total) || body.offers.length, results: body.offers.map(resultOf).filter((r) => r.title && /^https:\/\//.test(r.url)) };
42 } catch (err) {
43 return { ok: false, total: 0, results: [], error: err && err.name === 'TimeoutError' ? 'Deals did not answer in time.' : 'Deals could not be reached.' };
44 }
45 }
46 return { search };
47}
48
49module.exports = { createDeals, resultOf };
50