为了账号安全,请及时绑定邮箱和手机立即绑定

Node.js 中服务层的结构应该是什么

Node.js 中服务层的结构应该是什么

拉风的咖菲猫 2022-12-18 16:04:18
背景信息:我正在尝试使用单独的 Controller、Service 和 Dao 层来实现我的服务器。我不确定应该如何组织服务层模块。例如,让我们考虑一个UserService模块,它是服务层模块中的子模块。但是,我不想创建单个UserService文件,而是将其分成单独的文件,例如,一个FetchUsers类是用户服务的一部分,并且将具有不同的获取用户的方法,filterBySomething(params)其中也包括一些业务逻辑,所以他们需要在服务层。如果我不将“UserService”划分为单独的模块,那么单个模块中的内容就会过多,并且也会违反 SRP。问题:我可以想到两种实现此目的的方法,哪种更好?如果有比这两种更好的方法,或者我不应该尝试实现这一点,请提出替代方案。方法一:- services  - user    - index.js - directly exports modules inside user service    - FetchUser    - CreateUserThe index.js will do something like this:FetchUser = require('./FetchUser');module.exports = {  FetchUser: FetchUser}Controller will use it as:UserService.FetchUser.filterBySomething()方法二:- services  - user    - index.js - exports methods of individual modules, not the modules themselves    - FetchUser    - CreateUserThe index.js will do something like this:FetchUser = require('./FetchUser');module.exports = {  filterBySomething: FetchUser.filterBySomething}Controller will use it as:UserService.filterBySomething()方法 1 看起来它没有足够的封装。方法 2 有很好的封装,但它需要我在用户服务中维护 index.js 每当我想从任何文件中添加/删除任何内容时。
查看完整描述

1 回答

?
梦里花落0921

TA贡献1772条经验 获得超5个赞

方法 2看起来不错,因为封装。


另一种可以节省大量时间的方法是在 index.js中自动导出

(对于任何服务,index.js 都是相同的,并且每次在同一目录中更改/添加模块并重新启动时都会自我更新你的服务器)


我不是代码优化专家,但这行得通


// index.js (for ALL services)

const fs = require('fs')

const path = require('path')


let fileNames = fs.readdirSync('.')

// use Sync to not create Async errors elsewere

  .filter(name => name.endsWith('.js') && name !== __filename)

  // only get js files and exclude this file

  .map(name => './' + path.relative(__dirname, name))

  // get relative paths


let methods = {}

// the future export of this file


fileNames.forEach(file => {

  try {

    let fileModule = require(file) 

    // try to require the module

    Object.keys(fileModule).forEach(method => {

    // for each method/key of the module

      methods[method] = fileModule[method]

      // add this method to the exports of this file (methods)

    })

  } catch (err) {

    console.log('WARNING:\n' + err.message)

    // probably couldn't require the module

  }

})


module.exports = methods

// you export all the exported methods

// of all the js files of the same directory


显然,您应该在每个模块中仅导出“公共”方法


class FetchUser {

  static filterBySomething (arg) {

    // do your magik

  }

  static method2 (arg) {

    // another method

  }

}


module.exports = FetchUser

// this will make ALL methods of class FetchUser accessible in index


module.exports = {

  filterBySomething: FetchUser.filterBySomething

}

// if you want other methods like method2 to NOT be exported


查看完整回答
反对 回复 2022-12-18
  • 1 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信