How can I attach xray on typeorm in nodejs?

711 views Asked by At

I am using https://typeorm.io/#/ in my nodejs project to connect to Postgresql. My app is running in AWS lambda and I'd like to enable xray for performance analysis. With xray sdk, I can do something like below code:

var AWSXRay = require('aws-xray-sdk');
var pg = AWSXRay.capturePostgres(require('pg'));
var client = new pg.Client();

the above code will send query trace data to xray for instrumenting. However, I don't know how to make it work with typeorm since it hides the pg client from my code. Is there a way to capturePostgres inside typeorm?

3

There are 3 answers

0
sam loi On

I have a pretty smooth workaround using webpack (already have it in the project):

webpack.config.js

...
const bootstrapMysqlXray = new webpack.NormalModuleReplacementPlugin(/^mysql2$/, '/path/to/bootstrapMysql.ts');
...
plugins: [
        ...
        bootstrapMysqlXray
        ...
    ]

bootstrapMysql.ts

import { captureMySQL } from 'aws-xray-sdk';
import mysql from 'mysql';
// /!\ Do not import 'mysql2', it is replace by this module, creating a dependency loop
import mysql2 from '../../../node_modules/mysql2';

module.exports = captureMySQL(mysql2 as unknown as typeof mysql) as unknown as typeof mysql2;

I'm using TS, and mysql but it works in vanilla js and other dbs(replace imports by require)

I'm also applying this trick to inject xray on http call (using axios), and on aws-sdk

0
Ivan On

To make it work with TypeORM you need to wrap pg in AWSXRay.capturePostgres() and provide it to TypeORM as a driver in connection options:

import AWSXRay from "aws-xray-sdk"
import pg from "pg"
import { createConnection } from "typeorm"

await createConnection({
  driver: AWSXRay.capturePostgres(pg),
  // other options
})

Since TypeORM 0.3.0 you can use DataSource, so it will look like this:

import AWSXRay from "aws-xray-sdk"
import pg from "pg"
import { DataSource } from "typeorm"

const dataSource = new DataSource({
  driver: AWSXRay.capturePostgres(pg),
  // other options
})
0
Lei Wang On

If typeorm does not support be injected a Postgresql client from outside, Xray sdk would not work.