带有Typescript的NodeJS MySQL中的DatabaseController [英] DatabaseController in NodeJS MySQL with Typescript
问题描述
我正在使用nodejs,express和mysql开发restAPI.现在,我有了一个app.js,这是该应用程序的起点.
I am developing a restAPI with nodejs, express and mysql. Now I have a app.js which is the starting point of the App.
在app.js中,我初始化了UserController:
Within app.js I initialize the UserController:
const router: express.Router = express.Router();
new UserController(router);
UserController看起来像这样:
The UserController looks like this:
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,关闭它等等.
Now I would like to have a DatabaseController which handels everything around the Database like providing a Connection, closing it and so on:
class DatabaseController {
constructor() {
}
}
export default DatabaseController;
如何实现在DatabaseController中打开连接并让UserController轻松访问该连接?如果不初始化DatabaseController并给UserController一个参数"dbConnection",是否有可能实现?
How can I achieve that I open the connection in the DatabaseController and let the UserController simply access it? Is that even possible without initializing the DatabaseController and giving the UserController a parameter "dbConnection"?
推荐答案
是的.我对打字稿不是很熟悉,所以下面有一些伪代码. 未经测试.
Yes it's possible. I'm not entirely familiar with typescript so some psuedo code below. Untested.
在另一个文件的某处,配置数据库连接和服务:
Somewhere in another file, configure your database connection and the service:
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)
下一步,使用新的数据库服务连接控制器:
Next wire up your controller with the new database service:
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应用程序连接您的路线:
Finally, hook up your routes with the main Express app:
import { express } from 'express'
import { userRoutes } from 'user-routes'
const app = express()
app.use(userRoutes)
// ..
同样,以上代码未经测试,可能无法使用.它旨在为您提供一种方法的示例.您可能会找到一种更好的方法来做到这一点,但这就是要点.
Again, the above code is untested and likely unusable. It is meant to give you an example of one approach. You may find a better way to do it, but that's the gist of it.
这篇关于带有Typescript的NodeJS MySQL中的DatabaseController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!