UNPKG

shopify-currencies.js

Version:

Simple wrapper to access Shopify's currency conversion rates from Node.js

52 lines (46 loc) 1.49 kB
'use strict'; const vm = require('node:vm'); function _interopNamespaceCompat(e) { if (e && typeof e === 'object' && 'default' in e) return e; const n = Object.create(null); if (e) { for (const k in e) { n[k] = e[k]; } } n.default = e; return n; } const vm__namespace = /*#__PURE__*/_interopNamespaceCompat(vm); const SHOPIFY_CDN_URL = "https://cdn.shopify.com/s/javascripts/currencies.js"; async function loadCurrencies() { const response = await fetch(SHOPIFY_CDN_URL); if (!response.ok) { throw new Error( `Failed to fetch currencies from Shopify CDN (${SHOPIFY_CDN_URL}): ${response.statusText}` ); } const code = await response.text(); const ctx = {}; try { vm__namespace.createContext(ctx); vm__namespace.runInContext(code, ctx); } catch (e) { const message = e instanceof Error ? e.message : "Unknown error"; throw new Error( `Failed to parse currencies from Shopify CDN (${SHOPIFY_CDN_URL}): ${message}` ); } if (!ctx.Currency || typeof ctx.Currency !== "object") { throw new Error("Invalid currencies: Currency is not an object"); } const { rates, convert } = ctx.Currency; if (!rates || typeof rates !== "object") { throw new Error("Invalid currencies: rates is not an object"); } if (!convert || typeof convert !== "function") { throw new Error("Invalid currencies: convert is not a function"); } return { rates, convert }; } exports.loadCurrencies = loadCurrencies;