UNPKG

@citrineos/data

Version:

The OCPP data module which includes all persistence layer implementation.

78 lines 3.4 kB
import { CrudRepository, OCPP2_0_1 } from '@citrineos/base'; import { Boot } from '../model/Boot.js'; import { VariableAttribute } from '../model/index.js'; import { SequelizeRepository } from '../index.js'; import { Logger } from 'tslog'; import { Sequelize } from 'sequelize-typescript'; export class SequelizeBootRepository extends SequelizeRepository { variableAttributes; constructor(config, logger, sequelizeInstance, variableAttributes) { super(config, Boot.MODEL_NAME, logger, sequelizeInstance); this.variableAttributes = variableAttributes ? variableAttributes : new SequelizeRepository(config, VariableAttribute.MODEL_NAME, logger, sequelizeInstance); } async createOrUpdateByKey(tenantId, value, key) { let savedBootConfig; let created; await this.s.transaction(async (sequelizeTransaction) => { const [boot, bootCreated] = await this.readOrCreateByQuery(tenantId, { where: { tenantId, id: key, }, defaults: { ...value, }, transaction: sequelizeTransaction, }); if (!bootCreated) { savedBootConfig = await boot.update({ ...value }, { transaction: sequelizeTransaction }); } else { savedBootConfig = boot; } created = bootCreated; }); if (savedBootConfig) { if (value.pendingBootSetVariableIds) { savedBootConfig.pendingBootSetVariables = await this.manageSetVariables(tenantId, value.pendingBootSetVariableIds, key, savedBootConfig.id); } this.emit(created ? 'created' : 'updated', [savedBootConfig]); } return savedBootConfig; } async updateStatusByKey(tenantId, status, statusInfo, key) { return await this.updateByKey(tenantId, { status, statusInfo }, key); } async updateLastBootTimeByKey(tenantId, lastBootTime, key) { return await this.updateByKey(tenantId, { lastBootTime }, key); } /** * Private Methods */ async manageSetVariables(tenantId, setVariableIds, stationId, bootConfigId) { const managedSetVariables = []; // Unassigns variables await this.variableAttributes.updateAllByQuery(tenantId, { bootConfigId: null }, { where: { stationId, }, }); // Assigns variables, or throws an error if variable with id does not exist for (const setVariableId of setVariableIds) { const setVariable = await this.variableAttributes.updateByKey(tenantId, { bootConfigId }, setVariableId.toString()); if (!setVariable) { // When this is called from createOrUpdateByKey, this code should be impossible to reach // Since the boot object would have already been upserted with the pendingBootSetVariableIds as foreign keys // And if they were not valid foreign keys, it would have thrown an error throw new Error('SetVariableId does not exist ' + setVariableId); } else { managedSetVariables.push(setVariable); } } return managedSetVariables; } } //# sourceMappingURL=Boot.js.map