<think>好的,我需要帮助用户使用TypeScript、NestJS、TypeORM和MySQL来创建表结构,并实现一个自动抓取API数据并保存的接口。首先,我应该分析用户的具体需求。
用户提到的API返回的数据结构是怎样的呢?假设接口返回的data字段包含date、price、changepercent、maxprice、minprice、openingprice、lastclosingprice这些字段。需要将这些字段映射到数据库表中,date用日期类型,其他用数值类型,比如decimal或float。
接下来是实体类的创建。在NestJS中,使用TypeORM可以通过装饰器定义实体。每个字段对应数据库表中的一列,类型需要正确设置。例如,date字段可以用Date类型,其他数值字段用decimal或float。主键通常使用自增的id。
然后,需要配置TypeORM连接到MySQL。这需要在app.module.ts中设置数据库连接参数,包括类型、主机、端口、用户名、密码、数据库名,以及实体和同步选项。
接下来是服务的编写。用户需要一个定时任务来定期调用外部API。NestJS提供了@nestjs/schedule模块,可以方便地创建定时任务。同时,使用axios或http模块来发送HTTP请求获取数据。获取到数据后,通过TypeORM的repository将数据保存到数据库中。
控制器的部分需要提供一个接口,可能用于手动触发数据抓取,或者查看数据。但根据用户需求,主要是一个自动抓取的接口,所以可能控制器部分可以简单一些,或者根据是否需要手动触发来设计。
另外,需要考虑错误处理,比如API调用失败时的重试机制,或者数据库保存失败时的日志记录。还有数据类型的转换,确保API返回的字符串数值能正确转换为数据库的数值类型。
最后,测试整个流程,确保实体正确创建,数据库表结构符合预期,定时任务能正常运行,数据能正确插入。
可能遇到的问题包括TypeORM的配置错误,MySQL连接问题,或者API返回数据格式变化导致解析失败。需要提醒用户处理这些异常情况,并在代码中添加相应的错误处理逻辑。</think>我将分步骤说明如何使用NestJS+TypeORM+MySQL实现该需求:
1. 创建实体类(src/entities/gold-price.entity.ts):
```typescript
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class GoldPrice {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: 'date', unique: true })
date: Date;
@Column({ type: 'decimal', precision: 10, scale: 2 })
price: number;
@Column({ type: 'decimal', precision: 5, scale: 2 })
changepercent: number;
@Column({ type: 'decimal', precision: 10, scale: 2 })
maxprice: number;
@Column({ type: 'decimal', precision: 10, scale: 2 })
minprice: number;
@Column({ name: 'opening_price', type: 'decimal', precision: 10, scale: 2 })
openingprice: number;
@Column({ name: 'last_closing_price', type: 'decimal', precision: 10, scale: 2 })
lastclosingprice: number;
}
```
2. 配置数据库连接(app.module.ts):
```typescript
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'yourpassword',
database: 'gold_price',
entities: [GoldPrice],
synchronize: true, // 开发环境使用,生产环境应关闭
}),
TypeOrmModule.forFeature([GoldPrice])
]
})
export class AppModule {}
```
3. 创建定时任务服务(src/services/fetch.service.ts):
```typescript
import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { GoldPrice } from '../entities/gold-price.entity';
import { Cron } from '@nestjs/schedule';
@Injectable()
export class FetchService {
constructor(
private readonly httpService: HttpService,
@InjectRepository(GoldPrice)
private readonly goldPriceRepository: Repository<GoldPrice>
) {}
@Cron('0 0 9 * * *') // 每天9点执行
async fetchData() {
try {
const response = await this.httpService.axiosRef.get('https://api.pearktrue.cn/api/goldprice');
const data = response.data.data;
const goldPrice = this.goldPriceRepository.create({
date: new Date(data.date),
price: parseFloat(data.price),
changepercent: parseFloat(data.changepercent),
maxprice: parseFloat(data.maxprice),
minprice: parseFloat(data.minprice),
openingprice: parseFloat(data.openingprice),
lastclosingprice: parseFloat(data.lastclosingprice)
});
await this.goldPriceRepository.save(goldPrice);
} catch (error) {
console.error('数据获取失败:', error);
}
}
}
```
4. 创建API控制器(src/controllers/gold-price.controller.ts):
```typescript
import { Controller, Get } from '@nestjs/common';
import { GoldPrice } from '../entities/gold-price.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
@Controller('gold-prices')
export class GoldPriceController {
constructor(
@InjectRepository(GoldPrice)
private readonly goldPriceRepository: Repository<GoldPrice>
) {}
@Get()
async getAll() {
return this.goldPriceRepository.find({
order: { date: 'DESC' },
take: 30
});
}
}
```
关键要点说明:
1. 数据库字段使用decimal类型确保金融数据精度,其中:
- price/maxprice/minprice等主价格字段使用`precision: 10, scale: 2`
- changepercent使用`precision: 5, scale: 2`存储百分比变化
2. 定时任务使用@nestjs/schedule模块实现自动抓取,需要安装依赖:
```bash
npm install @nestjs/schedule axios
```
3. 日期字段使用MySQL的DATE类型存储,通过TypeORM的date类型自动转换
4. 数据库操作使用Repository模式,通过依赖注入实现松耦合[^1]