如何在LoopBack框架中禁用PersistedModel的某些HTTP方法(例如POST)

问题描述 投票:3回答:6

在LoopBack框架中创建模型时,可以从PersistedModel类继承。这样就生成了所有HTTP方法。我想知道如何禁用某些HTTP方法?

一种选择是使用空逻辑覆盖PersistedModel中的函数,但希望方法从Swagger API资源管理器中消失。

javascript loopbackjs
6个回答
3
投票

我在下面的model.js文件中做了以下。这使得表只读。

module.exports = function(model) {

    var methodNames = ['create', 'upsert', 'deleteById','updateAll',
                      'updateAttributes','createChangeStream','replace','replaceById',
                      'upsertWithWhere','replaceOrCreate'
                     ];

    methodNames.forEach(function(methodName) {
        disableMethods(model,methodName)
    });
}


function disableMethods(model,methodName)
{
if(methodName!='updateAttributes')
model.disableRemoteMethod(methodName, true);
else
model.disableRemoteMethod(methodName, false); 
}

1
投票

唯一需要额外注意的是禁用自定义模型方法(如User.login)。您需要在资源管理器中间件之前调用disableRemoteMethod:https://github.com/strongloop/loopback/issues/686


1
投票

关于Santhosh Hirekerur的更新答案是让它隐藏LB3上的所有内容,停止使用弃用的Model.disableRemoteMethod方法以及更智能的方法来隐藏updateAttributes以及可能同样有效的任何其他未来方法。

我检查方法是否在原型上,如果是,请在prototype.之前使用disableRemoteMethodByName作为名称的前缀:

module.exports = function (model) {

    var methodNames = [
        'create',
        'upsert',
        'deleteById',
        'updateAll',
        'updateAttributes',
        'patchAttributes',
        'createChangeStream',
        'findOne',
        'find',
        'findById',
        'count',
        'exists',
        'replace',
        'replaceById',
        'upsertWithWhere',
        'replaceOrCreate'
    ];

    methodNames.forEach(function (methodName) {
        if (!!model.prototype[methodName]) {
            model.disableRemoteMethodByName('prototype.' + methodName);
        } else {
            model.disableRemoteMethodByName(methodName);
        }
    });

}

我将上面的代码放在server/middleware/disable-methods.js中并从类似的模型中调用它:

var disableMethods = require('../../server/middleware/disable-methods');

module.exports = function (Model) {
    disableMethods(Model);
}

1
投票

在文档中找到答案。例如,这会禁用PersistedModel.deleteById:

var isStatic = true;
MyModel.disableRemoteMethod('deleteById', isStatic);

所以看起来你不可能同时禁用所有DELETE操作。例如,方法PersistedModel.deleteAll在给定示例中仍然可访问。

开发人员必须明确禁用PersistedModel类中的每个相关方法。

Relevant docs are here

部分:

  • 隐藏方法和REST端点
  • 隐藏相关模型的端点

In case of loopback 3


0
投票

我有同样的问题。

我的第一个解决方案是手动更新"public":true中的server/model-configuration.json项目,但是当我使用Swagger工具刷新LoopBack API(使用项目根目录中的slc loopback:swagger myswaggerfilename命令)时,它被覆盖了。

我终于写了一个Grunt任务作为可靠的解决方法。

  • slc loopback:swagger生成之后或在运行API之前运行它。
  • 你只需要在javascript数组list_of_REST_path_to_EXPOSE中指定我想要公开的路径的名称
  • 并确保您对原始/server/model-config.json文件的备份文件夹感到满意。

我希望与你分享以防万一:

https://github.com/FranckVE/grunt-task-unexpose-rest-path-loopback-swagger

基本上:

module.exports = function (grunt) {

  grunt.registerTask('unexpose_rest_path_for_swagger_models_v1', function (key, value) {
    try {
      // Change the list below depending on your API project :
      // list of the REST paths to leave Exposed
      var list_of_REST_path_to_EXPOSE =
        [
          "swagger_example-api_v1",
          "write_here_the_paths_you_want_to_leave_exposed"
        ];

      // Location of a bakup folder for modified model-config.json (change this according to your specific needs):
      var backup_folder = "grunt-play-field/backups-model-config/";

      var src_folder = "server/";
      var dest_folder = "server/";
      var src_file_extension = ".json";
      var src_file_root_name = "model-config";

      var src_filename = src_file_root_name + src_file_extension;
      var dest_filename = src_file_root_name + src_file_extension;
      var src = src_folder + src_filename;
      var dest = dest_folder + dest_filename;
      var free_backup_file = "";

      if (!grunt.file.exists(src)) {
        grunt.log.error("file " + src + " not found");
        throw grunt.util.error("Source file 'model-config.json' does NOT exists in folder '" + src_folder + "'");
      }

      // timestamp for the backup file of model-config.json
      var dateFormat = require('dateformat');
      var now = new Date();
      var ts = dateFormat(now, "yyyy-mm-dd_hh-MM-ss");

      // backup model-config.json
      var root_file_backup = src_file_root_name + "_bkp" + "_";
      var root_backup = backup_folder + root_file_backup;
      free_backup_file = root_backup + ts + src_file_extension;
      if (!grunt.file.exists(root_file_backup + "*.*", backup_folder)) {
        //var original_file = grunt.file.read(src);
        grunt.file.write(free_backup_file, "// backup of " + src + " as of " + ts + "\n");
        //grunt.file.write(free_backup_file, original_file);
        grunt.log.write("Creating BACKUP"['green'] + " of '" + src + "' " + "to file : "['green'] + free_backup_file + " ").ok();
      } else {
        grunt.log.write("NO BACKUP created"['red'] + " of '" + src + "' " + "because file : " + free_backup_file + " ALREADY EXISTS ! "['red']).error();
        throw grunt.util.error("Destination backup file already exists");
      }

      // load model-config.json
      var project = grunt.file.readJSON(src);//get file as json object

      // make modifications in model-config.json
      for (var rest_path in project) {
        if (rest_path.charAt(0) === "_") {
          grunt.log.write("SKIPPING"['blue'] + " the JSON item '" + rest_path + "' belonging to the " + "SYSTEM"['blue'] + ". ").ok();
          continue; // skip first level items that are system-related
        }
        if (list_of_REST_path_to_EXPOSE.indexOf(rest_path) > -1) { //
          project[rest_path]["public"] = true;
          grunt.log.write("KEEPING"['green'] + " the REST path '" + rest_path + "' " + "EXPOSED"['green'] + ". ").ok();
        } else {
          project[rest_path]["public"] = false;
          grunt.log.writeln("HIDING"['yellow'] + " REST path '" + rest_path + "' : it will " + "NOT"['yellow'] + " be exposed.");
        }
      }

}

0
投票

我想要隐藏PATCH方法,但是当我试图隐藏它时我也隐藏了PUT方法,我正在使用这一行:

 Equipment.disableRemoteMethod('updateAttributes', false); 

但后来我发现了一种只隐藏PATCH方法的方法,这条线对我来说非常适合。

 Equipment.sharedClass.find('updateAttributes', false).http = [{verb: 'put', path: '/'}];

上面的行会覆盖updateAttributes方法具有的原始http。

[{verb:'put',path:'/'},{verb:'patch',path:'/'}]

© www.soinside.com 2019 - 2024. All rights reserved.