Skip to content

Commit

Permalink
Merge pull request #123 from coronasafe/axios-error-handle
Browse files Browse the repository at this point in the history
handle axios errors when status >= 400
  • Loading branch information
khavinshankar authored Apr 19, 2024
2 parents bf230dc + 975f9a1 commit 614361b
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 27 deletions.
12 changes: 9 additions & 3 deletions src/controller/AssetConfigController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ import dayjs from "dayjs";
import { Request, Response } from "express";

import prisma from "@/lib/prisma";
import { retrieveAssetConfig } from "@/cron/retrieveAssetConfig";

export class AssetConfigController {
static listAssets = async (req: Request, res: Response) => {
try {
const assets = await prisma.asset.findMany({
where: {
deleted: false,
},
orderBy: [{ updatedAt: "desc" }],
});

Expand All @@ -31,13 +29,19 @@ export class AssetConfigController {
res.render("pages/assets/list", {
req,
dayjs,
csrfToken: res.locals.csrfToken,
assets: [],
beds: [],
errors: [err.message],
});
}
};

static refreshAssets = async (req: Request, res: Response) => {
await retrieveAssetConfig();
res.redirect("/assets");
}

static createAssetForm = async (req: Request, res: Response) => {
res.render("pages/assets/form", {
req,
Expand Down Expand Up @@ -143,6 +147,7 @@ export class AssetConfigController {
username,
password,
port,
deleted,
} = req.body;

const asset = await prisma.asset.findFirst({
Expand Down Expand Up @@ -175,6 +180,7 @@ export class AssetConfigController {
updatedAt: new Date(),
username,
password,
deleted: deleted === "true",
port: Number(port),
},
});
Expand Down
42 changes: 23 additions & 19 deletions src/cron/automatedDailyRounds.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import axios, { AxiosResponse } from "axios";
import axios, { AxiosError, AxiosResponse } from "axios";
import fs from "fs";
import path from "path";

Expand All @@ -24,14 +24,16 @@ import { parseVitalsFromImage } from "@/utils/ocr";
const UPDATE_INTERVAL = 60 * 60 * 1000;

export async function getMonitorPreset(bedId: string, assetId: string) {
const response = await axios.get<
unknown,
AxiosResponse<CarePaginatedResponse<AssetBed>>
>(`${careApi}/api/v1/assetbed/?bed=${bedId}&preset_name=monitor`, {
headers: await generateHeaders(assetId),
});
const response = await axios
.get<unknown, AxiosResponse<CarePaginatedResponse<AssetBed>>>(
`${careApi}/api/v1/assetbed/?bed=${bedId}&preset_name=monitor`,
{
headers: await generateHeaders(assetId),
},
)
.catch((error: AxiosError) => error.response);

if (response.status !== 200) {
if (response?.status !== 200) {
console.error(
`Failed to get assetbed from care for the bed ${bedId} and asset ${assetId}`,
);
Expand Down Expand Up @@ -112,28 +114,30 @@ export async function fileAutomatedDailyRound(
assetId: string,
vitals: DailyRoundObservation,
) {
const response = await axios.post(
`${careApi}/api/v1/consultation/${consultationId}/daily_rounds/`,
vitals,
{ headers: await generateHeaders(assetId) },
);
const response = await axios
.post(
`${careApi}/api/v1/consultation/${consultationId}/daily_rounds/`,
vitals,
{ headers: await generateHeaders(assetId) },
)
.catch((error: AxiosError) => error.response);

if (saveDailyRound) {
prisma.dailyRound.create({
data: {
assetExternalId: assetId,
status: response.statusText,
status: response?.statusText ?? "FAILED",
data: JSON.stringify(vitals),
response: JSON.stringify(response.data),
response: JSON.stringify(response?.data),
},
});
}

if (response.status !== 201) {
if (response?.status !== 201) {
console.error(
`Failed to file the daily round for the consultation ${consultationId} and asset ${assetId}`,
response.statusText,
JSON.stringify(response.data),
response?.statusText,
JSON.stringify(response?.data),
);
return;
}
Expand Down Expand Up @@ -219,7 +223,7 @@ export async function getVitalsFromObservations(assetHostname: string) {
temperature: number;
temperature_mesured_at: string;
} | null) ?? { temperature: null, temperature_measured_at: null }),
bp: getValueFromData("blood-pressure", data),
bp: getValueFromData("blood-pressure", data) ?? { },
rounds_type: "AUTOMATED",
is_parsed_by_ocr: false,
} as DailyRoundObservation;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ async function insertAsset(asset: AssetConfig) {
externalId: asset.id,
},
update: {
name: asset.name,
description: asset.description,
ipAddress: asset.ip_address,
port: asset.port,
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as cron from "node-cron";

import { automatedDailyRounds } from "@/cron/automatedDailyRounds";
import { retrieveAssetConfig } from "@/cron/retrieveAssetConfig";
import { initServer } from "@/server";
import { port } from "@/utils/configs";
import { retrieveAssetConfig } from "@/utils/retrieveAssetConfig";

process.env.AWS_SDK_JS_SUPPRESS_MAINTENANCE_MODE_MESSAGE = "1";
process.env.CHECKPOINT_DISABLE = "1";
Expand Down
1 change: 1 addition & 0 deletions src/router/assetConfigRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ router.use(csrfProtection());
router.get("/", AssetConfigController.listAssets);
router.get("/new", AssetConfigController.createAssetForm);
router.post("/", AssetConfigController.createAsset);
router.post("/refresh", AssetConfigController.refreshAssets);
router.get("/:externalId", AssetConfigController.updateAssetForm);
router.post("/:externalId", AssetConfigController.updateAsset);
router.get("/:externalId/delete", AssetConfigController.confirmDeleteAsset);
Expand Down
2 changes: 1 addition & 1 deletion src/types/observation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export interface DailyRoundObservation {
bp?: {
systolic?: number | null;
diastolic?: number | null;
} | null;
};
taken_at?: string | Date | null;
rounds_type?: "AUTOMATED";
is_parsed_by_ocr?: boolean;
Expand Down
11 changes: 10 additions & 1 deletion src/views/pages/assets/form.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,17 @@
<label for="port">Port</label>
<input class="px-2 py-1 border-2 border-black" type="number" placeholder="80" name="port" id="port" value="<%- asset.port %>" />
</div>
<% if(asset?.externalId) {%>
<div class="flex flex-col mt-2">
<label for="deleted">Deleted</label>
<select class="p-2 border-2 border-black" name="deleted" id="deleted">
<option value="false" <%= asset.deleted === false ? 'selected' : '' %>>No</option>
<option value="true" <%= asset.deleted === true ? 'selected' : '' %>>Yes</option>
</select>
</div>
<% } %>
<div class="flex flex-col mt-2">
<input class="px-4 py-2 hover:bg-green-700 bg-green-500" type="submit" value="Save" />
<input class="px-4 py-2 hover:bg-green-700 bg-green-500" type="submit" value="Save" />
</div>
</form>
</main>
Expand Down
10 changes: 8 additions & 2 deletions src/views/pages/assets/list.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<head>
<%- include('../../partials/head.ejs', { title: 'Teleicu Middleware | Asset Config'}) %>
</head>
<body class="max-w-screen-lg mx-auto">
<body class="max-w-screen-xl mx-auto">
<%- include("../../partials/header") %>
<main class="py-8 w-full">
<%- include("../../partials/pageTitle",{title:"Asset Config"}) %>
Expand All @@ -15,7 +15,11 @@
<% }) %>
</div>
<% } %>
<div class="float-right">
<div class="float-right flex gap-2">
<form action="/assets/refresh" method="post">
<input type="hidden" name="csrfToken" value="<%= csrfToken %>" />
<button class="px-4 py-2 hover:bg-blue-700 bg-blue-500" type="submit">Refresh</button>
</form>
<a class="px-4 py-2 ml-auto hover:bg-green-700 bg-green-500" href="/assets/new">Add New Asset</a>
</div>

Expand All @@ -27,6 +31,7 @@
<!-- <th>Description</th> -->
<th>IP address</th>
<th>Updated At</th>
<th>Deleted</th>
<th>Actions</th>
</tr>
<% for (var i = 0; i < assets.length; i++) { %>
Expand All @@ -38,6 +43,7 @@
<!-- <td ><%= assets[i].description %></td> -->
<td class="w-fit"><%= assets[i].ipAddress %></td>
<td class="w-fit"><%= dayjs(assets[i].updatedAt).format('DD/MM/YYYY hh:mm:ss a') %></td>
<td class="w-fit"><%= assets[i].deleted ? 'Yes' : 'No' %></td>
<td class="w-fit text-right">
<a class="px-4 py-2 my-2 hover:bg-yellow-700 bg-yellow-500" href="/assets/<%= assets[i].externalId %>">Edit</a>
<a class="px-4 py-2 my-2 hover:bg-red-700 bg-red-500" href="/assets/<%= assets[i].externalId %>/delete">Delete</a>
Expand Down

0 comments on commit 614361b

Please sign in to comment.