根据第 3 方 API 响应创建小部件 select 类型字段

Create widget select type field based on 3rd party API response

我们开始基于第 3 方 API 在 Apostrophe CMS 中开发站点,但遇到了以下问题:

场景如下:管理员从列表中选择一个产品,我们将在前端显示基于该 selection 的信息。

const request = require( 'request-promise' );

module.exports = {
    extend: 'apostrophe-widgets',
    label: 'Preloaded list widget',
    addFields: [
        {
            label: 'Product',
            name: 'product',
            type: 'select',
            required: true,
            choices: "getChoices"
        }
    ],

    getChoices: async function( req )
    {
        const products = await request( {
            uri: "http://API_for_product_list",
            json: true
        } );

        var choiceList = [];
        for( idx = 0; idx < products.totalRecords; idx++ )
        {
            var option =
            {
                label: products.items[ idx ].label,
                value: products.items[ idx ].value
            };

            choiceList.push( option );
        }

        return choiceList;
    }
};


当我启动应用程序时,我收到以下警告: "widget类型preloadedlist,字段名product: 使用 showFields 时,field.choices 必须是一个数组” 列表显示为空。从未调用 getChoices 函数。

我遗漏了一些东西,但我不知道是什么。我们按照文档做了一切。

您必须将 getChoices 函数附加到模块本身,以便以后可以引用它。

const request = require('request-promise');

module.exports = {
  extend: 'apostrophe-widgets',
  label: 'Preloaded list widget',
  addFields: [{
    label: 'Product',
    name: 'product',
    type: 'select',
    required: true,
    choices: 'getChoices'
  }],
  construct: function(self, options) {
    self.getChoices = async function (req) {
      const products = await request({
        uri: "http://API_for_product_list",
        json: true
      });

      var choiceList = [];
      for (idx = 0; idx < products.totalRecords; idx++) {
        var option = {
          label: products.items[idx].label,
          value: products.items[idx].value
        };

        choiceList.push(option);
      }
      return choiceList;
    }
  }
};