|
| 1 | +import { Injectable, Inject, forwardRef } from '@nestjs/common'; |
| 2 | +import axios from 'axios'; |
| 3 | + |
| 4 | +@Injectable() |
| 5 | +export class HealtCheckService { |
| 6 | + healthChecks = [ |
| 7 | + { |
| 8 | + protocol: 'http', |
| 9 | + host: 'localhost', |
| 10 | + path: '/healt/alive', |
| 11 | + port: '3001', |
| 12 | + }, |
| 13 | + { |
| 14 | + protocol: 'http', |
| 15 | + host: 'localhost', |
| 16 | + path: '/healt/dead', |
| 17 | + port: '3001', |
| 18 | + }, |
| 19 | + ]; |
| 20 | + |
| 21 | + checkAllEndpoints() { |
| 22 | + const checkPromises = []; |
| 23 | + |
| 24 | + this.healthChecks.forEach(healthCheck => { |
| 25 | + checkPromises.push(this.checkEndpoint(healthCheck)); |
| 26 | + }); |
| 27 | + |
| 28 | + let checkResults = []; |
| 29 | + |
| 30 | + return this.allSettled(checkPromises).then(results => { |
| 31 | + results.forEach((result, index) => { |
| 32 | + if (result.state === 'rejected') { |
| 33 | + checkResults.push({ |
| 34 | + path: this.healthChecks[index].path, |
| 35 | + status: 'failed', |
| 36 | + }); |
| 37 | + } else { |
| 38 | + checkResults.push({ |
| 39 | + path: this.healthChecks[index].path, |
| 40 | + status: 'ok', |
| 41 | + }); |
| 42 | + } |
| 43 | + }); |
| 44 | + |
| 45 | + return checkResults; |
| 46 | + }); |
| 47 | + } |
| 48 | + |
| 49 | + private checkEndpoint(healthCheck): Promise<any> { |
| 50 | + let uri = `${healthCheck.protocol}://${healthCheck.host}`; |
| 51 | + |
| 52 | + if (healthCheck.port) { |
| 53 | + uri += `:${healthCheck.port}`; |
| 54 | + } |
| 55 | + |
| 56 | + uri += healthCheck.path; |
| 57 | + |
| 58 | + //TODO (ivasiljevic) use http service instead of axios |
| 59 | + return axios({ |
| 60 | + url: uri, |
| 61 | + method: 'GET', |
| 62 | + }); |
| 63 | + } |
| 64 | + |
| 65 | + private allSettled(promises: Promise<any>[]): Promise<any> { |
| 66 | + let wrappedPromises = promises.map(p => |
| 67 | + Promise.resolve(p).then( |
| 68 | + val => ({ state: 'fulfilled', value: val }), |
| 69 | + err => ({ state: 'rejected', value: err }), |
| 70 | + ), |
| 71 | + ); |
| 72 | + |
| 73 | + return Promise.all(wrappedPromises); |
| 74 | + } |
| 75 | +} |
0 commit comments