2024-01-16 08:10:14 +00:00
|
|
|
import { DataSource } from 'typeorm';
|
|
|
|
import path from 'path';
|
|
|
|
import debug from 'debug';
|
|
|
|
|
2024-01-17 05:23:01 +00:00
|
|
|
import { User } from './entity/User';
|
|
|
|
import { DatabaseConfig } from './config';
|
2024-01-16 08:10:14 +00:00
|
|
|
|
2024-01-17 05:23:01 +00:00
|
|
|
const log = debug('snowball:database');
|
|
|
|
|
|
|
|
export class Database {
|
|
|
|
private dataSource: DataSource;
|
|
|
|
|
|
|
|
constructor ({ dbPath }: DatabaseConfig) {
|
|
|
|
this.dataSource = new DataSource({
|
2024-01-16 08:10:14 +00:00
|
|
|
type: 'better-sqlite3',
|
2024-01-17 05:23:01 +00:00
|
|
|
database: dbPath,
|
2024-01-16 08:10:14 +00:00
|
|
|
entities: [path.join(__dirname, '/entity/*')],
|
|
|
|
synchronize: true,
|
|
|
|
logging: false
|
|
|
|
});
|
2024-01-17 05:23:01 +00:00
|
|
|
}
|
2024-01-16 08:10:14 +00:00
|
|
|
|
2024-01-17 05:23:01 +00:00
|
|
|
async init () : Promise<void> {
|
|
|
|
await this.dataSource.initialize();
|
2024-01-16 08:10:14 +00:00
|
|
|
log('database initialized');
|
|
|
|
}
|
2024-01-17 05:23:01 +00:00
|
|
|
|
|
|
|
async getUser (userId: number) : Promise<User | null> {
|
|
|
|
const userRepository = this.dataSource.getRepository(User);
|
|
|
|
const user = await userRepository.findOneBy({
|
|
|
|
id: userId
|
|
|
|
});
|
|
|
|
|
|
|
|
return user;
|
|
|
|
}
|
|
|
|
}
|