src/services/systems.service.tsaddedimport { LoggerFactory } from "../util/logger";
import { query } from "../db/db";
import { NotFoundError } from "../types/errortypes";
import { getLoggedInUsername } from "../util/username";
import { PagingQueryParam } from "../models/ingress";
import { IndexedItem } from "../util/pagination.util";
const logger = LoggerFactory("SystemsService");
const SQL = {
LIST: `SELECT * FROM xyz."fn_GetCommissioningSystemList"($1, $2, $3)`,
GET_BY_ID: `SELECT * FROM xyz."fn_GetCommissioningSystem"($1, $2)`,
INSERT: `SELECT * FROM xyz."fn_InsertCommissioningSystem"($1, $2, $3, $4)`,
};
export interface System {
systemId: string;
name: string;
systemTypeId: string;
createdBy: string;
insertedOn: Date;
lastModifiedOn: Date | null;
lastModifiedBy: string | null;
}
function mapRow(row: any): System {
return {
systemId: row.CommissioningSystemId,
name: row.Name,
systemTypeId: row.SystemTypeId,
createdBy: row.CreatedBy,
insertedOn: row.InsertedOn,
lastModifiedOn: row.LastModifiedOn ?? null,
lastModifiedBy: row.LastModifiedBy ?? null,
};
}
function mapError(err: unknown): never {
if (err instanceof Error && err.message.includes('SystemType with id')) {
throw new NotFoundError(err.message);
}
throw err;
}
export async function listSystems(projectId: string, paging: PagingQueryParam): Promise<(System & IndexedItem)[]> {
try {
const { rows } = await query(SQL.LIST, [projectId, paging.lastFetchedIndexId, paging.size]);
return rows.map((row: any) => ({ ...mapRow(row), indexId: row.Id }));
} catch (err) {
logger.error("Error while listing systems", err);
throw err;
}
}
export async function getSystemById(projectId: string, systemId: string): Promise<System> {
try {
const { rows } = await query(SQL.GET_BY_ID, [projectId, systemId]);
if (rows.length === 0) {
throw new NotFoundError(`System with id: ${systemId} not found.`);
}
return mapRow(rows[0]);
} catch (err) {
logger.error("Error while fetching system", err);
throw err;
}
}
export async function createSystem(projectId: string, systemTypeId: string, name: string): Promise<System> {
try {
const { rows } = await query(SQL.INSERT, [projectId, systemTypeId, name, getLoggedInUsername()]);
return mapRow(rows[0]);
} catch (err) {
logger.error("Error while creating system", err);
mapError(err);
}
}