Skip to content

Commit

Permalink
Add api call to generate access_token
Browse files Browse the repository at this point in the history
  • Loading branch information
chtushar committed Nov 16, 2023
1 parent 2b4f03c commit af8b733
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 29 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules
dist
.DS_Store
.idea
.idea
.env
52 changes: 52 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@typescript-eslint/parser": "^5.61.0",
"@vitest/ui": "^0.34.1",
"axios": "^1.4.0",
"dotenv": "^16.3.1",
"eslint": "^8.44.0",
"eslint-config-semistandard": "^17.0.0",
"eslint-config-standard": "^17.1.0",
Expand All @@ -59,6 +60,7 @@
"dependencies": {
"prom-client": "^14.2.0",
"response-time": "^2.3.2",
"undici": "^5.27.2",
"url-value-parser": "^2.2.0"
},
"peerDependenciesMeta": {
Expand Down
17 changes: 10 additions & 7 deletions playground/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* Also, comment out the things that you are not using. For example, you can comment out the mysql code if you are
* not testing or developing for the same
* */
require('dotenv').config();
var express = require('express');
var { OpenAPM } = require('../dist/index.js');
var mysql2 = require('mysql2');
Expand All @@ -15,15 +16,17 @@ const openapm = new OpenAPM({
mask: ':org'
}
},
levitateConfig: {
orgSlug: process.env['LEVITATE_ORG_SLUG'],
dataSourceName: process.env['LEVITATE_DATASOURCE'],
refreshTokens: {
write: process.env['LEVITATE_WRITE_REFRESH_TOKEN']
}
},
customPathsToMask: [/\b\d+(?:,\d+)*\b/gm],
excludeDefaultLabels: ['host', 'program']
});
openapm.on('application_started', (domainEvents) => {
console.log(domainEvents);
});
openapm.on('application_stopped', (domainEvents) => {
console.log(domainEvents);
});

openapm.instrument('express');
openapm.instrument('mysql');

Expand Down Expand Up @@ -58,6 +61,6 @@ app.get('/cancel/:ids', (req, res) => {
res.status(200).json({});
});

app.listen(3000, () => {
const server = app.listen(3000, () => {
console.log('serving at 3000');
});
4 changes: 1 addition & 3 deletions src/OpenAPM.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ export class OpenAPM extends LevitateEvents {
private metricsServerPort: number;
readonly environment: string;
readonly program: string;
readonly levitateConfig?: LevitateConfig | undefined;
private defaultLabels?: Record<string, string>;
private requestsCounterConfig: CounterConfiguration<string>;
private requestDurationHistogramConfig: HistogramConfiguration<string>;
Expand All @@ -94,7 +93,7 @@ export class OpenAPM extends LevitateEvents {
public metricsServer?: Server;

constructor(options?: OpenAPMOptions) {
super();
super(options);
// Initializing all the options
this.path = options?.path ?? '/metrics';
this.metricsServerPort = options?.metricsServerPort ?? 9097;
Expand Down Expand Up @@ -127,7 +126,6 @@ export class OpenAPM extends LevitateEvents {
this.extractLabels = options?.extractLabels ?? {};
this.customPathsToMask = options?.customPathsToMask;
this.excludeDefaultLabels = options?.excludeDefaultLabels;
this.levitateConfig = options?.levitateConfig;

this.initiateMetricsRoute();
this.initiatePromClient();
Expand Down
53 changes: 35 additions & 18 deletions src/levitate/events.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import EventEmitter from 'events';
import type { OpenAPMOptions } from '../OpenAPM';
import { fetch, request } from 'undici';

export interface LevitateConfig {
host?: string;
Expand All @@ -23,9 +25,10 @@ const defaultHost = 'https://app.last9.io';

export class LevitateEvents extends EventEmitter {
private eventsUrl: URL;
public levitateConfig?: LevitateConfig;
constructor() {
readonly levitateConfig?: LevitateConfig;
constructor(options?: OpenAPMOptions) {
super();
this.levitateConfig = options?.levitateConfig;
this.eventsUrl = new URL(
`/api/v4/organizations/${this.levitateConfig?.orgSlug}/domain_events`,
this.levitateConfig?.host ?? defaultHost
Expand Down Expand Up @@ -77,25 +80,39 @@ export class LevitateEvents extends EventEmitter {
}
}

private putDomainEvents(body: DomainEventsBody) {
const params = new URLSearchParams();
private generateAccessToken = () => {
const endpoint = '/api/v4/oauth/access_token';
const url = new URL(endpoint, this.levitateConfig?.host ?? defaultHost);

try {
return fetch(url.toString(), {
method: 'POST',
body: JSON.stringify({
refresh_token: this.levitateConfig?.refreshTokens.write ?? ''
})
}).then((response) => {
return response.json();
}) as Promise<{ access_token: string }>;
} catch (error) {
console.log(error);
}
};

private async putDomainEvents(body: DomainEventsBody) {
if (!!body) {
for (const key in body) {
if (key in body) {
params.append(key, body[key]);
}
try {
const tokenResponse = await this.generateAccessToken();
await request(this.eventsUrl.toString(), {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-LAST9-API-TOKEN': `Bearer ${tokenResponse?.access_token}`
},
body: JSON.stringify(body)
});
} catch (error) {
console.log(error);
}

fetch(this.eventsUrl.toString(), {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-LAST9-API-TOKEN': `Bearer `
},
body: params
});
console.log(params);
}
}
}

0 comments on commit af8b733

Please sign in to comment.