Source: api/middleware/product.js

import app from 'cpb-api';
import { getBinaryFlagValue } from 'cpb-common';
import Product from '../product/index.js';
import Datastore from 'cpb-datastore';
import CPBMiddleware from './cpb.js';

/**
 * @method module:cpb-api/middleware.product
 * @param {Request} req
 * @param {string|number} req.params.id
 * @param {string|number} req.params.shop_id
 * @param {boolean} req.query.fetch
 * @param {boolean} req.query.versions
 * @param {boolean} req.query.files
 * @param {Response} res
 * @param {NextFunction} next
 * @returns {Promise<ProductList|Product|undefined>}
 */
export default async function ProductMiddleware(req, res, next) {
  if (req.method !== 'GET' && req.method !== 'HEAD') {
    res.statusCode = req.method === 'OPTIONS' ? 200 : 405;
    res.setHeader('Allow', 'GET, HEAD, OPTIONS');
    res.setHeader('Content-Length', '0');
    res.end();
    return next();
  }
  //const id = req.params.id,
  const id = req.params.productIdOrHandle,
        //shop_id = res.locals.shopIdOrName,
        shop_id = res.locals.shop.id,
        bucket = app.get('bucket'), // versions =
        fetch = getBinaryFlagValue(req.query.fetch, 0),
        versions = getBinaryFlagValue(req.query.versions, 0),
        files = getBinaryFlagValue(req.query.files, 0), // req.query.versions || true,
        debug = {
          params: req.params,
          query: req.query,
          id,
          shop_id,
          bucket, // versions,
          fetch,
          versions,
          files,
  };

  let data, entries, DSQuery;

  // missing prefix means no storeId was passed as the parameter and we return all stores
  if (!id) {
    // const [ids, misc, legacy] = await getShopifyStoreIds(bucket);
    try {
      DSQuery = {
        kind: 'shopify_products',
        filter: {
          'shopName': `${res.locals.shop.name}`,
        },
      };
      data = await Datastore.query(DSQuery);
      entries = data.map(entry => {
        const buf = {
          "node": {
            "id": entry.admin_graphql_api_id,
            "title": entry.title,
            "description": entry.body_html,
            "featuredImage": {
              "id": entry.image ? entry.image.admin_graphql_api_id : null,
              "src": entry.image ? entry.image.src : null,
              "transformedSrc": entry.image ? entry.image.src : null  ///  !!! CHECK what difference between src and transformedSrc
            },
            "handle": entry.handle
          }
        }
        return buf;
      })
      //cacheKey = stringifyJSON(DSQuery);
      //data = await Product.list({ bucket, shop_id, files, fetch, versions });
      //      title('[api/product/middleware.list::data', { ...data.stats, debug });
    } catch (error) {
      console.error(`ProductListError::[gs://${bucket}/${shop_id}`, error);
      throw error;
    }
  } else {
    try {
      DSQuery = {
        kind: 'shopify_products',
        filter: {
          'shopName': `${res.locals.shop.name}`,
          'id': +id
        },
      };
      //cacheKey = stringifyJSON(DSQuery);
      entries = await Datastore.query(DSQuery);
      console.log(id, ' ', shop_id, ' ', bucket, ' ', files, ' ', fetch, ' ', versions);
      data = await Product.get({ id, shop_id, bucket, files, fetch, versions });
      //      title('ProductMiddleware.ProductGet', { ...data.stats, debug });
    } catch (error) {
      console.error(`ProductGetError::[gs://${bucket}/${shop_id}/${id}]`, error);
      throw error;
    }
  }
  //res.json({ ...data, debug});
  res.json({ products: {edges: entries}, debug});
  res.end();
}