我正在使用nodejs,express和mysql开发restAPI。现在,我有一个app.js,这是该应用程序的起点。
在app.js中,我初始化了UserController:
const router: express.Router = express.Router();
new UserController(router);
UserController看起来像这样:
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来处理数据库中的所有内容,例如提供一个Connection,关闭它等等。
class DatabaseController {
constructor() {
}
}
export default DatabaseController;
如何实现在DatabaseController中打开连接并让UserController轻松访问该连接?在不初始化DatabaseController并将UserController参数设置为“ dbConnection”的情况下,这是否有可能?
最佳答案
是的,有可能。我对打字稿不是很熟悉,所以下面有一些伪代码。未经测试。
在另一个文件中的某个位置,配置数据库连接和服务:
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)
// ..
同样,以上代码未经测试,可能无法使用。它旨在为您提供一种方法的示例。您可能会找到一种更好的方法来做到这一点,但这就是要旨。
关于mysql - 带有Typescript的NodeJS MySQL中的DatabaseController,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55472992/