Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Client for Azure Application Insights REST API

AppInsights Client for Nodejs

Because the LogAnalyticsClient Azure SDK is not usable

Usage

import { AppInsightsClient } from './AppInsightsClient'

const client = new AppInsightsClient('AI_APPID', 'AI_APIKEY')

const timespan = 'PT4H'
const query = 'customEvents | where name == 'foo' | limit 5'

const objects = await client.query(query, timespan)

Get an API Key

image

import * as rp from 'request-promise-native'
function convertTable (columns: any[], rows: any[]): any[] {
return rows.map((row: any[]) => columns.reduce((obj, col, idx) => {
obj[col.name] = row[idx]
return obj
}, {}))
}
// API reference @ https://dev.applicationinsights.io/reference
export class AppInsightsClient {
private static instance: AppInsightsClient
// eslint-disable-next-line no-useless-constructor
constructor (
private appId: string = process.env.AAI_APPID,
private apiKey: string = process.env.AAI_APIKEY,
private baseUrl: string = 'https://api.applicationinsights.io/v1/apps'
) {}
static getInstance () {
if (!AppInsightsClient.instance) AppInsightsClient.instance = new AppInsightsClient()
return AppInsightsClient.instance
}
private baseRequest (options: any = { uri: '' }): Promise<any> {
return rp({
baseUrl: `${this.baseUrl}/${this.appId}`,
json: true,
headers: { 'x-api-key': this.apiKey },
...options
})
}
// Docs: https://dev.applicationinsights.io/reference/post-query
async query (query: string, timespan: string): Promise<any> {
const options = {
method: 'POST',
uri: `/query?timespan=${timespan}`,
body: { query }
}
return this.baseRequest(options).then(d => convertTable(d.tables[0].columns, d.tables[0].rows))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment