nodejs项目的正确打开方式,typescript + koa

koa + typescript

typescript + tslint 规范化代码,选择typeorm作为数据库的orm,选择log4js输出日志

1. 目录结构

├── bin
│   └── www.ts // 启动应用
├── logs // 存放日志
├── src 
│   ├── app
│   │   ├── components // 控制器组件
│   │   │   ├── account
│   │   │   │   ├── account.controller.ts
│   │   │   │   └── account.service.ts
│   │   │   └── user
│   │   │       ├── user.controller.ts
│   │   │       └── user.service.ts
│   │   ├── constants // 常量
│   │   │   └── index.ts
│   │   ├── core // 一些核心类或全局引用的方法
│   │   │   ├── error.ts
│   │   │   └── logger.ts
│   │   ├── database // 数据库连接
│   │   │   └── index.ts
│   │   ├── entities // 实体
│   │   │   └── user
│   │   │       ├── user.entity.ts
│   │   │       └── user.model.ts
│   │   ├── middleware // 中间件
│   │   │   ├── error.middleware.ts
│   │   │   ├── jwt.middleware.ts
│   │   │   ├── logger.middleware.ts
│   │   │   └── response.middleware.ts
│   │   └── utils // 工具函数
│   │   │   └── crypto.ts
│   │	└── app.ts // 应用启动类
│   └── environments  // 多环境配置
│       ├── env.dev.ts
│       ├── env.prop.ts
│       └── index.ts
├── nodemon.json // nodemon 配置, watch ts文件
├── package-lock.json
├── package.json
├── tsconfig.json
└── tslint.json

2. package.json

{
   
  "name": "huzz-koa-template",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
   
    "@koa/cors": "^3.0.0",
    "koa": "^2.11.0",
    "koa-body": "^4.1.1",
    "koa-jwt": "^3.6.0",
    "koa-route-decors": "^1.0.3",
    "koa-router": "^7.4.0",
    "koa-static": "^5.0.0",
    "log4js": "^5.3.0",
    "mysql2": "^2.0.0",
    "reflect-metadata": "^0.1.13",
    "typeorm": "^0.2.20"
  },
  "devDependencies": {
   
    "@types/jsonwebtoken": "^8.3.5",
    "@types/koa": "^2.0.52",
    "@types/koa-router": "^7.0.42",
    "@types/koa-static": "^4.0.1",
    "@types/koa__cors": "^2.2.3",
    "cross-env": "^6.0.3",
    "nodemon": "^1.19.4",
    "ts-node": "^8.5.0",
    "tslint": "^5.20.1",
    "tslint-config-standard": "^9.0.0",
    "typescript": "^3.7.2"
  },
  "scripts": {
   
    "dev": "cross-env NODE_ENV=development nodemon --config nodemon.json",
    "compile": "tsc",
    "start": "npm run compile && pm2 start ./bin/www --name app",
    "restart": "npm run compile && pm2 start ./dist/app/app.js",
    "stop": "pm2 stop app"
  },
  "repository": {
   
    "type": "git",
    "url": "git+https://github.com/xhuz/huzz-koa-template.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
   
    "url": "https://github.com/xhuz/huzz-koa-template/issues"
  },
  "homepage": "https://github.com/xhuz/huzz-koa-template#readme"
}

3. 开始

1. core
  1. 自定义错误,
    // error.ts
    // 继承自原生Error类, 方便抛出各类异常
    export class CustomError extends Error {
          
      code: number;
      constructor(code: number, message: string) {
         
        super(message);
        this.code = code;
      }
    }
    
  2. 配置logger
    // logger.ts 具体配置自行查看log4js 文档
    import {
         configure, getLogger} from 'log4js';
    import {
         resolve} from 'path';
    import {
         Context} from 'koa';
    
    const logPath = resolve(__dirname, '../../../logs'); // log存放路径,确保该路径存在
    
    configure({
         
      appenders: {
         
        console: {
         type: 'console'},
        dateFile: {
         type: 'dateFile', filename: `${
           logPath}/log.log`, pattern: 'yyyy-MM-dd', alwaysIncludePattern: true, keepFileExt: true}
      },
      categories: {
         
        default: {
         
          appenders: ['console', 'dateFile'],
          level: 'info'
        },
        mysql: {
         
          appenders: ['console', 'dateFile'],
          level: 'info'
        }
      }
    });
    
    export const logger = getLogger('default');
    export const</
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个比较具体的问题,我尽量给出详细的回答。 首先,你需要了解每个工具的作用: - Node.js: 一个基于 Chrome V8 引擎的 JavaScript 运行时,可用于构建高性能的网络应用程序。 - Midway.js: 一个基于 Egg.js 的 Serverless Node.js 框架,提供了函数计算、API 网关等 Serverless 场景下的解决方案。 - Koa: 一个基于 Node.js 平台的 Web 开发框架,旨在提供更小、更富有表现力、更健壮的 Web 应用程序。 - TypeScript: 是 JavaScript 的一个超集,可以编译成纯 JavaScript。 接下来,你可以按照以下步骤进行开发: 1. 创建一个基于 Midway.js 的应用程序: ``` $ npm init midwayjs-app jsapi ``` 2. 安装需要的依赖: ``` $ cd jsapi $ npm install koa koa-bodyparser koa-router cross-env --save $ npm install @midwayjs/koa @midwayjs/faas @midwayjs/socketio --save $ npm install typescript ts-node @types/node --save-dev ``` 3. 创建 TypeScript 配置文件 `tsconfig.json`: ``` { "extends": "@midwayjs/tsconfig/tsconfig.json", "compilerOptions": { "outDir": "dist", "rootDir": "src" }, "include": ["src"] } ``` 4. 创建一个简单的 TypeScript 控制器: ``` import { Provide, Controller, Get, Post, Body } from '@midwayjs/decorator'; import { Context } from 'koa'; @Provide() @Controller('/api') export class ApiController { @Get('/hello') async hello(ctx: Context) { ctx.body = 'Hello Midwayjs'; } @Post('/share') async share(@Body() body) { const { url } = body; // 解析分享链接 // ... // 返回解析结果 return { title, desc }; } } ``` 5. 创建 Koa 应用程序: ``` import { App, Config, Inject } from '@midwayjs/decorator'; import { ILifeCycle, IMidwayApplication } from '@midwayjs/core'; import { Application } from 'egg'; import * as bodyParser from 'koa-bodyparser'; import * as Router from 'koa-router'; @Config() export class AppConfig implements ILifeCycle { @Inject() app: IMidwayApplication; async onReady() { const app = this.app.getApplication() as Application; // 添加中间件 app.use(bodyParser()); app.use(app.get('koaRouter').routes()); // 启动应用程序 app.listen(3000, () => { console.log('Server listening on http://localhost:3000'); }); } } @App() export class ApiApplication implements ILifeCycle { @Inject() app: IMidwayApplication; async onReady() { const router = this.app.getApplicationContext().get('koaRouter') as Router; router.get('/api/hello', async (ctx) => { ctx.body = 'Hello Koa'; }); } } ``` 6. 启动应用程序: ``` $ npm run dev ``` 7. 使用 curl 或者 Postman 等工具测试 API: ``` $ curl -X GET http://localhost:3000/api/hello ``` ``` $ curl -X POST http://localhost:3000/api/share -d '{"url": "http://example.com"}' ``` 这样,一个基于 Node.js、Midway.js、KoaTypeScript 的 API 解析程序就完成了。当然,这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值