"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, 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 (e instanceof _typeorm.EntityNotFoundError) {
                    throw new _runtimeexceptions.NotFoundException(`The entity ${entity} with the provided id was not found`);
                }
                throw e;
            }
        }
        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 ("id" in dto && dto.id !== undefined && dto.id !== null) {
                throw new Error("Cannot create entity with an existing ID. Use update method instead.");
            }
            const entity = this.repository.create(dto);
            await (0, _classvalidator.validate)(entity);
            return await this.repository.save(entity);
        }
        async delete(id) {
            const entity = await this.get(id);
            await this.repository.delete(entity.id);
        }
        async deleteMany(ids) {
            await this.repository.delete(ids);
        }
    }
    return BaseServiceHost;
}

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