【问题标题】:How to implement an authenticated es 7 decorator with babel for my js service module如何使用 babel 为我的 js 服务模块实现经过身份验证的 es 7 装饰器
【发布时间】:2026-01-28 06:50:01
【问题描述】:

我在我的 Flux Fluxible js 项目中使用带有装饰器 stage:0 支持的 babel,并且我想为我的服务 api 模块使用经过身份验证的装饰器来检查有效的用户会话。

四处搜索,似乎有几篇文章解释了不同的变化,但找不到一个权威的文档或说明。

这是我到目前为止所尝试的,我知道我的身份验证函数的参数不正确,并且不确定我是否需要为我的模块实现一个类,而不仅仅是使用导出对象。

我找不到文档的部分是如何实现装饰器本身 - 在这种情况下,装饰函数将接收并检查它的 req 参数。

// how do I change this method so that it can be implemented as a decorator
function checkAuthenticated(req) {

    if (!req.session || !req.session.username)
    {
        throw new Error('unauthenticated');
    }
}

module.exports = {
    @checkAuthenticated
    read: function(req, resource, params, serviceConfig, callback) {
        //@authenticated decorator should allow me to move this out of this here
        //checkAuthenticated(req);
        if (resource === 'product.search') {
            var keyword = params.text;
            if (!keyword || keyword.length === 0) {
                return callback('empty param', null);
            } else {
                searchProducts(keyword, callback);
            }
        }

    }
};

【问题讨论】:

  • 装饰器会将您的 read 方法作为参数,而不是现在的请求。你以前是怎么做到的(注释掉的部分)会正常工作,那有什么问题?
  • 被注释掉的部分工作得很好——但我对学习如何使用装饰器很好奇,所以把它当作一种学习的可能性。使用装饰器如何将读取方法中的 req 参数获取到检查函数中?
  • 看我的回答,应该可以的。 @decorator 只是 decorator(methodToDecorate) 的简写
  • 我在一个类属性和控制台中有它。记录装饰器的参数显示这个 {"0":{},"1":"read","2":{"enumerable" :false,"可配置":true,"可写":true}}
  • 对不起,我的错误,类(我如何使用它们)与类属性的签名不同。查看我更新的答案和 jsbin。

标签: javascript node.js decorator babeljs ecmascript-2016


【解决方案1】:
class Http{
  @checkAuthenticated
  read(req, resource, params, serviceConfig, callback) {
    if (resource === 'product.search') {
      var keyword = params.text;
      if (!keyword || keyword.length === 0) {
        return callback('empty param', null);
      } else {
        this.searchProducts(keyword, callback);
      }
    }
  }

  searchProducts(keyword, callback) {
    callback(null, 'worked');
  }
}

function checkAuthenticated(target, key, descriptor) {
    return {
      ...descriptor,
      value: function(){
        console.log(arguments);
        const req = arguments[0];
        if (!req.session || !req.session.username) {
            throw new Error('unauthenticated');
        }
        return descriptor.value.apply(this, arguments);
      }
    };
}

let h = new Http();

h.read(
  { session: { username: 'user' } },
  'product.search',
  { text: 'my keywords' },
  null,
  function(err, result) {
    if (err) return alert(err);
    return alert(result);
  }
);

见jsbinhttp://jsbin.com/yebito/edit?js,console,output

【讨论】:

  • 刚刚试了一下,得到了以下错误TypeError: Cannot read property 'apply' of undefined /node_modules/fluxible-plugin-fetchr/node_modules/fetchr/libs/fetcher.js:181 service[op].apply(service, args);
  • 看起来装饰器函数的签名实际上是期望(目标,键,描述符)而不是我的情况下的函数(fn)
最近更新 更多