有没有办法用自定义控制器覆盖sails.js 水线端点,但保持内置分页和过滤? [英] Is there a way to override sails.js waterline endpoint with custom controller, but keep built in pagination, and filtering?

查看:34
本文介绍了有没有办法用自定义控制器覆盖sails.js 水线端点,但保持内置分页和过滤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个模型,我喜欢分页,并用水线和蓝图过滤掉盒子.但是,我需要为所有请求添加一个 where 子句.我不是要添加 where 的客户.我仍然想要获得所有神奇的sails.js 分页和过滤器,尽管我在创建覆盖控制器时丢失了.

I have defined a model, and I like that I get pagination, and filtering out of the box with waterline and blueprint. However, I need to add a where clause to all requests. I don't wasn't the client to add the where. I still want to get all the magical sails.js pagination and filters though that I lose when I create an override controller.

有谁知道如何拿到我的蛋糕并吃掉它?

Does anyone know how to get my cake and eat it too?

推荐答案

我最初采用了 arbuthnott 建议的路线,但是我很沮丧,因为它仅适用于蓝图而不适用于水线 ORM.我希望在我的 API 中保持一致的行为.由于sails 使用mixin 的方式,它对monkeypatch 有点棘手,因为在实例化时ORM 方法没有添加到模型中.

I initially went the route that arbuthnott suggested, however I was frustrated that it only worked for blueprint and not waterline ORM. I wanted consistent behavior across my API. Because of the way that sails uses mixins its a bit tricky to monkeypatch because at instantiation time the ORM methods are not added to the models.

它的工作方式是使用钩子,一旦加载了 ORM,它将使用合并到您的 defaultScope 标准中的 find 对每个方法进行猴子修补.与策略相比,这样做的好处是它适用于水线 ORM 和蓝图,以便您获得一致的行为

在要添加条件的每个模型中,添加以下范围:

In each model you want to add a criteria to, add the following scope:

defaultScope: {
  where: {
    status: {
      '>': 0,
      '>=': sails.config.catalogVersions.status,
    },
  },
},

在 api/hooks 中添加一个包含以下内容的新文件:

in api/hooks add a new file with the following:

const _ = require('lodash');
const _monkeyPatch = (model, method) => {
  const _method = model[method];
  model[method] = (...args) => {
    let criteria = args[0] || {};
    criteria = _.merge(model.defaultScope || {}, criteria);
    args[0] = criteria;
    return _method.apply(model, args);
  };
};
const applyScopeToFinds = (model) => {
  _monkeyPatch(model, 'find');
  _monkeyPatch(model, 'findOne');
  _monkeyPatch(model, 'findOrCreate');
  _monkeyPatch(model, 'count');
};

module.exports = (sails) => {
  return {
    initialize: async (next) => {
      sails.on('hook:orm:loaded', () => {
        _.forEach(sails.models, (model) => applyScopeToFinds(model));
      });
      return next();
    },
  };
};

这篇关于有没有办法用自定义控制器覆盖sails.js 水线端点,但保持内置分页和过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆