我正在用nodejs、express和mysql开发restAPI。现在我有一个app.js,它是应用程序的起点。
在app.js中,我初始化用户控制器:
const router: express.Router = express.Router();
new UserController(router);
用户控制器如下所示:
import { Request, Response, Router } from 'express';
import UserModel from '../model/user';
class UserController {
constructor(private router: Router) {
router.get('/users', async (req: Request, resp: Response) => {
try {
// const users = get Users with mysql
// resp.status(200).send(users);
} catch (error) {
resp.send({
msg: 'Not found',
status: 404
});
}
});
}
}
export default UserController;
现在我想要一个DatabaseController来处理数据库周围的一切,比如提供连接、关闭它等等:
class DatabaseController {
constructor() {
}
}
export default DatabaseController;
如何在DatabaseController中打开连接并让UserController简单地访问它?如果不初始化DatabaseController并给UserController一个参数“dbConnection”,这是否可能?
最佳答案
是的,这是可能的。我不完全熟悉typescript,所以下面是一些psuedo代码。未经测试。
在另一个文件中的某个位置,配置数据库连接和服务:
import { MyConnection } from 'my-db-package';
class DatabaseService {
private connection: MyConnection
constructor(db: MyConnection) {
this.connection = db;
}
// Return the promise if any.
// Don't want to handle the error here.
// Let your controller handle the error
async openConnection() {
return this.connection.open()
}
async closeConnection() {
return this.connection.close()
}
async getAllUsers() {
return this.connection.query('SELECT * FROM USERS;')
}
}
export default DatabaseService;
import { Database } from 'my-db-driver'
import { DatabaseService } from 'my-db-service'
// Don't actually connect here
// Just create the object so it's ready for connection.
const connection = new Database({
// config
})
// Wire up the internal db connection
// Remember this is a singleton.
export default new DatabaseService(connection)
下一步用新的数据库服务连接控制器:
import { Request, Response } from 'express';
import { DatabaseService } from './my-service'
class UserController {
private dbService: DatabaseService;
constructor(dbService: DatabaseService) {
this.dbService = dbService;
}
async connect() {
return this.dbService.openConnection()
}
async close() {
return this.dbService.closeConnection()
}
async getAllUsers(req: Request, res: Response) {
let users
try {
users = await this.dbService.getAllUsers();
} catch (error) {
// ...
}
res.json(users)
}
}
export default UserController;
然后连接你的路线:
import { express } from 'express'
import { UserController } from 'user-controller'
import { DatabaseService } from 'database-service'
const userController = new UserController(DatabaseService);
const router: express.Router = express.Router();
router.get('/users', userController.getAllUsers)
// ...
export default router
最后,将您的路线与主要的Express应用程序连接起来:
import { express } from 'express'
import { userRoutes } from 'user-routes'
const app = express()
app.use(userRoutes)
// ..
同样,上述代码未经测试,可能无法使用。这是给你一个例子,一种方法。你可能会找到一个更好的方法来做,但这就是要点。