0

我试图将我的控制器分离到它们自己的文件中并利用 OOP,我的问题是如何分离辅助函数?我不是在谈论会被大量使用的实用功能,我指的是您创建的功能只是为了使您的代码更清晰并且只使用一次。

app.js

const express = require('express');

const app = express();

const routes = require('./routes');

app.use('/', routes);

routes/index.js

const express = require('express');
const router = express.Router();

const user = require('./user');
router.use('/user', user);

routes/user.js

const express = require('express');
const router = express.Router();

const User = require('./controllers/user');

router.get('/', User.getUser);
router.post('/', User.addUser);
router.put('/', User.updateUser);

controllers/user.js

class User {
  static getUser(req, res) {
    // example of getting a user
  }

  static async addUser(req, res) {
    const { username } = req.body;

    if (!username) {
      throw customError(res, 'username is required', 400);
    }

    const exists = await database.find(username);
    if (exists) {
      throw customError(res, 'user with this username already exists.', 409);
    }

    // generate unique id for user
    const id = await genId();

    const user = {
      id,
      username,
    };
    await database.create(user);

    res.status(201).send({
      success: true,
      user,
    });

    // I'm talking about these functions

    function getNum() {
      return Math.floor(1000 + Math.random() * 9000);
    }

    async function isIdUnique(id) {
      const exists = await database.findById(id);
      return !!exists;
    }

    async function genId() {
      const id = getNum();
      const isUnique = await isIdUnique(id);
      if (!isUnique) {
        return genId();
      }
      return id;
    }
  }

  static updateUser(req, res) {
    // example of updating a user
  }
}

我认为我的问题更多是关于结构,但任何提示/技巧都非常感谢!

4

1 回答 1

2

也许您可以将您的实用程序函数分隔在其他目录中,即我将其命名/utilities并将实用程序函数放入其中。

在其中,您可以将函数分类为子级用法:lib, data, ...

/
|- index.js
|- /contollers
|- /routes
|- /models
|- /utils
|-|- /data
|-|- /lib
|- /node_modules
|- package.json
...

我经常使用这种配置。

因此,您可以将与 DB 相关的函数放入utils/data,并将其他杂项函数放入utils/lib,...等。

于 2020-05-10T01:53:02.367 回答