从外部文件调用停止代码执行

时间:2016-09-26 14:07:51

标签: javascript node.js

这是一个nodejs设置。如果用户不在管理员组中,目标是阻止某些代码执行:

这是在file1.js:

export function adminAuthRequired( req, res) {
if ( req.session.user_group !== "admin") {
    const message = "You are not  authorized to access this content."

    boundaries.redirectToPage( res, message, "redirect-default-page.ejs")

}

}

这是从file1.js调用函数的file2.js:

public destroy( slug ) {
    utils.adminAuthRequired( this.req, this.res) // Here we include file1 function
    // Code needs to stop execution here if user is not admin

    // Query db for user details
    db.deleteSingleRecord( this.res, "links", `WHERE link_slug = ${slug}`, callback )

    // ... rest of code....
}

在file2中调用adminAuthRequired之后是否还要停止代码执行?在file1中处理执行停止?

我可以简单地在file2中对从文件1返回的bool执行if语句,但是我想知道是否有办法将它全部嵌入到file1中?

1 个答案:

答案 0 :(得分:0)

您可以使用回调方法..

例如

....
  .Terms("Students", t => t
          .Field("name")
          .Size(50)
          .Aggregations(aa => aa
            .Cardinality("Count", co => co
              .Field("_parent"))))))));

然后调用 - >

export function adminAuthRequired( req, res, cb) {
    if ( req.session.user_group !== "admin") {
        const message = "You are not  authorized to access this content."
        boundaries.redirectToPage( res, message, "redirect-default-page.ejs")
    } else cb();
}