在 NodeJS 中公开函数的更好方法?

Better way to expose functions in NodeJS?

我有一个目录,用于保存我的所有 DAO 文件,其中包含与 MySQL 服务器交互的方法。

我的 DAO 目录如下所示

| -- dao
  | -- user.dao.ts
  | -- employee.dao.ts

我的控制器目录如下所示

| -- controller
  | -- user.controller.ts
  | -- employee.controller.ts

每个 DAO 文件都包含可能具有相同名称的函数,例如:

function insertOne() {}

function insertMany() {}

我在我的控制器文件中使用这些 DAO 函数,我在一个控制器文件中导入多个 DAO 文件,因为我想在一个控制器中使用多个 DAO 函数

我有两种方法可以从 DAO 文件导出函数:

第一种方法:

export function insertOne() {}

export function insertMany() {}

第二种方法:

function insertOne() {}

function insertMany() {}

export default {
  insertOne,
  insertMany
};

我知道最好导出单个函数,因为我们只能导入该文件中需要的函数,但在我的情况下,函数名称会发生​​冲突,那么,最好的处理方法应该是什么用这个 ?

如果我使用第一种方法,我会在我的控制器中做类似的事情

import * as userDAO from "../dao/user.dao.ts";
import * as empDAO from "../dao/emp.dao.ts";

// import { insertOne } from "../dao/user.dao.ts"; // can't do this as name would clash

userDAO.insertOne();
empDAO.insertOne();

如果我使用第二种方法,我会在我的控制器中做类似的事情

import userDAO from "../dao/user.dao.ts";
import empDAO from "../dao/emp.dao.ts";

userDAO.insertOne();
empDAO.insertOne();

我在每个 DAO 文件中保留相同名称的方法是否做错了什么?寻找可以添加到我的代码中的建议和类似方法。

您也可以使用 as 语法重命名命名导入:

import {insertOne as userInsertOne} from "../dao/user.dao.ts";
import {insertOne as empInsertOne} from "../dao/emp.dao.ts";
//You can use shorter names if you want, of course...

userInsertOne();
empInsertOne();

第二种方法没有错,我不认为你有成千上万的文件。那么,如果您要导出几个不会被使用的函数,那有什么问题呢?人们正在导入 lodash 库,使用了其中的 5%。我想你太关注这个了。

但我的建议是创建 classes。做一个

class DAOModel {
  insertOne () {}
  insertMany () {}
}

并在您的文件中创建 classes 继承 DAOModel 并传递此 class 的实例,可能会使所有方法成为静态的

或者只创建对象

const personsDAO = {
  insertOne() {...},
  insertMany() {...},
}

export default personsDAO

那你就忘记头痛了