diff --git a/src/controllers/base.ts b/src/controllers/base.ts new file mode 100644 index 0000000..109cc01 --- /dev/null +++ b/src/controllers/base.ts @@ -0,0 +1,52 @@ +import { type Request, type Response } from "express"; +import { type CID } from 'kubo-rpc-client' + +import { saveContentData } from "../models/Content"; +import { ipfsCore } from "../modules/IPFSCore"; +import { generateGatewayURL, getContentMetadata } from "../utils"; + +async function healthCheck(_request: Request, response: Response): Promise { + const ts = Date.now() + const cid = await uploadSampleContent() + let contentGatewayStatus = false + + if(cid !== false) { + contentGatewayStatus = await isContentRetrievableFromGateway(cid) + } + + return response.status(200).send({ + ts, + node: !!cid, + contentGateway: contentGatewayStatus + }) +} + +async function uploadSampleContent(): Promise { + try { + const content = 'data:text/plain;base64,SGVsbG8gV29ybGQh'; // Hello World! + const { buff, ...metadata } = getContentMetadata(content); + const cid = await ipfsCore.add(buff, true); + const pinned = await ipfsCore.isPinned(cid); + await saveContentData({ cid, pinned, metadata }); + + return cid + } catch(error) { + return false + } +} + +async function isContentRetrievableFromGateway(cid: CID): Promise { + try { + const response = await fetch(generateGatewayURL(cid), { + redirect: 'follow' + }) + + return response.status === 200 + } catch(error) { + return false + } +} + +export { + healthCheck +} \ No newline at end of file diff --git a/src/routes/base.ts b/src/routes/base.ts new file mode 100644 index 0000000..688d701 --- /dev/null +++ b/src/routes/base.ts @@ -0,0 +1,9 @@ +import { Router } from "express"; + +import { healthCheck } from "../controllers/base"; + +const router = Router(); + +router.get("/health-check", healthCheck); + +export default { basePath: "/", router }; \ No newline at end of file diff --git a/src/routes/index.ts b/src/routes/index.ts index 6e971d4..d892e69 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -1,10 +1,11 @@ import { type NextFunction, type Request, type Response, Router } from "express"; import ERRORS from "../errors"; +import BaseRouter from './base' import IPFSRouter from "./ipfs"; const applicationRouter = Router(); -const routers = [IPFSRouter]; +const routers = [IPFSRouter, BaseRouter]; // Dynamically bind routers to the main application router routers.forEach((router) => {