Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active March 25, 2020 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradoyler/33cdc3ad5da37972efae80ba28d4ace9 to your computer and use it in GitHub Desktop.
Save bradoyler/33cdc3ad5da37972efae80ba28d4ace9 to your computer and use it in GitHub Desktop.
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