File size: 7,233 Bytes
975fa6c
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
{
  "id": "1f7dbfa3-f52c-4533-819d-f834b30cf177",
  "title": "getMarketplaceProduct.js",
  "content": "/**\n * getMarketplaceProduct(defaultFuncs, api, ctx) -> (listingId, cb?) => Promise<Product>\n * Fetch a Marketplace product by ID with full details and all images in one response.\n *\n * Args:\n *  - listingId : string (required)\n * Returns Product: { id, title, description, price, status, location, delivery, attributes, category, shareUrl, createdAt, images }\n *\n * Example:\n *   const getProduct = getMarketplaceProduct(defaultFuncs, api, ctx);\n *   const product = await getProduct(\"1234567890123456\");\n *\n * Author: @tas33n, 27/08/2025\n */\n\n\nconst { ensureTokens, pickPart, postGraphQL, parseNdjsonOrJson } = require('../../../utils/marketplaceUtils');\n\nmodule.exports = function getMarketplaceProductModule(defaultFuncs, api, ctx) {\n  return function getMarketplaceProduct(targetId, callback) {\n    let resolveFunc = () => {};\n    let rejectFunc = () => {};\n    const promise = new Promise((resolve, reject) => { resolveFunc = resolve; rejectFunc = reject; });\n\n    if (typeof targetId === \"function\") { callback = targetId; targetId = null; }\n    callback = callback || function (err, data) { if (err) return rejectFunc(err); resolveFunc(data); };\n\n    (async () => {\n      try {\n        if (!targetId) throw new Error(\"targetId is required\");\n        if (typeof api.refreshFb_dtsg === \"function\") { try { await api.refreshFb_dtsg(); } catch {} }\n        ensureTokens(ctx);\n\n        // 1) Details\n        const detailsVars = {\n          feedbackSource: 56,\n          feedLocation: \"MARKETPLACE_MEGAMALL\",\n          referralCode: \"null\",\n          scale: 1,\n          targetId,\n          useDefaultActor: false,\n          __relay_internal__pv__CometUFIShareActionMigrationrelayprovider: true,\n          __relay_internal__pv__GHLShouldChangeSponsoredDataFieldNamerelayprovider: true,\n          __relay_internal__pv__GHLShouldChangeAdIdFieldNamerelayprovider: true,\n          __relay_internal__pv__CometUFI_dedicated_comment_routable_dialog_gkrelayprovider: false,\n          __relay_internal__pv__IsWorkUserrelayprovider: false,\n          __relay_internal__pv__CometUFIReactionsEnableShortNamerelayprovider: false,\n          __relay_internal__pv__MarketplacePDPRedesignrelayprovider: false\n        };\n        const DOC_ID_DETAILS = \"24056064890761782\";\n        const detailsPayload = await postGraphQL(defaultFuncs, ctx, detailsVars, DOC_ID_DETAILS);\n        const detailsSelected = pickPart(detailsPayload, (p) => p?.data?.viewer?.marketplace_product_details_page);\n        const base = normalizeDetails(detailsSelected);\n\n        // 2) Images\n        const DOC_ID_IMAGES = \"10059604367394414\";\n        const imgForm = {\n          fb_dtsg: ctx.fb_dtsg,\n          jazoest: ctx.jazoest,\n          av: ctx.userID || (ctx.globalOptions && ctx.globalOptions.pageID),\n          variables: JSON.stringify({ targetId }),\n          doc_id: DOC_ID_IMAGES\n        };\n        const imgRes = await defaultFuncs.post(\"https://www.facebook.com/api/graphql/\", ctx.jar, imgForm);\n        const imgJson = parseNdjsonOrJson(imgRes && imgRes.body ? imgRes.body : \"{}\");\n        const imgSelected = Array.isArray(imgJson)\n          ? imgJson.find((p) => p?.data?.viewer?.marketplace_product_details_page) || imgJson[0]\n          : imgJson;\n        base.images = normalizeImages(imgSelected);\n\n        return callback(null, base);\n      } catch (err) {\n        return callback(err);\n      }\n    })();\n\n    return promise;\n  };\n\n  function n(x) { return Number.isFinite(+x) ? +x : null; }\n\n  function normalizeDetails(payload) {\n    const page = payload?.data?.viewer?.marketplace_product_details_page;\n    const item = page?.target || page?.marketplace_listing_renderable_target || null;\n    const price = item?.listing_price || {};\n    const coords = item?.location || item?.item_location || null;\n\n    return {\n      id: item?.id ?? null,\n      title: item?.marketplace_listing_title ?? item?.base_marketplace_listing_title ?? null,\n      description: item?.redacted_description?.text ?? null,\n      price: {\n        amount: n(price.amount),\n        amountString: price.amount ?? null,\n        formatted: price.formatted_amount_zeros_stripped ?? price.formatted_amount ?? null,\n        currency: price.currency ?? null,\n        strikethrough:\n          item?.strikethrough_price?.formattedAmountWithoutDecimals ??\n          item?.strikethrough_price?.formatted_amount ??\n          null\n      },\n      status: {\n        isLive: !!item?.is_live,\n        isPending: !!item?.is_pending,\n        isSold: !!item?.is_sold\n      },\n      location: {\n        text: item?.location_text?.text ?? null,\n        latitude: coords?.latitude ?? null,\n        longitude: coords?.longitude ?? null,\n        locationId: item?.location_vanity_or_id ?? null\n      },\n      delivery: {\n        types: item?.delivery_types ?? [],\n        shippingOffered: !!item?.is_shipping_offered,\n        buyNowEnabled: !!item?.is_buy_now_enabled\n      },\n      attributes: Array.isArray(item?.attribute_data)\n        ? item.attribute_data.map((a) => ({ name: a?.attribute_name ?? null, value: a?.value ?? null, label: a?.label ?? null }))\n        : [],\n      category: {\n        id: item?.marketplace_listing_category_id ?? null,\n        slug: item?.marketplaceListingRenderableIfLoggedOut?.marketplace_listing_category?.slug ?? null,\n        name: item?.marketplaceListingRenderableIfLoggedOut?.marketplace_listing_category_name ?? null,\n        seo: (() => {\n          const catSeo = item?.marketplaceListingRenderableIfLoggedOut?.seo_virtual_category?.taxonomy_path?.[0];\n          return {\n            categoryId: catSeo?.id ?? null,\n            seoUrl: catSeo?.seo_info?.seo_url ?? null,\n            name: catSeo?.name ?? null\n          };\n        })()\n      },\n      shareUrl: item?.share_uri ?? null,\n      createdAt: item?.creation_time ? new Date(item.creation_time * 1000).toISOString() : null,\n      images: []\n    };\n  }\n\n  function normalizeImages(selected) {\n    const page = selected?.data?.viewer?.marketplace_product_details_page;\n    const target = page?.target || page?.marketplace_listing_renderable_target || {};\n    const photos = Array.isArray(target?.listing_photos) ? target.listing_photos : [];\n\n    const fromPhotos = photos\n      .map((p) => ({\n        id: p?.id ?? null,\n        url: p?.image?.uri ?? null,\n        width: p?.image?.width ?? null,\n        height: p?.image?.height ?? null,\n        alt: p?.accessibility_caption ?? null\n      }))\n      .filter((img) => !!img.url);\n\n    const fromPrefetch = Array.isArray(selected?.extensions?.prefetch_uris)\n      ? selected.extensions.prefetch_uris.map((u) => ({ id: null, url: u, width: null, height: null, alt: null }))\n      : [];\n\n    const seen = new Set();\n    return [...fromPhotos, ...fromPrefetch].filter((img) => {\n      if (seen.has(img.url)) return false;\n      seen.add(img.url);\n      return true;\n    });\n  }\n};",
  "language": "javascript",
  "createdAt": 1756349648956,
  "updatedAt": 1756349648956
}