Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(nestjs): Update scope transaction name with parameterized route #11510

Merged
merged 3 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ export class AppController1 {
return this.appService.testError();
}

@Get('test-exception')
async testException() {
return this.appService.testException();
@Get('test-exception/:id')
async testException(@Param('id') id: string) {
return this.appService.testException(id);
}

@Get('test-outgoing-fetch-external-allowed')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ export class AppService1 {
return { exceptionId };
}

testException() {
throw new Error('This is an exception');
testException(id: string) {
throw new Error(`This is an exception with id ${id}`);
}

async testOutgoingFetchExternalAllowed() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,28 +43,28 @@ test('Sends captured error to Sentry', async ({ baseURL }) => {

test('Sends exception to Sentry', async ({ baseURL }) => {
const errorEventPromise = waitForError('node-nestjs-app', event => {
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception';
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception with id 123';
});

try {
axios.get(`${baseURL}/test-exception`);
axios.get(`${baseURL}/test-exception/123`);
} catch {
// this results in an error, but we don't care - we want to check the error event
}

const errorEvent = await errorEventPromise;

expect(errorEvent.exception?.values).toHaveLength(1);
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception');
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception with id 123');

expect(errorEvent.request).toEqual({
method: 'GET',
cookies: {},
headers: expect.any(Object),
url: 'http://localhost:3030/test-exception',
url: 'http://localhost:3030/test-exception/123',
});

expect(errorEvent.transaction).toEqual('GET /test-exception');
expect(errorEvent.transaction).toEqual('GET /test-exception/:id');

expect(errorEvent.contexts?.trace).toEqual({
trace_id: expect.any(String),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck These are only tests
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { loggingTransport, sendPortToRunner } from '@sentry-internal/node-integration-tests';
import * as Sentry from '@sentry/node';

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
release: '1.0',
tracesSampleRate: 0,
transport: loggingTransport,
integrations: integrations => integrations.filter(i => i.name !== 'Express'),
debug: true,
});

import { Controller, Get, Injectable, Module, Param } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

const port = 3480;

// Stop the process from exiting before the transaction is sent
// eslint-disable-next-line @typescript-eslint/no-empty-function
setInterval(() => {}, 1000);

@Injectable()
class AppService {
getHello(): string {
return 'Hello World!';
}
}

@Controller()
class AppController {
constructor(private readonly appService: AppService) {}

@Get('test-exception/:id')
async testException(@Param('id') id: string): void {
Sentry.captureException(new Error(`error with id ${id}`));
}
}

@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
class AppModule {}

async function init(): Promise<void> {
const app = await NestFactory.create(AppModule);
Sentry.setupNestErrorHandler(app);
await app.listen(port);
sendPortToRunner(port);
}

// eslint-disable-next-line @typescript-eslint/no-floating-promises
init();
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { conditionalTest } from '../../../utils';
import { cleanupChildProcesses, createRunner } from '../../../utils/runner';

jest.setTimeout(20000);

const { TS_VERSION } = process.env;
const isOldTS = TS_VERSION && TS_VERSION.startsWith('3.');

// This is required to run the test with ts-node and decorators
process.env.TS_NODE_PROJECT = `${__dirname}/tsconfig.json`;

conditionalTest({ min: 16 })('nestjs auto instrumentation', () => {
afterAll(async () => {
cleanupChildProcesses();
});

test("should assign scope's transactionName if spans are not sampled and express integration is disabled", done => {
if (isOldTS) {
// Skipping test on old TypeScript
return done();
}

createRunner(__dirname, 'scenario.ts')
.expect({
event: {
exception: {
values: [
{
value: 'error with id 456',
},
],
},
transaction: 'GET /test-exception/:id',
},
})
.start(done)
.makeRequest('get', '/test-exception/456');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"include": ["scenario.ts"],
"compilerOptions": {
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "ES2021",
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck These are only tests
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { loggingTransport, sendPortToRunner } from '@sentry-internal/node-integration-tests';
import * as Sentry from '@sentry/node';

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
release: '1.0',
tracesSampleRate: 0,
transport: loggingTransport,
});

import { Controller, Get, Injectable, Module, Param } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

const port = 3460;

// Stop the process from exiting before the transaction is sent
// eslint-disable-next-line @typescript-eslint/no-empty-function
setInterval(() => {}, 1000);

@Injectable()
class AppService {
getHello(): string {
return 'Hello World!';
}
}

@Controller()
class AppController {
constructor(private readonly appService: AppService) {}

@Get('test-exception/:id')
async testException(@Param('id') id: string): void {
Sentry.captureException(new Error(`error with id ${id}`));
}
}

@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
class AppModule {}

async function init(): Promise<void> {
const app = await NestFactory.create(AppModule);
Sentry.setupNestErrorHandler(app);
await app.listen(port);
sendPortToRunner(port);
}

// eslint-disable-next-line @typescript-eslint/no-floating-promises
init();
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { conditionalTest } from '../../../utils';
import { cleanupChildProcesses, createRunner } from '../../../utils/runner';

jest.setTimeout(20000);

const { TS_VERSION } = process.env;
const isOldTS = TS_VERSION && TS_VERSION.startsWith('3.');

// This is required to run the test with ts-node and decorators
process.env.TS_NODE_PROJECT = `${__dirname}/tsconfig.json`;

conditionalTest({ min: 16 })('nestjs auto instrumentation', () => {
afterAll(async () => {
cleanupChildProcesses();
});

test("should assign scope's transactionName if spans are not sampled", done => {
if (isOldTS) {
// Skipping test on old TypeScript
return done();
}

createRunner(__dirname, 'scenario.ts')
.expect({
event: {
exception: {
values: [
{
value: 'error with id 123',
},
],
},
transaction: 'GET /test-exception/:id',
},
})
.start(done)
.makeRequest('get', '/test-exception/123');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"include": ["scenario.ts"],
"compilerOptions": {
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "ES2021",
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck These are only tests
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable @typescript-eslint/explicit-member-accessibility */
import { loggingTransport, sendPortToRunner } from '@sentry-internal/node-integration-tests';
import * as Sentry from '@sentry/node';

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
release: '1.0',
tracesSampleRate: 1,
transport: loggingTransport,
integrations: integrations => integrations.filter(i => i.name !== 'Express'),
debug: true,
});

import { Controller, Get, Injectable, Module, Param } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

const port = 3470;

// Stop the process from exiting before the transaction is sent
// eslint-disable-next-line @typescript-eslint/no-empty-function
setInterval(() => {}, 1000);

@Injectable()
class AppService {
getHello(): string {
return 'Hello World!';
}
}

@Controller()
class AppController {
constructor(private readonly appService: AppService) {}

@Get('test-exception/:id')
async testException(@Param('id') id: string): void {
Sentry.captureException(new Error(`error with id ${id}`));
}
}

@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
class AppModule {}

async function init(): Promise<void> {
const app = await NestFactory.create(AppModule);
Sentry.setupNestErrorHandler(app);
await app.listen(port);
sendPortToRunner(port);
}

// eslint-disable-next-line @typescript-eslint/no-floating-promises
init();
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { conditionalTest } from '../../../utils';
import { cleanupChildProcesses, createRunner } from '../../../utils/runner';

jest.setTimeout(20000);

const { TS_VERSION } = process.env;
const isOldTS = TS_VERSION && TS_VERSION.startsWith('3.');

// This is required to run the test with ts-node and decorators
process.env.TS_NODE_PROJECT = `${__dirname}/tsconfig.json`;

conditionalTest({ min: 16 })('nestjs auto instrumentation', () => {
afterAll(async () => {
cleanupChildProcesses();
});

test("should assign scope's transactionName if express integration is disabled", done => {
if (isOldTS) {
// Skipping test on old TypeScript
return done();
}

createRunner(__dirname, 'scenario.ts')
.ignore('transaction')
.expect({
event: {
exception: {
values: [
{
value: 'error with id 456',
},
],
},
transaction: 'GET /test-exception/:id',
},
})
.start(done)
.makeRequest('get', '/test-exception/456');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"include": ["scenario.ts"],
"compilerOptions": {
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "ES2021",
}
}
Loading
Loading