簡體   English   中英

Sails.js-如何為所有模型綁定自定義藍圖操作?

[英]Sails.js - how to bind Custom blueprint action for all the models?

我已經在文件api / blueprints / count.js中創建了一個自定義的藍圖操作計數。

我想將此操作推廣到所有模型。 問題是當我添加這樣的自定義藍圖操作時

         'get /:model/count': {blueprint: 'count'}

我在提升應用程序時遇到此錯誤:

           error: count :: Ignoring attempt to bind route (/:model/count) to blueprint action (`count`), but no valid model was specified and we couldn't guess one based on the path.

我通過在配置屬性中指定型號名稱來解決問題

        'get /:model/count': {blueprint: 'count', model: 'user'}

或在地址中指定

         'get /user/count': {blueprint: 'count'}

這樣指定的問題是我還需要為其他所有模型添加路由。 有什么辦法可以將這種方法推廣到類似“ get /:model / count”這樣的內容:{blueprint:'count'}。

如果我們具有此功能,那就太好了。

請幫忙。

為此,我們實現了自定義鈎子。 您可以將其添加到您的api/hooks文件夾中。

/**
 * Adds support for count blueprint and binds :model/count route for each RESTful model.
 */

import _ from 'lodash';
import actionUtil from 'sails/lib/hooks/blueprints/actionUtil';
import pluralize from 'pluralize';

const defaultCountBlueprint = (req, res) => {
  let Model = actionUtil.parseModel(req);
  let countQuery = Model.count();

  countQuery.then(count => res.ok({count}));
};

export default function (sails) {
  return {
    initialize: cb => {
      let config = sails.config.blueprints;
      let countFn = _.get(sails.middleware, 'blueprints.count') || defaultCountBlueprint;

      sails.on('router:before', () => {
        _.forEach(sails.models, model => {
          let controller = sails.middleware.controllers[model.identity];

          if (!controller) return;

          let baseRoute = [config.prefix, model.identity].join('/');

          if (config.pluralize && _.get(controller, '_config.pluralize', true)) {
            baseRoute = pluralize(baseRoute);
          }

          let route = baseRoute + '/count';

          sails.router.bind(route, countFn, null, {controller: model.identity});
        });

      });

      cb();
    }
  }
};

基於@ghaiklor的答案/代碼,我創建了sails可安裝鈎子 sails -hook-blueprint-count”以啟用count藍圖api方法。

可通過npm存儲庫( https://www.npmjs.com/package/sails-hook-blueprint-count )獲得“ sails-hook-blueprint-count”軟件包,您可以使用以下命令進行安裝

npm install sails-hook-blueprint-count

命令。

然后,當您抬起帆應用程序時,可以使用以下路線

GET /:model/count

要么

GET /:model/count?where={:criteria}

:criteria與在find where藍圖方法( http://sailsjs.org/documentation/reference/blueprint-api/find-where )中的相同。

響應將是json,格式為

{數:COUNT個}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM