Commit 947ffcc1 by yixinjj

添加prisma 支持

1 parent ca0d3ca9
...@@ -4,4 +4,4 @@ ...@@ -4,4 +4,4 @@
# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB. # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
# See the documentation for all the connection string options: https://pris.ly/d/connection-strings # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
DATABASE_URL="mysql://user_limin:LmotGSOY@192.168.3.113:3306/app_admin"
\ No newline at end of file \ No newline at end of file
DATABASE_URL="mysql://user_limin:LmotGSOY@192.168.3.113:3306/app_admin?schema=public"
\ No newline at end of file \ No newline at end of file
-- CreateTable
CREATE TABLE `device` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`sn` VARCHAR(20) NOT NULL,
`create_time` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `device_info` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`user` VARCHAR(20) NULL,
`status` TINYINT NULL,
`last_log_upload_time` VARCHAR(30) NULL,
`last_log_remove_time` VARCHAR(30) NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`mobile` VARCHAR(20) NULL,
`merchant_name` VARCHAR(50) NULL,
UNIQUE INDEX `device_id`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_config` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`device_id` INTEGER NOT NULL DEFAULT 0,
`log_saved_days` TINYINT NULL DEFAULT 7,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
UNIQUE INDEX `device_id`(`device_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_config_userfield_relation` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`config_id` INTEGER NOT NULL DEFAULT 0,
`user_field_id` INTEGER NOT NULL DEFAULT 0,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
INDEX `FK_log_config_userfield_relation_log_config`(`config_id`),
INDEX `FK_log_config_userfield_relation_log_user_field`(`user_field_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `log_user_field` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL,
`created_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
`updated_at` TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- AddForeignKey
ALTER TABLE `device_info` ADD CONSTRAINT `FK_device_info_device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config` ADD CONSTRAINT `FK_log_config_device` FOREIGN KEY (`device_id`) REFERENCES `device`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config` ADD CONSTRAINT `FK_log_config_device_info` FOREIGN KEY (`device_id`) REFERENCES `device_info`(`device_id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config_userfield_relation` ADD CONSTRAINT `FK_log_config_userfield_relation_log_config` FOREIGN KEY (`config_id`) REFERENCES `log_config`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
-- AddForeignKey
ALTER TABLE `log_config_userfield_relation` ADD CONSTRAINT `FK_log_config_userfield_relation_log_user_field` FOREIGN KEY (`user_field_id`) REFERENCES `log_user_field`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "mysql"
\ No newline at end of file \ No newline at end of file
...@@ -9,40 +9,55 @@ datasource db { ...@@ -9,40 +9,55 @@ datasource db {
model device { model device {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
create_time DateTime @db.DateTime(0) sn String @db.VarChar(20)
sn String @unique @db.VarChar(20) create_time DateTime @default(now()) @db.Timestamp(0)
// device_info device_info? device_info device_info?
// log_config log_config? log_config log_config?
} }
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model device_info { model device_info {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
device_sn String @unique @db.VarChar(20) device_id Int @unique(map: "device_id") @default(0)
user String? @db.VarChar(20) user String? @db.VarChar(20)
status Int? @db.TinyInt status Int? @db.TinyInt
last_log_upload_time DateTime? @db.DateTime(0) last_log_upload_time String? @db.VarChar(30)
last_log_remove_time DateTime? @db.Date last_log_remove_time String? @db.VarChar(30)
// device device? @relation(fields: [device_sn], references: [sn]) created_at DateTime @default(now()) @db.Timestamp(0)
// log_config log_config? updated_at DateTime @default(now()) @db.Timestamp(0)
mobile String? @db.VarChar(20)
merchant_name String? @db.VarChar(50)
device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_device_info_device")
log_config log_config?
} }
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments
model log_config { model log_config {
id Int @id @default(autoincrement()) id Int @id @default(autoincrement())
device_sn String @unique @db.VarChar(50) device_id Int @unique(map: "device_id") @default(0)
log_saved_days Int? @default(7) @db.TinyInt log_saved_days Int? @default(7) @db.TinyInt
log_user_field log_user_field[] created_at DateTime @default(now()) @db.Timestamp(0)
// device device @relation(fields: [device_sn], references: [sn]) updated_at DateTime @default(now()) @db.Timestamp(0)
// device_info device_info @relation(fields: [device_sn], references: [device_sn], onDelete: NoAction, onUpdate: NoAction, map: "FK_303042b366f2ba3d54f4ddaf6ab") device device @relation(fields: [device_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device")
device_info device_info @relation(fields: [device_id], references: [device_id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_device_info")
user_fields log_config_userfield_relation[]
} }
/// This model or at least one of its fields has comments in the database, and requires an additional setup for migrations: Read more: https://pris.ly/d/database-comments model log_config_userfield_relation {
model log_user_field { id Int @id @default(autoincrement())
id Int @id @default(autoincrement()) config_id Int @default(0)
name String @db.VarChar(20) user_field_id Int @default(0)
config_id Int? created_at DateTime @default(now()) @db.Timestamp(0)
log_config log_config? @relation(fields: [config_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_303042b366f2ba3d54f4ddaf6ac") updated_at DateTime @default(now()) @db.Timestamp(0)
log_config log_config @relation(fields: [config_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_userfield_relation_log_config")
log_user_field log_user_field @relation(fields: [user_field_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "FK_log_config_userfield_relation_log_user_field")
@@index([config_id], map: "FK_log_config_userfield_relation_log_config")
@@index([user_field_id], map: "FK_log_config_userfield_relation_log_user_field")
}
@@index([config_id], map: "FK_log_user_field_log_config") model log_user_field {
id Int @id @default(autoincrement())
name String @db.VarChar(20)
created_at DateTime @default(now()) @db.Timestamp(0)
updated_at DateTime @default(now()) @db.Timestamp(0)
config_ids log_config_userfield_relation[]
} }
...@@ -21,10 +21,10 @@ import { AlbumModule } from './modules/album/album.module' ...@@ -21,10 +21,10 @@ import { AlbumModule } from './modules/album/album.module'
@Module({ @Module({
imports: [ imports: [
ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')), ConfigModule.load(resolve(__dirname, 'config', '**/!(*.d).{ts,js}')),
TypeOrmModule.forRootAsync({ // TypeOrmModule.forRootAsync({
useFactory: (config: ConfigService) => config.get('database'), // useFactory: (config: ConfigService) => config.get('database'),
inject: [ConfigService] // inject: [ConfigService]
}), // }),
// TODO @nestjs/terminus almost the same // TODO @nestjs/terminus almost the same
StatusMonitorModule.setUp(statusMonitorConfig), StatusMonitorModule.setUp(statusMonitorConfig),
MailerModule.forRootAsync({ MailerModule.forRootAsync({
......
type ResponseBase = {
code?: number // 状态码
msg?: string // 响应信息
url?: string // 请求接口路径
timestamp: number // 时间戳
}
type pagenation = {
current?: number // 页码
size?: number // 当前页条数
total?: number // 总条数
}
/** /**
* @description: 全局响应体 * @description: 全局响应体
*/ */
export type Response<T = any> = { export type Response<T = any> = {
code: number // 状态码
data?: T // 业务数据 data?: T // 业务数据
msg: string // 响应信息 } & ResponseBase & pagenation
url: string // 请求接口路径
timestamp: number // 时间戳
}
/** /**
* @description: 分页数据 * @description: 分页数据
*/ */
...@@ -15,5 +22,5 @@ export type PageResponse<T = any> = { ...@@ -15,5 +22,5 @@ export type PageResponse<T = any> = {
current?: number // 页码 current?: number // 页码
size?: number // 当前页条数 size?: number // 当前页条数
total?: number // 总条数 total?: number // 总条数
records: T[] // 业务数据 data: T[] // 业务数据
} } & ResponseBase
import { Controller, Get, Post, Body, UseInterceptors } from '@nestjs/common' import { Controller, Get, Post, Body, UseInterceptors, Query } from '@nestjs/common'
import { DeviceService } from './device.service' import { DeviceService } from './device.service'
import { TransformInterceptor } from '../../common/interceptors' import { TransformInterceptor } from '../../common/interceptors'
import { ResponseDto } from 'src/dto/response.dto'
@Controller('device') @Controller('device')
export class DeviceController { export class DeviceController {
constructor(private readonly deviceService: DeviceService) {} constructor(private readonly deviceService: DeviceService) {}
@Get() @Get()
@UseInterceptors(TransformInterceptor) @UseInterceptors(TransformInterceptor)
findAll() { findAll(@Query() { user,mobile,sn,pageindex,pageSize }:Api.Device.QueryDevice):Promise<ResponseDto> {
return this.deviceService.findAll() return this.deviceService.findAll({user,mobile,sn,pageindex,pageSize})
} }
@Post() @Post()
async create(@Body() param) { async create(@Body() param) {
const newParam = { ...param, status: true } const newParam = { ...param, status: true }
await this.deviceService.create(newParam) // await this.deviceService.create(newParam)
return true return true
} }
@Post('/many') @Post('/many')
async createMany(@Body() users) { async createMany(@Body() users) {
const newUsers = users.map(user => ({ ...user, status: true })) const newUsers = users.map(user => ({ ...user, status: true }))
await this.deviceService.createMany(newUsers) // await this.deviceService.createMany(newUsers)
return true return true
} }
} }
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm'; // import { TypeOrmModule } from '@nestjs/typeorm';
import { DeviceController } from './device.controller'; import { DeviceController } from './device.controller';
import { DeviceService } from './device.service'; import { DeviceService } from './device.service';
import { Device as DeviceEntity } from '../entities/Device'; // import { Device as DeviceEntity } from '../entities/Device';
import { PrismaService } from 'nestjs-prisma'; import { PrismaService } from 'nestjs-prisma';
@Module({ @Module({
imports: [TypeOrmModule.forFeature([DeviceEntity])], // imports: [TypeOrmModule.forFeature([DeviceEntity])],
controllers: [DeviceController], controllers: [DeviceController],
providers: [DeviceService,PrismaService], providers: [DeviceService,PrismaService],
}) })
......
import { Inject,Injectable, HttpException, HttpStatus } from '@nestjs/common'; import { Inject, Injectable, HttpException, HttpStatus } from '@nestjs/common'
import { Repository, Connection, getRepository } from 'typeorm'; // import { Repository, Connection, getRepository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm'; // import { InjectRepository } from '@nestjs/typeorm';
import { Device as DeviceEntity } from '../entities/Device' // import { Device as DeviceEntity } from '../entities/Device'
import { PrismaService } from 'nestjs-prisma'; import { PrismaService } from 'nestjs-prisma'
import { Prisma } from '@prisma/client';
@Injectable() @Injectable()
export class DeviceService { export class DeviceService {
constructor( constructor(
@InjectRepository(DeviceEntity) // @InjectRepository(DeviceEntity)/
private readonly deviceRepository: Repository<DeviceEntity>, // private readonly deviceRepository: Repository<DeviceEntity>,
@Inject(PrismaService) @Inject(PrismaService)
private readonly prisma: PrismaService, private readonly prisma: PrismaService
private connection: Connection, ) // private connection: Connection,
) {} {}
async findAll(): Promise<any> { async findAll({user,mobile,sn,pageSize,pageindex}:Api.Device.QueryDevice): Promise<Api.Device.DeviceInfo[]> {
// relations: ['photos'], 联合查询 const result = await this.prisma.device.findMany({
return await this.prisma.device.findMany(); // skip,
// take,
select: {
sn: true,
'device_info': {
select: {
user: true,
status: true,
'log_config': {
select: {
'log_saved_days': true,
'user_fields': {
select: {
'log_user_field': {
select:{
name:true,
}
}
}
}
}
}
},
where:{
mobile,
user
}
},
},
where:{
sn
}
})
const data = result.reduce((pre, cur) => {
pre.push({
sn:cur.sn,
user:cur.device_info?.user,
status:cur.device_info?.status,
'log_saved_days':cur.device_info?.log_config?.log_saved_days,
'log_user_fields':cur.device_info?.log_config?.user_fields?.map(item => item.log_user_field.name)
})
return pre
},[])
return data
// 或者使用queryBuilder // 或者使用queryBuilder
// return await getRepository(UsersEntity) // return await getRepository(UsersEntity)
// .createQueryBuilder("user") // .createQueryBuilder("user")
...@@ -25,41 +66,41 @@ export class DeviceService { ...@@ -25,41 +66,41 @@ export class DeviceService {
// .getMany() // .getMany()
} }
async create(user): Promise<DeviceEntity[]> { // async create(user): Promise<DeviceEntity[]> {
const { name } = user; // const { name } = user;
const u = await getRepository(DeviceEntity).findOne({ where: { name } }); // const u = await getRepository(DeviceEntity).findOne({ where: { name } });
// .createQueryBuilder('users') // // .createQueryBuilder('users')
// .where('users.name = :name', { name }); // // .where('users.name = :name', { name });
// const u = await qb.getOne(); // // const u = await qb.getOne();
if (u) { // if (u) {
throw new HttpException( // throw new HttpException(
{ // {
message: 'Input data validation failed', // message: 'Input data validation failed',
error: 'name must be unique.', // error: 'name must be unique.',
}, // },
HttpStatus.BAD_REQUEST, // HttpStatus.BAD_REQUEST,
); // );
} // }
return await this.deviceRepository.save(user); // return await this.deviceRepository.save(user);
} // }
async createMany(users: DeviceEntity[]) { // async createMany(users: DeviceEntity[]) {
const queryRunner = this.connection.createQueryRunner(); // const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect(); // await queryRunner.connect();
await queryRunner.startTransaction(); // await queryRunner.startTransaction();
try { // try {
users.forEach(async user => { // users.forEach(async user => {
await queryRunner.manager.getRepository(DeviceEntity).save(user); // await queryRunner.manager.getRepository(DeviceEntity).save(user);
}); // });
await queryRunner.commitTransaction(); // await queryRunner.commitTransaction();
} catch (err) { // } catch (err) {
// since we have errors lets rollback the changes we made // // since we have errors lets rollback the changes we made
await queryRunner.rollbackTransaction(); // await queryRunner.rollbackTransaction();
} finally { // } finally {
// you need to release a queryRunner which was manually instantiated // // you need to release a queryRunner which was manually instantiated
await queryRunner.release(); // await queryRunner.release();
} // }
} // }
} }
...@@ -19,4 +19,24 @@ declare namespace Api { ...@@ -19,4 +19,24 @@ declare namespace Api {
records: T[] // 业务数据 records: T[] // 业务数据
} }
} }
namespace Device {
type QueryDevice = {
user?: string // 用户
mobile?: string // 手机号
sn?: string // 设备号
pageindex?: number // 页码
pageSize?: number // 每页条数
}
type DeviceInfo = {
id?: string // 设备id
user?: string // 用户
mobile?: string // 手机号
sn?: string // 设备号
status?: number // 状态
log_saved_days?: number // 日志保存天数
log_user_fields?: string[] // 日志用户字段
}
}
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!