diff --git a/Common/Types/API/StatusCode.ts b/Common/Types/API/StatusCode.ts index 328d7ffb5b..d1a9b8aab8 100644 --- a/Common/Types/API/StatusCode.ts +++ b/Common/Types/API/StatusCode.ts @@ -30,7 +30,10 @@ export default class StatusCode { statusCode = parseInt(statusCode as string); } - if (statusCode as number >= 100 && statusCode as number <= 599) { + if ( + (statusCode as number) >= 100 && + (statusCode as number) <= 599 + ) { return true; } diff --git a/Common/Types/PositiveNumber.ts b/Common/Types/PositiveNumber.ts index 515ea4e032..562c22f83d 100644 --- a/Common/Types/PositiveNumber.ts +++ b/Common/Types/PositiveNumber.ts @@ -18,7 +18,7 @@ export default class PositiveNumber { } } - if (positiveNumber as number < 0) { + if ((positiveNumber as number) < 0) { throw new BadDataException('positiveNumber cannot be less than 0'); } diff --git a/CommonServer/Config.ts b/CommonServer/Config.ts index 065c13cb96..d5ed85068b 100644 --- a/CommonServer/Config.ts +++ b/CommonServer/Config.ts @@ -47,7 +47,7 @@ export const ClusterKey: ObjectID = new ObjectID( process.env['ONEUPTIME_SECRET'] || 'secret' ); -export const hasClusterKey: boolean = !!process.env['ONEUPTIME_SECRET']; +export const hasClusterKey: boolean = Boolean(process.env['ONEUPTIME_SECRET']); export const Domain: Hostname = Hostname.fromString( process.env['DOMAIN'] || 'localhost' diff --git a/CommonServer/Services/MonitorProbeService.ts b/CommonServer/Services/MonitorProbeService.ts index 0c6172f1e7..029162f072 100644 --- a/CommonServer/Services/MonitorProbeService.ts +++ b/CommonServer/Services/MonitorProbeService.ts @@ -1,32 +1,39 @@ import PostgresDatabase from '../Infrastructure/PostgresDatabase'; -import Model from 'Model/Models/MonitorProbe'; import DatabaseService, { OnCreate } from './DatabaseService'; import CreateBy from '../Types/Database/CreateBy'; import BadDataException from 'Common/Types/Exception/BadDataException'; +import MonitorProbe from 'Model/Models/MonitorProbe'; -export class Service extends DatabaseService { +export class Service extends DatabaseService { public constructor(postgresDatabase?: PostgresDatabase) { - super(Model, postgresDatabase); + super(MonitorProbe, postgresDatabase); } - protected override async onBeforeCreate(createBy: CreateBy): Promise> { - - if((createBy.data.monitorId || createBy.data.monitor) && (createBy.data.probeId || createBy.data.probe)){ - const monitorProbe = await this.findOneBy({ + protected override async onBeforeCreate( + createBy: CreateBy + ): Promise> { + if ( + (createBy.data.monitorId || createBy.data.monitor) && + (createBy.data.probeId || createBy.data.probe) + ) { + const monitorProbe: MonitorProbe | null = await this.findOneBy({ query: { - monitorId: createBy.data.monitorId! || createBy.data.monitor?.id!, - probeId: createBy.data.probeId! || createBy.data.probe?.id! + monitorId: + createBy.data.monitorId! || createBy.data.monitor?.id!, + probeId: createBy.data.probeId! || createBy.data.probe?.id!, }, select: { - _id: true + _id: true, }, props: { - isRoot: true - } + isRoot: true, + }, }); - if(monitorProbe){ - throw new BadDataException('Probe is already added to this monitor.'); + if (monitorProbe) { + throw new BadDataException( + 'Probe is already added to this monitor.' + ); } } diff --git a/CommonServer/Services/MonitorService.ts b/CommonServer/Services/MonitorService.ts index f449834537..2328088870 100644 --- a/CommonServer/Services/MonitorService.ts +++ b/CommonServer/Services/MonitorService.ts @@ -14,6 +14,7 @@ import { LIMIT_PER_PROJECT } from 'Common/Types/Database/LimitMax'; import MonitorProbe from 'Model/Models/MonitorProbe'; import MonitorProbeService from './MonitorProbeService'; import MonitorType from 'Common/Types/Monitor/MonitorType'; +import Probe from 'Model/Models/Probe'; export class Service extends DatabaseService { public constructor(postgresDatabase?: PostgresDatabase) { @@ -75,47 +76,59 @@ export class Service extends DatabaseService { onCreate.createBy.props ); - if(createdItem.monitorType && (createdItem.monitorType === MonitorType.API || createdItem.monitorType === MonitorType.IncomingRequest || createdItem.monitorType === MonitorType.Website || createdItem.monitorType === MonitorType.Ping || createdItem.monitorType === MonitorType.IP)) { - await this.addDefaultProbesToMonitor(createdItem.projectId, createdItem.id); + if ( + createdItem.monitorType && + (createdItem.monitorType === MonitorType.API || + createdItem.monitorType === MonitorType.IncomingRequest || + createdItem.monitorType === MonitorType.Website || + createdItem.monitorType === MonitorType.Ping || + createdItem.monitorType === MonitorType.IP) + ) { + await this.addDefaultProbesToMonitor( + createdItem.projectId, + createdItem.id + ); } return createdItem; } - - public async addDefaultProbesToMonitor(projectId: ObjectID, monitorId: ObjectID) { - const globalProbes = await ProbeService.findBy({ + public async addDefaultProbesToMonitor( + projectId: ObjectID, + monitorId: ObjectID + ): Promise { + const globalProbes: Array = await ProbeService.findBy({ query: { isGlobalProbe: true, - shouldAutoEnableProbeOnNewMonitors: true + shouldAutoEnableProbeOnNewMonitors: true, }, select: { - _id: true + _id: true, }, skip: 0, limit: LIMIT_PER_PROJECT, props: { - isRoot: true - } + isRoot: true, + }, }); - const projectProbes = await ProbeService.findBy({ + const projectProbes: Array = await ProbeService.findBy({ query: { isGlobalProbe: false, shouldAutoEnableProbeOnNewMonitors: true, - projectId: projectId + projectId: projectId, }, select: { - _id: true + _id: true, }, skip: 0, limit: LIMIT_PER_PROJECT, props: { - isRoot: true - } - }) + isRoot: true, + }, + }); - const totalProbes = [...globalProbes, ...projectProbes]; + const totalProbes: Array = [...globalProbes, ...projectProbes]; for (const probe of totalProbes) { const monitorProbe: MonitorProbe = new MonitorProbe(); @@ -128,8 +141,8 @@ export class Service extends DatabaseService { await MonitorProbeService.create({ data: monitorProbe, props: { - isRoot: true - } + isRoot: true, + }, }); } } diff --git a/CommonServer/Utils/CronTab.ts b/CommonServer/Utils/CronTab.ts index d5fb12b363..c20550dfd9 100644 --- a/CommonServer/Utils/CronTab.ts +++ b/CommonServer/Utils/CronTab.ts @@ -1,9 +1,9 @@ -import CronParser from 'cron-parser'; +import CronParser, { CronExpression } from 'cron-parser'; export default class CronTab { public static getNextExecutionTime(crontab: string): Date { - const interval = CronParser.parseExpression(crontab); - const nextExecutionTime = interval.next().toDate(); + const interval: CronExpression = CronParser.parseExpression(crontab); + const nextExecutionTime: Date = interval.next().toDate(); return nextExecutionTime; - } -} \ No newline at end of file + } +} diff --git a/CommonUI/src/Components/Table/TableRow.tsx b/CommonUI/src/Components/Table/TableRow.tsx index 842cf63ea0..c5f4a95176 100644 --- a/CommonUI/src/Components/Table/TableRow.tsx +++ b/CommonUI/src/Components/Table/TableRow.tsx @@ -125,7 +125,9 @@ const TableRow: FunctionComponent = ( props.item, column.key, '' - )?.toString() || column.noValueMessage || '' + )?.toString() || + column.noValueMessage || + '' ) ) : ( <> diff --git a/Dashboard/src/App.tsx b/Dashboard/src/App.tsx index d7e9d27a26..75a221fe5c 100644 --- a/Dashboard/src/App.tsx +++ b/Dashboard/src/App.tsx @@ -301,7 +301,7 @@ const App: FunctionComponent = () => { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { = ( <> This is a manual monitor. It does not monitor anything and so, it cannot have monitorting probes - set. You can have monitoring probes on other - monitor types.{' '} + set. You can have monitoring probes on other monitor + types.{' '} } /> ); } + return ( + + modelType={MonitorProbe} + query={{ + projectId: DashboardNavigation.getProjectId()?.toString(), + monitorId: modelId.toString(), + }} + onBeforeCreate={(item: MonitorProbe): MonitorProbe => { + item.monitorId = modelId; + item.projectId = DashboardNavigation.getProjectId()!; - return ( - modelType={MonitorProbe} - query={{ - projectId: - DashboardNavigation.getProjectId()?.toString(), - monitorId: modelId.toString(), - - }} - onBeforeCreate={(item: MonitorProbe): MonitorProbe => { - item.monitorId = modelId; - item.projectId = DashboardNavigation.getProjectId()! - - return item; - }} - id="probes-table" - name="Monitor > Monitor Probes" - isDeleteable={false} - isEditable={true} - isCreateable={true} - cardProps={{ - icon: IconProp.Signal, - title: 'Probes', - description: - 'List of probes that help you monitor this resource.', - }} - noItemsMessage={'No probes found for this resource. However, you can add some probes to monitor this resource.'} - viewPageRoute={Navigation.getCurrentRoute()} - formFields={[ - { - field: { - probe: true, + return item; + }} + id="probes-table" + name="Monitor > Monitor Probes" + isDeleteable={false} + isEditable={true} + isCreateable={true} + cardProps={{ + icon: IconProp.Signal, + title: 'Probes', + description: + 'List of probes that help you monitor this resource.', + }} + noItemsMessage={ + 'No probes found for this resource. However, you can add some probes to monitor this resource.' + } + viewPageRoute={Navigation.getCurrentRoute()} + formFields={[ + { + field: { + probe: true, + }, + title: 'Probe', + stepId: 'incident-details', + description: 'Which probe do you want to use?', + fieldType: FormFieldSchemaType.Dropdown, + dropdownModal: { + type: Probe, + labelField: 'name', + valueField: '_id', + }, + required: true, + placeholder: 'Probe', }, - title: 'Probe', - stepId: 'incident-details', - description: 'Which probe do you want to use?', - fieldType: FormFieldSchemaType.Dropdown, - dropdownModal: { - type: Probe, - labelField: 'name', - valueField: '_id', - }, - required: true, - placeholder: 'Probe', - }, - - { - field: { - isEnabled: true, + { + field: { + isEnabled: true, + }, + title: 'Enabled', + fieldType: FormFieldSchemaType.Toggle, + required: false, }, - title: 'Enabled', - fieldType: FormFieldSchemaType.Toggle, - required: false, - }, - ]} - showRefreshButton={true} - showFilterButton={false} - - columns={[ - { - field: { - probe: { - name: true, - iconFileId: true, + ]} + showRefreshButton={true} + showFilterButton={false} + columns={[ + { + field: { + probe: { + name: true, + iconFileId: true, + }, + }, + isFilterable: false, + title: 'Probe', + type: FieldType.Entity, + getElement: (item: JSONObject): ReactElement => { + return ( + + ); }, }, - isFilterable: false, - title: 'Probe', - type: FieldType.Entity, - getElement: (item: JSONObject): ReactElement => { - return ; + { + field: { + lastPingAt: true, + }, + title: 'Last Monitored At', + type: FieldType.DateTime, + isFilterable: false, + noValueMessage: 'Will be picked up by this probe soon.', }, - }, - { - field: { - lastPingAt: true, + { + field: { + isEnabled: true, + }, + title: 'Enabled', + type: FieldType.Boolean, + isFilterable: false, }, - title: 'Last Monitored At', - type: FieldType.DateTime, - isFilterable: false, - noValueMessage: 'Will be picked up by this probe soon.', - - }, - { - field: { - isEnabled: true, - }, - title: 'Enabled', - type: FieldType.Boolean, - isFilterable: false, - - }, - ]} - />) + ]} + /> + ); }; return ( diff --git a/Dashboard/src/Pages/Monitor/View/SideMenu.tsx b/Dashboard/src/Pages/Monitor/View/SideMenu.tsx index 852f88f22d..a77069a47c 100644 --- a/Dashboard/src/Pages/Monitor/View/SideMenu.tsx +++ b/Dashboard/src/Pages/Monitor/View/SideMenu.tsx @@ -78,13 +78,11 @@ const DashboardSideMenu: FunctionComponent = ( - = ( placeholder: 'This probe is to monitor all the internal services.', }, - + { field: { iconFile: true, diff --git a/Dashboard/src/Utils/RouteMap.ts b/Dashboard/src/Utils/RouteMap.ts index 295004f61a..14f20b63eb 100644 --- a/Dashboard/src/Utils/RouteMap.ts +++ b/Dashboard/src/Utils/RouteMap.ts @@ -31,7 +31,6 @@ const RouteMap: Dictionary = { `/dashboard/${RouteParams.ProjectID}/monitor/${RouteParams.ModelID}/probes` ), - [PageMap.MONITOR_VIEW_CRITERIA]: new Route( `/dashboard/${RouteParams.ProjectID}/monitor/${RouteParams.ModelID}/criteria` ), diff --git a/Model/Models/Index.ts b/Model/Models/Index.ts index a7eb839d26..9cdf5822af 100644 --- a/Model/Models/Index.ts +++ b/Model/Models/Index.ts @@ -135,5 +135,5 @@ export default [ ProjectSSO, StatusPageSSO, - MonitorProbe + MonitorProbe, ]; diff --git a/Model/Models/Probe.ts b/Model/Models/Probe.ts index 93c866ba69..df402cdf46 100755 --- a/Model/Models/Probe.ts +++ b/Model/Models/Probe.ts @@ -429,7 +429,6 @@ export default class Probe extends BaseModel { }) public isGlobalProbe?: boolean = undefined; - @ColumnAccessControl({ create: [ Permission.ProjectOwner, diff --git a/Probe/Config.ts b/Probe/Config.ts index 1959aac748..d12f09feab 100644 --- a/Probe/Config.ts +++ b/Probe/Config.ts @@ -1,9 +1,9 @@ -import URL from "Common/Types/API/URL"; +import URL from 'Common/Types/API/URL'; import logger from 'CommonServer/Utils/Logger'; -import ObjectID from "Common/Types/ObjectID"; +import ObjectID from 'Common/Types/ObjectID'; -if(!process.env['PROBE_API_URL']){ - logger.error("PROBE_API_URL is not set"); +if (!process.env['PROBE_API_URL']) { + logger.error('PROBE_API_URL is not set'); process.exit(); } @@ -11,14 +11,16 @@ export const PROBE_API_URL: URL = URL.fromString(process.env['PROBE_API_URL']); export const PROBE_NAME: string | null = process.env['PROBE_NAME'] || null; -export const PROBE_DESCRIPTION: string | null = process.env['PROBE_DESCRIPTION'] || null; +export const PROBE_DESCRIPTION: string | null = + process.env['PROBE_DESCRIPTION'] || null; -export const PROBE_ID: ObjectID | null = process.env['PROBE_ID'] ? new ObjectID(process.env['PROBE_ID']) : null; +export const PROBE_ID: ObjectID | null = process.env['PROBE_ID'] + ? new ObjectID(process.env['PROBE_ID']) + : null; -if(!process.env['PROBE_KEY']){ - logger.error("PROBE_KEY is not set"); +if (!process.env['PROBE_KEY']) { + logger.error('PROBE_KEY is not set'); process.exit(); } export const PROBE_KEY: string = process.env['PROBE_KEY']; - diff --git a/Probe/Index.ts b/Probe/Index.ts index ce488875c1..74fc01051d 100644 --- a/Probe/Index.ts +++ b/Probe/Index.ts @@ -12,9 +12,8 @@ const init: Function = async (): Promise => { // init the app await App(APP_NAME); - // Register this probe. + // Register this probe. await Register.registerProbe(); - } catch (err) { logger.error('App Init Failed:'); logger.error(err); diff --git a/Probe/Jobs/Alive.ts b/Probe/Jobs/Alive.ts index 3ab50b4404..f723cbd9b5 100644 --- a/Probe/Jobs/Alive.ts +++ b/Probe/Jobs/Alive.ts @@ -1,23 +1,29 @@ -import API from "Common/Utils/API"; -import RunCron from "../Utils/Cron"; +import API from 'Common/Utils/API'; +import RunCron from '../Utils/Cron'; import { EVERY_MINUTE } from 'Common/Utils/CronTime'; -import { PROBE_API_URL, PROBE_KEY } from "../Config"; -import LocalCache from "CommonServer/Infrastructure/LocalCache"; -import URL from "Common/Types/API/URL"; -import logger from "CommonServer/Utils/Logger"; +import { PROBE_API_URL, PROBE_KEY } from '../Config'; +import LocalCache from 'CommonServer/Infrastructure/LocalCache'; +import URL from 'Common/Types/API/URL'; +import logger from 'CommonServer/Utils/Logger'; -RunCron('Basic:Alive', { - schedule: EVERY_MINUTE, - runOnStartup: false, -}, async ()=>{ +RunCron( + 'Basic:Alive', + { + schedule: EVERY_MINUTE, + runOnStartup: false, + }, + async () => { + if (!LocalCache.getString('PROBE', 'PROBE_ID')) { + logger.warn('Probe is not registered yet. Skipping alive check.'); + return; + } - if(!LocalCache.getString("PROBE", "PROBE_ID")){ - logger.warn("Probe is not registered yet. Skipping alive check."); - return; + await API.post( + URL.fromString(PROBE_API_URL.toString()).addRoute('/alive'), + { + probeKey: PROBE_KEY, + probeId: LocalCache.getString('PROBE', 'PROBE_ID'), + } + ); } - - await API.post(URL.fromString(PROBE_API_URL.toString()).addRoute("/alive"), { - "probeKey": PROBE_KEY, - "probeId": LocalCache.getString("PROBE", "PROBE_ID"), - }); -}); \ No newline at end of file +); diff --git a/Probe/Jobs/Monitor.ts b/Probe/Jobs/Monitor.ts index 364f405e0f..dd5d028e99 100644 --- a/Probe/Jobs/Monitor.ts +++ b/Probe/Jobs/Monitor.ts @@ -1,27 +1,33 @@ -import API from "Common/Utils/API"; -import RunCron from "../Utils/Cron"; +import API from 'Common/Utils/API'; +import RunCron from '../Utils/Cron'; import { EVERY_MINUTE } from 'Common/Utils/CronTime'; -import { PROBE_API_URL, PROBE_KEY } from "../Config"; -import LocalCache from "CommonServer/Infrastructure/LocalCache"; -import URL from "Common/Types/API/URL"; -import logger from "CommonServer/Utils/Logger"; +import { PROBE_API_URL, PROBE_KEY } from '../Config'; +import LocalCache from 'CommonServer/Infrastructure/LocalCache'; +import URL from 'Common/Types/API/URL'; +import logger from 'CommonServer/Utils/Logger'; -RunCron('Basic:Monitor', { - schedule: EVERY_MINUTE, - runOnStartup: false, -}, async ()=>{ +RunCron( + 'Basic:Monitor', + { + schedule: EVERY_MINUTE, + runOnStartup: false, + }, + async () => { + // get a list of monitors from probe-api - // get a list of monitors from probe-api + // for each monitor, ping and then report back to probe-api - // for each monitor, ping and then report back to probe-api + if (!LocalCache.getString('PROBE', 'PROBE_ID')) { + logger.warn('Probe is not registered yet. Skipping alive check.'); + return; + } - if(!LocalCache.getString("PROBE", "PROBE_ID")){ - logger.warn("Probe is not registered yet. Skipping alive check."); - return; + await API.post( + URL.fromString(PROBE_API_URL.toString()).addRoute('/alive'), + { + probeKey: PROBE_KEY, + probeId: LocalCache.getString('PROBE', 'PROBE_ID'), + } + ); } - - await API.post(URL.fromString(PROBE_API_URL.toString()).addRoute("/alive"), { - "probeKey": PROBE_KEY, - "probeId": LocalCache.getString("PROBE", "PROBE_ID"), - }); -}); \ No newline at end of file +); diff --git a/Probe/Services/Register.ts b/Probe/Services/Register.ts index eed37550a8..961f712a50 100644 --- a/Probe/Services/Register.ts +++ b/Probe/Services/Register.ts @@ -1,43 +1,55 @@ -import API from "Common/Utils/API"; -import { PROBE_API_URL, PROBE_DESCRIPTION, PROBE_ID, PROBE_KEY, PROBE_NAME } from "../Config"; -import URL from "Common/Types/API/URL"; -import { ClusterKey, hasClusterKey } from "CommonServer/Config"; -import logger from "CommonServer/Utils/Logger"; -import HTTPResponse from "Common/Types/API/HTTPResponse"; -import { JSONObject } from "Common/Types/JSON"; -import LocalCache from "CommonServer/Infrastructure/LocalCache"; +import API from 'Common/Utils/API'; +import { + PROBE_API_URL, + PROBE_DESCRIPTION, + PROBE_ID, + PROBE_KEY, + PROBE_NAME, +} from '../Config'; +import URL from 'Common/Types/API/URL'; +import { ClusterKey, hasClusterKey } from 'CommonServer/Config'; +import logger from 'CommonServer/Utils/Logger'; +import HTTPResponse from 'Common/Types/API/HTTPResponse'; +import { JSONObject } from 'Common/Types/JSON'; +import LocalCache from 'CommonServer/Infrastructure/LocalCache'; export default class Register { public static async registerProbe(): Promise { + if (hasClusterKey) { + const resullt: HTTPResponse = await API.post( + URL.fromString(PROBE_API_URL.toString()).addRoute('/register'), + { + probeKey: PROBE_KEY, + probeName: PROBE_NAME, + probeDescription: PROBE_DESCRIPTION, + clusterKey: ClusterKey.toString(), + } + ); - if(hasClusterKey){ - const resullt: HTTPResponse = await API.post(URL.fromString(PROBE_API_URL.toString()).addRoute("/register"), { - "probeKey": PROBE_KEY, - "probeName": PROBE_NAME, - "probeDescription": PROBE_DESCRIPTION, - "clusterKey": ClusterKey.toString() - }); - - if(resullt.isSuccess()){ - const probeId = resullt.data['_id']; - LocalCache.setString("PROBE", "PROBE_ID", probeId as string); + if (resullt.isSuccess()) { + const probeId: string = resullt.data['_id'] as string; + LocalCache.setString('PROBE', 'PROBE_ID', probeId as string); } - - }else{ + } else { // validate probe. - if(!PROBE_ID){ - logger.error("PROBE_ID or ONEUPTIME_SECRET should be set"); + if (!PROBE_ID) { + logger.error('PROBE_ID or ONEUPTIME_SECRET should be set'); return process.exit(); } - await API.post(URL.fromString(PROBE_API_URL.toString()).addRoute("/alive"), { - "probeKey": PROBE_KEY.toString(), - "probeId": PROBE_ID.toString(), - }) + await API.post( + URL.fromString(PROBE_API_URL.toString()).addRoute('/alive'), + { + probeKey: PROBE_KEY.toString(), + probeId: PROBE_ID.toString(), + } + ); - LocalCache.setString("PROBE", "PROBE_ID", PROBE_ID.toString() as string); + LocalCache.setString( + 'PROBE', + 'PROBE_ID', + PROBE_ID.toString() as string + ); } - - } -} \ No newline at end of file +} diff --git a/Probe/Utils/Cron.ts b/Probe/Utils/Cron.ts index e7191558d8..fdd75798a9 100644 --- a/Probe/Utils/Cron.ts +++ b/Probe/Utils/Cron.ts @@ -9,7 +9,6 @@ const RunCron: Function = ( }, runFunction: Function ): void => { - cron.schedule(options.schedule, async () => { try { logger.info(`Job ${jobName} Start`); @@ -21,7 +20,7 @@ const RunCron: Function = ( } }); - if(options.runOnStartup) { + if (options.runOnStartup) { runFunction(); } }; diff --git a/ProbeAPI/API/Alive.ts b/ProbeAPI/API/Alive.ts index 530471a929..6725ad8421 100644 --- a/ProbeAPI/API/Alive.ts +++ b/ProbeAPI/API/Alive.ts @@ -18,8 +18,7 @@ router.post( next: NextFunction ): Promise => { try { - - // middleware marks the probe as alive. + // middleware marks the probe as alive. // so we dont need to do anything here. return Response.sendEmptyResponse(req, res); } catch (err) { diff --git a/ProbeAPI/API/Monitor.ts b/ProbeAPI/API/Monitor.ts index 9e49f07438..89b866de95 100644 --- a/ProbeAPI/API/Monitor.ts +++ b/ProbeAPI/API/Monitor.ts @@ -12,9 +12,10 @@ import QueryHelper from 'CommonServer/Types/Database/QueryHelper'; import OneUptimeDate from 'Common/Types/Date'; import { ProbeExpressRequest } from '../Types/Request'; import BadDataException from 'Common/Types/Exception/BadDataException'; -import CronTab from "CommonServer/Utils/CronTab" +import CronTab from 'CommonServer/Utils/CronTab'; import Monitor from 'Model/Models/Monitor'; import PositiveNumber from 'Common/Types/PositiveNumber'; +import { JSONObject } from 'Common/Types/JSON'; const router: ExpressRouter = Express.getRouter(); @@ -27,12 +28,13 @@ router.post( next: NextFunction ): Promise => { try { - - const data = req.body; - const limit = data['limit'] as number || 100; + const data: JSONObject = req.body; + const limit: number = (data['limit'] as number) || 100; - - if(!(req as ProbeExpressRequest).probe || !(req as ProbeExpressRequest).probe?.id){ + if ( + !(req as ProbeExpressRequest).probe || + !(req as ProbeExpressRequest).probe?.id + ) { return Response.sendErrorResponse( req, res, @@ -41,55 +43,65 @@ router.post( } //get list of monitors to be monitored - const monitorProbes: Array = await MonitorProbeService.findBy({ - query: { - probeId: ((req as ProbeExpressRequest).probe)!.id!, - isEnabled: true, - nextPingAt: QueryHelper.lessThanEqualTo( - OneUptimeDate.getCurrentDate() - ) - }, - skip: 0, - limit: limit, - select: { - probeId: true, - monitorId: true - }, - populate: { - monitor: { - monitorSteps: true, - monitorType: true, - monitoringInterval: true, - } - }, - props: { - isRoot: true - } - }); + const monitorProbes: Array = + await MonitorProbeService.findBy({ + query: { + probeId: (req as ProbeExpressRequest).probe!.id!, + isEnabled: true, + nextPingAt: QueryHelper.lessThanEqualTo( + OneUptimeDate.getCurrentDate() + ), + }, + skip: 0, + limit: limit, + select: { + probeId: true, + monitorId: true, + }, + populate: { + monitor: { + monitorSteps: true, + monitorType: true, + monitoringInterval: true, + }, + }, + props: { + isRoot: true, + }, + }); // update the lastMonitoredAt field of the monitors - for(const monitorProbe of monitorProbes){ + for (const monitorProbe of monitorProbes) { await MonitorProbeService.updateOneById({ id: monitorProbe.id!, data: { lastPingAt: OneUptimeDate.getCurrentDate(), - nextPingAt: CronTab.getNextExecutionTime(monitorProbe?.monitor?.monitoringInterval as string) + nextPingAt: CronTab.getNextExecutionTime( + monitorProbe?.monitor?.monitoringInterval as string + ), }, props: { - isRoot: true - } + isRoot: true, + }, }); } - - const monitors: Array = monitorProbes.map((monitorProbe) => { - return monitorProbe.monitor!; - }); + const monitors: Array = monitorProbes.map( + (monitorProbe: MonitorProbe) => { + return monitorProbe.monitor!; + } + ); // return the list of monitors to be monitored - return Response.sendEntityArrayResponse(req, res, monitors, new PositiveNumber(monitors.length), Monitor); + return Response.sendEntityArrayResponse( + req, + res, + monitors, + new PositiveNumber(monitors.length), + Monitor + ); } catch (err) { return next(err); } diff --git a/ProbeAPI/API/Register.ts b/ProbeAPI/API/Register.ts index a4d2831da1..44f770d073 100644 --- a/ProbeAPI/API/Register.ts +++ b/ProbeAPI/API/Register.ts @@ -50,13 +50,12 @@ router.post( }); if (probe) { - await ProbeService.updateOneById({ id: probe.id!, data: { name: data['probeName'] as string, description: data['probeDescription'] as string, - lastAlive: OneUptimeDate.getCurrentDate() + lastAlive: OneUptimeDate.getCurrentDate(), }, props: { isRoot: true, diff --git a/ProbeAPI/Middleware/ProbeAuthorization.ts b/ProbeAPI/Middleware/ProbeAuthorization.ts index faa7acf5b7..105ae52a65 100644 --- a/ProbeAPI/Middleware/ProbeAuthorization.ts +++ b/ProbeAPI/Middleware/ProbeAuthorization.ts @@ -1,8 +1,5 @@ import { ClusterKey as ONEUPTIME_SECRET } from 'CommonServer/Config'; -import { - ExpressResponse, - NextFunction, -} from 'CommonServer/Utils/Express'; +import { ExpressResponse, NextFunction } from 'CommonServer/Utils/Express'; import Response from 'CommonServer/Utils/Response'; import BadDataException from 'Common/Types/Exception/BadDataException'; @@ -28,51 +25,51 @@ export default class ProbeAuthorization { ): Promise { const data: JSONObject = req.body; - if (!data['probeId'] || !data['probeKey']) { - return Response.sendErrorResponse( - req, - res, - new BadDataException('ProbeId or ProbeKey is missing') - ); - } + if (!data['probeId'] || !data['probeKey']) { + return Response.sendErrorResponse( + req, + res, + new BadDataException('ProbeId or ProbeKey is missing') + ); + } - const probeId: ObjectID = new ObjectID(data['probeId'] as string); + const probeId: ObjectID = new ObjectID(data['probeId'] as string); - const probeKey: string = data['probeKey'] as string; + const probeKey: string = data['probeKey'] as string; - const probe: Probe | null = await ProbeService.findOneBy({ - query: { - _id: probeId.toString(), - key: probeKey, - }, - select: { - _id: true, - }, - props: { - isRoot: true, - }, - }); + const probe: Probe | null = await ProbeService.findOneBy({ + query: { + _id: probeId.toString(), + key: probeKey, + }, + select: { + _id: true, + }, + props: { + isRoot: true, + }, + }); - if (!probe) { - return Response.sendErrorResponse( - req, - res, - new BadDataException('Invalid Probe ID or Probe Key') - ); - } + if (!probe) { + return Response.sendErrorResponse( + req, + res, + new BadDataException('Invalid Probe ID or Probe Key') + ); + } - await ProbeService.updateOneById({ - id: probeId, - data: { - lastAlive: OneUptimeDate.getCurrentDate(), - }, - props: { - isRoot: true, - }, - }); + await ProbeService.updateOneById({ + id: probeId, + data: { + lastAlive: OneUptimeDate.getCurrentDate(), + }, + props: { + isRoot: true, + }, + }); - req.probe = probe; + req.probe = probe; - return next(); + return next(); } } diff --git a/ProbeAPI/Types/Request.ts b/ProbeAPI/Types/Request.ts index a6806dcecc..00f6bd6abd 100644 --- a/ProbeAPI/Types/Request.ts +++ b/ProbeAPI/Types/Request.ts @@ -1,6 +1,6 @@ -import { ExpressRequest } from "CommonServer/Utils/Express"; -import Probe from "Model/Models/Probe"; +import { ExpressRequest } from 'CommonServer/Utils/Express'; +import Probe from 'Model/Models/Probe'; export interface ProbeExpressRequest extends ExpressRequest { probe?: Probe | undefined; -} \ No newline at end of file +}