chore: remove sqlite

This commit is contained in:
vben
2024-06-30 22:28:35 +08:00
parent 9572d1a1c5
commit 692225cfff
18 changed files with 139 additions and 663 deletions

View File

@@ -1,12 +0,0 @@
import { UserEntity } from '@/models/entity/user.entity';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersModule } from '../users/users.module';
import { DatabaseService } from './database.service';
@Module({
imports: [UsersModule, TypeOrmModule.forFeature([UserEntity])],
providers: [DatabaseService],
})
export class DatabaseModule {}

View File

@@ -1,19 +0,0 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DatabaseService } from './database.service';
describe('databaseService', () => {
let service: DatabaseService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [DatabaseService],
}).compile();
service = module.get<DatabaseService>(DatabaseService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@@ -1,40 +0,0 @@
import type { Repository } from 'typeorm';
import { UserEntity } from '@/models/entity/user.entity';
import { Injectable, type OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UsersService } from '../users/users.service';
@Injectable()
export class DatabaseService implements OnModuleInit {
constructor(
@InjectRepository(UserEntity)
private usersRepository: Repository<UserEntity>,
private userService: UsersService,
) {}
async onModuleInit() {
// data/db.sqlite会被git忽略方式数据库文件被提交到git
// 清空表,并初始化两条数据
await this.usersRepository.clear();
await this.userService.create({
id: 0,
password: '123456',
realName: 'Administrator',
roles: ['admin'],
username: 'vben',
});
await this.userService.create({
id: 1,
password: '123456',
realName: 'Jack',
roles: ['user'],
username: 'jack',
});
const count = await this.usersRepository.count();
console.log('Database has been initialized with seed data, count:', count);
}
}

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1,13 @@
interface User {
id: number;
password: string;
realName: string;
roles: string[];
username: string;
}
interface MockDatabaseData {
users: User[];
}
export type { MockDatabaseData, User };

View File

@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { MockService } from './mock.service';
@Module({
exports: [MockService],
providers: [MockService],
})
export class MockModule {}

View File

@@ -0,0 +1,71 @@
import type { MockDatabaseData } from './mock.interface';
import fs from 'node:fs';
import path from 'node:path';
import { Injectable, type OnModuleInit } from '@nestjs/common';
import bcrypt from 'bcryptjs';
@Injectable()
export class MockService implements OnModuleInit {
private data: MockDatabaseData;
private readonly filePath: string;
constructor() {
this.filePath = path.join(__dirname, '.', 'mock-db.json');
this.loadData();
}
private loadData() {
const fileData = fs.readFileSync(this.filePath, 'utf8');
this.data = JSON.parse(fileData);
}
private saveData() {
fs.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2));
}
addItem(collection: string, item: any) {
this.data[collection].push(item);
this.saveData();
return item;
}
clearCollection(collection: string) {
this.data[collection] = [];
this.saveData();
return this.data[collection];
}
findAll(collection: string) {
return this.data[collection];
}
findOneById(collection: string, id: number) {
return this.data[collection].find((item) => item.id === id);
}
async onModuleInit() {
// 清空表,并初始化两条数据
await this.clearCollection('users');
// 密码哈希
const hashPassword = await bcrypt.hash('123456', 10);
await this.addItem('users', {
id: 0,
password: hashPassword,
realName: 'Vben',
roles: ['admin'],
username: 'vben',
});
await this.addItem('users', {
id: 1,
password: hashPassword,
realName: 'Jack',
roles: ['user'],
username: 'jack',
});
const count = await this.findAll('users').length;
console.log('Database has been initialized with seed data, count:', count);
}
}

View File

@@ -1,12 +1,11 @@
import { UserEntity } from '@/models/entity/user.entity';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { MockModule } from '../mock/mock.module';
import { UsersService } from './users.service';
@Module({
exports: [UsersService],
imports: [TypeOrmModule.forFeature([UserEntity])],
imports: [MockModule],
providers: [UsersService],
})
export class UsersModule {}

View File

@@ -1,28 +1,18 @@
import type { CreateUserDto } from '@/models/dto/user.dto';
import type { Repository } from 'typeorm';
import { UserEntity } from '@/models/entity/user.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import bcrypt from 'bcryptjs';
import { MockService } from '../mock/mock.service';
@Injectable()
export class UsersService {
constructor(
@InjectRepository(UserEntity)
private usersRepository: Repository<UserEntity>,
) {}
async create(user: CreateUserDto): Promise<UserEntity> {
user.password = await bcrypt.hash(user.password, 10); // 密码哈希
return this.usersRepository.save(user);
}
constructor(private mockService: MockService) {}
/**
* Find user by username
* @param username
*/
async findOne(username: string): Promise<UserEntity | undefined> {
return await this.usersRepository.findOne({ where: { username } });
const allUsers = await this.mockService.findAll('users');
return allUsers.find((user) => user.username === username);
}
}