# typescript-boot

`typescript-boot` 是一个面向 TypeScript 后端项目的轻量脚手架，目标是让你用较少的样板代码，快速搭建并发布 HTTP API 服务与 WebSocket 服务。

它当前提供的核心能力包括：

- HTTP 接口服务发布
- WebSocket 服务发布
- 在线接口文档
- Session 与权限管理
- Redis 接入
- 数据库统一访问抽象与 MySQL 实现
- 文件上传与下载
- 邮件发送
- 自定义行为日志

完整示例项目可参考：

- https://github.com/seeksdream/typescript-boot-demo

## 安装

```bash
npm install typescript-boot reflect-metadata
```

如果你使用 TypeScript，请确保开启：

- `experimentalDecorators`
- `emitDecoratorMetadata`

并且在入口文件最先执行：

```ts
import 'reflect-metadata';
```

## HTTP 快速开始

```ts
import 'reflect-metadata';
import {
  BaseService,
  SeeksWebServer,
  apiDoc,
  apiParamFromBody,
  apiPath,
  apiReturn
} from 'typescript-boot';

@apiDoc('账号服务')
@apiPath('/account')
class AccountService extends BaseService {
  @apiDoc('登录')
  @apiReturn('登录结果')
  @apiPath('login')
  async login(
    @apiParamFromBody('登录账号') account: string,
    @apiParamFromBody('登录密码') password: string
  ) {
    return this.success({
      account,
      token: 'demo-token'
    });
  }
}

const server = new SeeksWebServer(3333);
server.publishService(new AccountService());
server.start();
```

启动后可访问：

- `http://localhost:3333/account/login`
- `http://localhost:3333/typescript-boot`

## WebSocket 快速开始

```ts
import 'reflect-metadata';
import {
  BaseSocketService,
  SeeksWebServer,
  apiPath
} from 'typescript-boot';

@apiPath('/chat')
class ChatSocketService extends BaseSocketService {
  async onConnected(client) {
    client.sendAction('connected', {
      clientId: client.id
    });
  }

  @apiPath('echo')
  async echo(client, data) {
    return this.success({
      echo: data
    });
  }
}

const server = new SeeksWebServer(3333);
server.publishSocketService(new ChatSocketService());
server.start();
```

客户端连接地址：

- `ws://localhost:3333/chat`

客户端发送消息示例：

```json
{
  "action": "echo",
  "requestId": "r1",
  "data": {
    "text": "hello"
  }
}
```

## 使用手册

建议按下面顺序阅读：

- [完整脚手架使用手册](docs/typescript-boot-user-manual.md)
- [接口Service、接口方法、WebSocket服务使用手册](docs/service-websocket-manual.md)
- [路径规则说明](docs/api-path-rules.md)
- [作者说明](docs/from-author.md)
- [下个版本新特性设计](docs/next-version-feature.md)

## 一些关键规则

- `接口Service` 的 `@apiPath()` 只能使用单段路径，例如 `/account`
- `接口方法` 的 `@apiPath()` 支持多段路径和变量路径，例如 `oauth/:provider/authorizeUrl`
- 如果接口方法没有写 `@apiPath()`，默认使用方法名作为访问路径
- `BaseService` 和 `BaseSocketService` 中的普通实例方法会被视为可发布接口或动作，不建议把辅助函数直接写在 service 类里

## 在线文档

默认情况下，框架会自动发布在线文档页面：

- `http://localhost:端口/typescript-boot`

效果如下：

![简单示例效果图](readme-images/typescript-boot-doc.png)
