基于typeScript和nodejs的API项目目录结构

以下是如何按照之前讨论的组织结构对你的代码进行剥离和重构的完整示例。

文件结构

project-root-directory/
|-- bin/
|   |-- www
|
|-- common/
|   |-- MySQLConnector.ts
|
|-- routes/
|   |-- index.ts
|
|-- package.json
|-- tsconfig.json
|-- app.ts

1. bin/www

bin/目录下,创建一个名为www的文件,并添加以下内容:

#!/usr/bin/env node
import app from '../app';
import http from 'http';

const port = 3000;
app.set('port', port);

const server = http.createServer(app);

server.listen(port);
server.on('listening', () => {
    console.log(`Server is running at http://localhost:${port}/`);
});

确保这个文件是可执行的(在Unix/Linux下,运行chmod +x bin/www)。

2. common/MySQLConnector.ts

这个文件保持不变。

3. routes/index.ts

routes/目录下,创建一个名为index.ts的文件,并添加以下内容:

import express from 'express';
import { MySQLConnector } from '../common/MySQLConnector';

const router = express.Router();

router.get('/', async (req, res) => {
    const connector = new MySQLConnector();
    try {
        const connection = await connector.getConnection();

        // Use the connection for database operations
        const [rows] = await connection.execute('SELECT * FROM fb_user');
        console.log('Query result:', rows);

        // Release the connection when done
        connector.releaseConnection(connection);
        
        res.send('Hello TypeScript with Express!');
    } catch (error) {
        console.error('Error:', error);
        res.status(500).send('Internal Server Error');
    }
});

export default router;

4. app.ts

最后,在app.ts文件中,只包含与应用设置相关的代码,并导入路由:

import express from 'express';
import indexRouter from './routes/index';

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use('/', indexRouter);

export default app;

5. package.json

package.json文件的scripts部分,你可以像这样更新dev脚本:

{
    "scripts": {
        "dev": "nodemon --watch 'common/**/*' --watch 'routes/**/*' --watch 'bin/**/*' -e ts,tsx --exec ts-node bin/www"
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值