src/services/asset.types.service.tsmodifiedimport { LoggerFactory } from "../util/logger";
import { query } from "../db/db";
import { NotFoundError } from "../types/errortypes";
import { getLoggedInUsername } from "../util/username";
const logger = LoggerFactory("AssetTypesService");
const SQL = {
LIST: `SELECT * FROM xyz."fn_GetAssetTypeList"($1)`,
GET_BY_ID: `SELECT * FROM xyz."fn_GetAssetType"($1, $2)`,
INSERT: `SELECT * FROM xyz."fn_InsertAssetType"($1, $2, $3, $4)`,
};
export interface AssetType {
assetTypeId: string;
name: string;
description: string | null;
createdBy: string;
insertedOn: Date;
lastModifiedOn: Date | null;
lastModifiedBy: string | null;
}
function mapRow(row: any): AssetType {
return {
assetTypeId: row.AssetTypeId,
name: row.Name,
description: row.Description ?? null,
createdBy: row.CreatedBy,
insertedOn: row.InsertedOn,
lastModifiedOn: row.LastModifiedOn ?? null,
lastModifiedBy: row.LastModifiedBy ?? null,
};
}
export async function listAssetTypes(projectId: string): Promise<AssetType[]> {
try {
const { rows } = await query(SQL.LIST, [projectId]);
return rows.map(mapRow);
} catch (err) {
logger.error("Error while listing asset types", err);
throw err;
}
}
export async function getAssetTypeById(projectId: string, assetTypeId: string): Promise<AssetType> {
try {
const { rows } = await query(SQL.GET_BY_ID, [projectId, assetTypeId]);
if (rows.length === 0) {
throw new NotFoundError(`AssetType with id: ${assetTypeId} not found.`);
}
return mapRow(rows[0]);
} catch (err) {
logger.error("Error while fetching asset type", err);
throw err;
}
}
export async function createAssetType(projectId: string, name: string, description: string | null): Promise<AssetType> {
try {
const { rows } = await query(SQL.INSERT, [projectId, name, description, getLoggedInUsername()]);
return mapRow(rows[0]);
} catch (err) {
logger.error("Error while creating asset type", err);
throw err;
}
}