2021-07-08 19:40:14 +02:00
|
|
|
import { Injectable } from '@nestjs/common';
|
2021-07-08 23:58:07 +02:00
|
|
|
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
|
|
|
|
import { EntityManager, Repository, TreeRepository } from 'typeorm';
|
2021-07-08 19:40:14 +02:00
|
|
|
import { NewItemInput } from './dto/new-item.input';
|
|
|
|
import { Item } from './items.entity';
|
2021-07-08 23:58:07 +02:00
|
|
|
import { ItemModel } from './items.model';
|
2021-07-08 19:40:14 +02:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class ItemsService {
|
|
|
|
constructor(
|
|
|
|
@InjectRepository(Item)
|
|
|
|
private itemRepository: Repository<Item>,
|
2021-07-08 23:58:07 +02:00
|
|
|
@InjectEntityManager()
|
|
|
|
private entityManager: EntityManager,
|
|
|
|
) {
|
|
|
|
this.treeRepository = this.entityManager.getTreeRepository(Item);
|
|
|
|
}
|
|
|
|
treeRepository: TreeRepository<Item>;
|
2021-07-08 19:40:14 +02:00
|
|
|
|
|
|
|
async getItem(id: string): Promise<Item | undefined> {
|
|
|
|
return this.itemRepository.findOne(id);
|
|
|
|
}
|
|
|
|
|
2021-07-17 18:34:30 +02:00
|
|
|
async getItemParent(item: ItemModel): Promise<Item | undefined> {
|
2021-07-17 17:07:19 +02:00
|
|
|
const childItem = await this.itemRepository.findOneOrFail(item.id, {
|
|
|
|
relations: ['parent'],
|
|
|
|
});
|
|
|
|
return childItem.parent;
|
2021-07-08 23:58:07 +02:00
|
|
|
}
|
|
|
|
|
2021-07-17 18:34:30 +02:00
|
|
|
async getItemChildren(item: ItemModel): Promise<Item[]> {
|
|
|
|
return this.itemRepository.find({
|
|
|
|
where: {
|
|
|
|
parent: item.id,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-07-17 22:51:12 +02:00
|
|
|
async getItemDescendents(item: ItemModel): Promise<Item[]> {
|
|
|
|
const parentItem = await this.itemRepository.findOneOrFail(item.id, {
|
|
|
|
relations: ['parent'],
|
|
|
|
});
|
|
|
|
return this.treeRepository.findDescendants(parentItem);
|
|
|
|
}
|
|
|
|
|
2021-07-08 19:40:14 +02:00
|
|
|
async createItem(input: NewItemInput): Promise<Item> {
|
2021-07-17 16:44:34 +02:00
|
|
|
const item = this.itemRepository.create({
|
|
|
|
...input,
|
|
|
|
id: input.id || undefined,
|
|
|
|
parent: input.parent
|
|
|
|
? await this.itemRepository.findOneOrFail(input.parent)
|
|
|
|
: undefined,
|
|
|
|
});
|
|
|
|
|
|
|
|
const highestIdQuery = this.itemRepository
|
|
|
|
.createQueryBuilder()
|
|
|
|
.select('id')
|
|
|
|
.orderBy('id', 'DESC')
|
|
|
|
.limit(1);
|
|
|
|
|
|
|
|
const insert = await this.itemRepository
|
|
|
|
.createQueryBuilder()
|
|
|
|
.insert()
|
|
|
|
.into(Item)
|
|
|
|
.values({
|
|
|
|
...item,
|
|
|
|
// if id is specified, use it.
|
|
|
|
// if not, get the highest id in table and use highest_id+1
|
|
|
|
id: input.id || (() => `((${highestIdQuery.getSql()}) + 1)`),
|
|
|
|
})
|
|
|
|
.returning(['id'])
|
|
|
|
.execute();
|
|
|
|
|
|
|
|
item.id = insert.identifiers[0].id || item.id;
|
|
|
|
return item;
|
2021-07-08 19:40:14 +02:00
|
|
|
}
|
|
|
|
}
|