"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "BaseService", {
    enumerable: true,
    get: function() {
        return BaseService;
    }
});
const _typeorm = require("typeorm");
const _classvalidator = require("class-validator");
const _runtimeexceptions = require("../../exceptions/runtime.exceptions");
const _pageinterface = require("../interfaces/page.interface");
function BaseService(entity, dto, createDTO, updateDto) {
    class BaseServiceHost {
        typeormService;
        repository;
        constructor({ typeormService }){
            this.typeormService = typeormService;
            this.repository = typeormService.getDataSource().getRepository(entity);
        }
        async get(id, throwIfNotFound = true, options) {
            try {
                if (id === null || id === undefined) {
                    throw new _typeorm.EntityNotFoundError(entity, "Id was not provided");
                }
                return this.repository.findOneOrFail({
                    ...options,
                    where: {
                        id
                    }
                });
            } catch (e) {
                if (throwIfNotFound && e instanceof _typeorm.EntityNotFoundError) {
                    throw new _runtimeexceptions.NotFoundException(`The entity ${entity} with the provided id was not found`);
                }
                return undefined;
            }
        }
        async list(options) {
            return this.repository.find(options);
        }
        async listPaged(page = _pageinterface.DEFAULT_PAGE, options) {
            return this.repository.find({
                take: page.pageSize,
                skip: page.pageSize * page.page,
                ...options
            });
        }
        async update(id, updateDto) {
            const entity = await this.get(id);
            await (0, _classvalidator.validate)(updateDto);
            await (0, _classvalidator.validate)(Object.assign(entity, updateDto));
            await this.repository.update(entity.id, updateDto);
            return await this.get(id);
        }
        async create(dto) {
            if (dto.id) {
                delete dto.id;
            }
            await (0, _classvalidator.validate)(dto);
            const entity = this.repository.create(dto);
            await (0, _classvalidator.validate)(entity);
            return await this.repository.save(entity);
        }
        async delete(id, throwIfNotFound = true) {
            const entity = await this.get(id, throwIfNotFound);
            return await this.repository.delete(entity.id);
        }
        async deleteMany(ids, emitEvent = true) {
            return await this.repository.delete(ids);
        }
    }
    return BaseServiceHost;
}

//# sourceMappingURL=base.service.js.map