Skip to content

Commit

Permalink
Merge pull request #72 from pinax-network/feature/cache-health
Browse files Browse the repository at this point in the history
add 1s cache to `/health`
  • Loading branch information
DenisCarriere authored Nov 8, 2023
2 parents ca6b063 + 1ca42fe commit 58f0ec4
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/fetch/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,32 @@ import client from "../clickhouse/createClient.js";
import { logger } from "../logger.js";
import { BadRequest, toText } from "./cors.js";

function now() {
return Math.floor(Date.now() / 1000); // seconds
}

// cache the timestamp and value for 1 seconds
let timestamp = now();
let value = true; // true = OK, false = ERROR

export default async function () {
// return cached response if timestamp is less than 1 second old
if ( now() - timestamp < 1 ) {
return value ? toText("OK") : BadRequest;
}

try {
const response = await client.ping();
if (!response.success) {
throw new Error(response.error.message);
}

timestamp = now();
value = true;
return toText("OK");
} catch (e) {
logger.error(e);
timestamp = now();
value = false;
return BadRequest;
}
}

0 comments on commit 58f0ec4

Please sign in to comment.