How to use @storefront-api/lib - 10 common examples

To help you get started, we’ve selected a few @storefront-api/lib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DivanteLtd / storefront-api / src / modules / default-vsf / api / product.ts View on Github external
productApi.get('/render-list', (req, res) => {
    const productProxy = _getProxy(req)

    if (!req.query.skus) { return apiStatus(res, 'skus parameter is required', 400); }

    productProxy.renderList(req.query.skus.split(','), req.query.currencyCode, (req.query.storeId && parseInt(req.query.storeId) > 0) ? req.query.storeId : 1).then((result) => {
      result.items = result.items.map((item) => {
        let sgnObj = item
        if (config.tax.calculateServerSide === true) {
          sgnObj = { priceInclTax: item.price_info.final_price }
        } else {
          sgnObj = { price: item.price_info.extension_attributes.tax_adjustments.final_price }
        }

        item.sgn = hmac.sign(sgnSrc(sgnObj, item), config.objHashSecret); // for products we sign off only price and id becase only such data is getting back with orders
        return item
      })
      apiStatus(res, result, 200);
    }).catch(err => {
      apiError(res, err);
github DivanteLtd / storefront-api / src / modules / default-vsf / api / product.ts View on Github external
productProxy.renderList(req.query.skus.split(','), req.query.currencyCode, (req.query.storeId && parseInt(req.query.storeId) > 0) ? req.query.storeId : 1).then((result) => {
      result.items = result.items.map((item) => {
        let sgnObj = item
        if (config.tax.calculateServerSide === true) {
          sgnObj = { priceInclTax: item.price_info.final_price }
        } else {
          sgnObj = { price: item.price_info.extension_attributes.tax_adjustments.final_price }
        }

        item.sgn = hmac.sign(sgnSrc(sgnObj, item), config.objHashSecret); // for products we sign off only price and id becase only such data is getting back with orders
        return item
      })
      apiStatus(res, result, 200);
    }).catch(err => {
      apiError(res, err);
github DivanteLtd / storefront-api / src / modules / default-vsf / api / order.ts View on Github external
create (req, res) {
    const ajv = new Ajv();
    require('ajv-keywords')(ajv, 'regexp');

    const orderSchema = require('../models/order.schema.js.js')
    let orderSchemaExtension = {}
    if (fs.existsSync('../models/order.schema.extension.json')) {
      orderSchemaExtension = require('../models/order.schema.extension.json')
    }
    const validate = ajv.compile(merge(orderSchema, orderSchemaExtension));

    if (!validate(req.body)) { // schema validation of upcoming order
      console.dir(validate.errors);
      apiStatus(res, validate.errors, 400);
      return;
    }
    const incomingOrder = { title: 'Incoming order received on ' + new Date() + ' / ' + req.ip, ip: req.ip, agent: req.headers['user-agent'], receivedAt: new Date(), order: req.body }/* parsed using bodyParser.json middleware */
    console.log(JSON.stringify(incomingOrder))

    for (let product of req.body.products) {
      let key = config.tax.calculateServerSide ? { priceInclTax: product.priceInclTax, id: null, sku: null } : { price: product.price, id: null, sku: null }
      if (config.tax.alwaysSyncPlatformPricesOver) {
        key.id = product.id
      } else {
        key.sku = product.sku
      }
      // console.log(key)

      if (!config.tax.usePlatformTotals) {
        if (!hmac.verify(key, product.sgn, config.objHashSecret)) {
github DivanteLtd / storefront-api / src / modules / default-vsf / api / order.ts View on Github external
const incomingOrder = { title: 'Incoming order received on ' + new Date() + ' / ' + req.ip, ip: req.ip, agent: req.headers['user-agent'], receivedAt: new Date(), order: req.body }/* parsed using bodyParser.json middleware */
    console.log(JSON.stringify(incomingOrder))

    for (let product of req.body.products) {
      let key = config.tax.calculateServerSide ? { priceInclTax: product.priceInclTax, id: null, sku: null } : { price: product.price, id: null, sku: null }
      if (config.tax.alwaysSyncPlatformPricesOver) {
        key.id = product.id
      } else {
        key.sku = product.sku
      }
      // console.log(key)

      if (!config.tax.usePlatformTotals) {
        if (!hmac.verify(key, product.sgn, config.objHashSecret)) {
          console.error('Invalid hash for ' + product.sku + ': ' + product.sgn)
          apiStatus(res, 'Invalid signature validation of ' + product.sku, 200);
          return;
        }
      }
    }

    if (config.orders.useServerQueue) {
      try {
        let queue = kue.createQueue(Object.assign(config.kue, { redis: config.redis }));
        const job = queue.create('order', incomingOrder).save((err) => {
          if (err) {
            console.error(err)
            apiError(res, err);
          } else {
            apiStatus(res, job.id, 200);
          }
        })
github DivanteLtd / storefront-api / src / modules / default-catalog / api / catalog.js View on Github external
resultProcessor.process(_resBody.hits.hits).then((result) => {
            _resBody.hits.hits = result
            _cacheStorageHandler(config, _resBody, reqHash, tagsArray)
            res.json(_resBody);
          }).catch((err) => {
            console.error(err)
          })
        }
      } else { // no cache storage if no results from Elastic
        res.json(_resBody);
      }
    });
  }

  if (config.server.useOutputCache && cache) {
    cache.get(
      'api:' + reqHash
    ).then(output => {
      if (output !== null) {
        res.setHeader('X-VS-Cache', 'Hit')
        res.json(output)
        console.log(`cache hit [${req.url}], cached request: ${Date.now() - s}ms`)
      } else {
        res.setHeader('X-VS-Cache', 'Miss')
        console.log(`cache miss [${req.url}], request: ${Date.now() - s}ms`)
        dynamicRequestHandler()
      }
    }).catch(err => console.error(err))
  } else {
    dynamicRequestHandler()
  }
}
github DivanteLtd / storefront-api / src / platform / magento1 / tax.js View on Github external
client.search(esQuery).then((result) => { // we're always trying to populate cache - when online
          inst._taxClasses = es.getHits(result).map(el => { return el._source })
          for (let item of productList) {
            const isActive = checkIfTaxWithUserGroupIsActive(inst._storeConfigTax)
            if (isActive) {
              groupId = getUserGroupIdToUse(inst._userGroupId, inst._storeConfigTax)
            } else {
              groupId = null
            }

            inst.taxFor(item._source, groupId)
          }

          resolve(productList)
        }).catch(err => {
          reject(err)
github DivanteLtd / storefront-api / src / modules / default-vsf / platform / magento2 / tax.js View on Github external
client.search(esQuery).then((body) => { // we're always trying to populate cache - when online
          inst._taxClasses = es.getHits(body).map(el => { return el._source })
          for (let item of productList) {
            const isActive = checkIfTaxWithUserGroupIsActive(inst._storeConfigTax)
            if (isActive) {
              groupId = getUserGroupIdToUse(inst._userGroupId, inst._storeConfigTax)
            } else {
              groupId = null
            }

            inst.taxFor(item._source, groupId)
          }

          resolve(productList)
        }).catch(err => {
          reject(err)
github DivanteLtd / storefront-api / src / modules / default-vsf / platform / magento2 / tax.js View on Github external
return new Promise((resolve, reject) => {
      inst.applyTierPrices(productList, groupId)

      if (this._config.tax.calculateServerSide) {
        const client = es.getClient(this._config)
        const esQuery = es.adjustQuery({
          index: this._indexName,
          body: bodybuilder()
        }, 'taxrule', this._config)
        client.search(esQuery).then((body) => { // we're always trying to populate cache - when online
          inst._taxClasses = es.getHits(body).map(el => { return el._source })
          for (let item of productList) {
            const isActive = checkIfTaxWithUserGroupIsActive(inst._storeConfigTax)
            if (isActive) {
              groupId = getUserGroupIdToUse(inst._userGroupId, inst._storeConfigTax)
            } else {
              groupId = null
            }

            inst.taxFor(item._source, groupId)
          }
github DivanteLtd / storefront-api / src / platform / magento1 / tax.js View on Github external
return new Promise((resolve, reject) => {
      inst.applyTierPrices(productList, groupId)

      if (this._config.tax.calculateServerSide) {
        const client = es.getClient(this._config)
        const esQuery = es.adjustQuery({
          index: this._indexName,
          body: bodybuilder()
        }, 'taxrule', this._config)

        client.search(esQuery).then((result) => { // we're always trying to populate cache - when online
          inst._taxClasses = es.getHits(result).map(el => { return el._source })
          for (let item of productList) {
            const isActive = checkIfTaxWithUserGroupIsActive(inst._storeConfigTax)
            if (isActive) {
              groupId = getUserGroupIdToUse(inst._userGroupId, inst._storeConfigTax)
            } else {
              groupId = null
            }

            inst.taxFor(item._source, groupId)
          }
github DivanteLtd / storefront-api / src / modules / template-module / graphql / hello / resolver.ts View on Github external
testElastic: async (_, { sku }, { db, config }, rootValue) => {
      const client = db.getElasticClient()
      const esQuery = es.adjustQuery({
        index: 'vue_storefront_catalog', // current index name
        type: 'product',
        body: bodybuilder().filter('terms', 'visibility', [2, 3, 4]).andFilter('term', 'status', 1).andFilter('terms', 'sku', sku).build()
      }, 'product', config)
      const response = es.getResponseObject(await client.search(esQuery)).hits.hits.map(el => { return el._source })
      if (response.length > 0) return response[0]; else return null
    }
  }