import Shopify from 'cpb-shopify';
import Datastore from 'cpb-datastore';
import { getBinaryFlagValue, stringifyJSON, title } from 'cpb-common';
export const CACHE = new Map();
/**
*
* @return {Promise<Object|{maps: {names: {}, ids: {}}, data: {}}>}
* @example
* js
* {
* multi_location_enabled: true,
* shopID: 13878489,
* email: 'Chloe@slateplate.com',
* enabled_presentment_currencies: [ 'USD' ],
* visitor_tracking_consent_preference: 'allow_all',
* pre_launch_enabled: false,
* longitude: -75.251347,
* weight_unit: 'lb',
* myshopify_domain: 'slateplate.myshopify.com',
* created_at: '2016-07-15T21:43:09-04:00',
* finances: true,
* iana_timezone: 'America/New_York',
* country: 'US',
* setup_required: false,
* eligible_for_card_reader_giveaway: true,
* tax_shipping: null,
* google_apps_domain: null,
* address1: '251 Irving Street',
* datastore_inserted_at: 2021-12-30T08:18:22.412Z,
* force_ssl: true,
* plan_name: 'basic',
* city: 'Honesdale',
* zip: '18431',
* province: 'Pennsylvania',
* county_taxes: true,
* country_code: 'US',
* customer_email: 'info@slateplate.com',
* requires_extra_payments_agreement: false,
* shopName: 'slateplate',
* updated_at: '2021-12-12T19:25:12-05:00',
* google_apps_login_enabled: null,
* source: null,
* currency: 'USD',
* money_with_currency_in_emails_format: '${{amount}} USD',
* plan_display_name: 'Basic Shopify',
* shop_owner: 'Chloe Nicolini',
* country_name: 'United States',
* has_discounts: true,
* money_in_emails_format: '${{amount}}',
* checkout_api_supported: true,
* primary_location_id: 61838622917,
* auto_configure_tax_inclusivity: null,
* eligible_for_payments: true,
* password_enabled: false,
* money_format: '${{amount}}',
* has_storefront: true,
* timezone: '(GMT-05:00) America/New_York',
* province_code: 'PA',
* latitude: 41.5741673,
* phone: '570-493-9063',
* primary_locale: 'en',
* taxes_included: false,
* id: 13878489,
* has_gift_cards: false,
* money_with_currency_format: '${{amount}} USD',
* name: 'Slateplate',
* address2: '',
* cookie_consent_level: 'implicit',
* domain: 'www.slateplate.com'
* },
* @param {?object} [filter]
* @param {?(boolean|number|string|undefined)} [fetch]
*/
export async function get(filter = {}, fetch) {
const query = {
kind: 'shopify_shops',
order: 'shopName',
filter,
},
cacheKey = stringifyJSON(query);
if (!fetch && CACHE.has(cacheKey)) {
title(`[api/middleware/shop/get][CACHE_HIT] ${cacheKey}
size: ${CACHE.size} hasEntry: ${CACHE.has(cacheKey)}`);
return CACHE.get(cacheKey);
}
console.info(`[api/middleware/shop/get[${filter.shopName}]`, { filter });
if (fetch && filter.shopName) {
console.info(`[api/middleware/shop/get][${filter.shopName}][fetch=${fetch}] requesting shopData from Shopify`, filter);
return await Shopify.getShopData(filter.shopName, fetch);
}
const entries = await Datastore.query(query),
maps = {
ids: {},
names: {},
},
data = {};
console.debug(`[api/middleware/shop/get][${filter.shopName}] length: ${entries.length}`);
for (const shop of entries) {
// console.debug({ shop });
data[shop.shopName] = shop;
maps.ids[shop.id] = shop.shopName;
maps.names[shop.shopName] = shop.id;
}
const result = query.filter ? entries[0] : { maps, data };
CACHE.set(cacheKey, result);
return result;
}
export default async function ShopMiddleware(req, res) {
if (!res.locals.shop) throw new TypeError('!res.locals.shop');
const { id, name: shopName } = res.locals.shop || {},
fetch = getBinaryFlagValue(req.query.fetch, 0),
debug = {
id,
shopName,
fetch,
request: {
query: req.query,
params: req.params,
locals: req.locals,
},
timestamp: new Date(),
};
console.info(`[api/middleware/shop][${id},${shopName}] DEBUG`, debug);
let status = 200,
result;
try {
if (shopName) {
result = await get({ shopName }, fetch);
}
} catch (error) {
console.error(`[api/middleware/shop][${id},${shopName}] ERROR_LIST_DATA`, error);
status = 500;
error.rid = res.locals.rid;
result = error;
} finally {
res.type('json').status(status).end(stringifyJSON(result));
}
}