Retrieve product information as JSON with Stencil Utils

本小妞迷上赌 提交于 2019-12-12 13:22:12

问题


Using stencil-utils, I can retrieve product information for a given product ID. However, I can't find any documentation on how to retrieve the information as a JSON response as opposed to an HTML template.

Right now, I'm using the following code:

utils.api.product.getById(
    847,
    {},
    (err, resp) => {
        console.log(resp);
    }
)

I'm hoping there's a parameter I can pass in the params object that will return the response as JSON so I can extract just the information I need about the product.


回答1:


Using { params: { debug: "context" } } will work great on the local environment created using stencil start, however once you bundle & upload your theme to a live site, it stops working. The debugging tools debug: "context" and debug: "bar" are disabled on production.

After reaching out to bigcommerce support, which originally linked me to this SO question, it seems this is their proposed workflow:

You will have to use a dummy handlebars template, include the variables you need, and use the custom handlebars helper provided by bigcommerce, {{json}} - which seems to just run JSON.stringify() - the helper is defined here.

utils.api.product.getById(
    847, { template: 'path/to/template' }, (err, resp) => {
        // Will print the name of the product.
        console.log(resp.product.title);
    });

I have had success with path/to/template being custom/template-name and placing the handlebars template in the templates/components/custom folder. I have not tested passing it a template from another source.




回答2:


So it looks like you can pass additional parameters by adding a param object to the options. With debug: "context", you can retrieve the entire context of the page, and you can then get the product information by accessing response.product.

utils.api.product.getById(
    847,
    { params: { debug: "context" } },
    (err, resp) => {
        // Will print the name of the product.
        console.log(resp.product.title);
    }
)


来源:https://stackoverflow.com/questions/35090421/retrieve-product-information-as-json-with-stencil-utils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!