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 { DatabaseConfig } from './config';
|
2024-01-17 11:29:59 +00:00
|
|
|
import { User } from './entity/User';
|
|
|
|
import { Organization } from './entity/Organization';
|
|
|
|
import { UserOrganization } from './entity/UserOrganization';
|
|
|
|
import { Project } from './entity/Project';
|
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;
|
|
|
|
}
|
2024-01-17 11:29:59 +00:00
|
|
|
|
|
|
|
async getOrganizationsbyUserId (userId: number) : Promise<Organization[]> {
|
|
|
|
const userOrganizationRepository = this.dataSource.getRepository(UserOrganization);
|
|
|
|
|
|
|
|
const userOrgs = await userOrganizationRepository.find({
|
|
|
|
relations: {
|
|
|
|
user: true,
|
|
|
|
organization: true
|
|
|
|
},
|
|
|
|
where: {
|
|
|
|
user: {
|
|
|
|
id: userId
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
const organizations = userOrgs.map(userOrg => userOrg.organization);
|
|
|
|
return organizations;
|
|
|
|
}
|
|
|
|
|
|
|
|
async getProjectsbyOrganizationId (organizationId: number): Promise<Project[]> {
|
|
|
|
const projectRepository = this.dataSource.getRepository(Project);
|
|
|
|
|
|
|
|
const projects = await projectRepository.find({
|
|
|
|
relations: {
|
|
|
|
organization: true,
|
|
|
|
owner: true
|
|
|
|
},
|
|
|
|
where: {
|
|
|
|
organization: {
|
|
|
|
id: organizationId
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
return projects;
|
|
|
|
}
|
2024-01-17 05:23:01 +00:00
|
|
|
}
|