I'm trying to insert the data from Bitfinex api into table rows of my database. I use node with typescript and mssql to execute the data service. Sometimes it works and I see the data is inserted, but sometimes the console log shows
"connection error: connection is not opened yet"
I don't even know why and where the root cause is.
Below is my code:
app-data-service.ts
import * as mssql from 'mssql';
import { AppConfig } from '../config';
import { LendbookService, UsersService, MockUsersService } from './data-services';
import { MOCK_USERS } from './mock-data';
import { Logger, LoggerFactory } from '../common';
export class AppDataServices {
private static readonly LOGGER: Logger = LoggerFactory.getLogger();
private db: any;
public usersService: UsersService;
public lendbookService: LendbookService;
constructor(private appConfig: AppConfig) {
this.initConnectionPool();
this.usersService = new MockUsersService(MOCK_USERS);
this.lendbookService = new LendbookService(this.db, AppDataServices.LOGGER);
}
private initConnectionPool() {
this.db = new mssql.ConnectionPool({
user: this.appConfig.mssqlUsername,
password: this.appConfig.mssqlPassword,
server: this.appConfig.mssqlServer,
database: this.appConfig.mssqlDatabase,
// If you are on Microsoft Azure, you need this:
options: { encrypt: true }
}, (err: any) => {
if (err) AppDataServices.LOGGER.error('MSSQL error', err);
});
}
}
lendbook-service.ts
import * as mssql from 'mssql';
import { Lendbook } from '../../models';
import { Logger, LoggerFactory } from '../../../common';
export class LendbookService {
private static readonly LOGGER: Logger = LoggerFactory.getLogger();
constructor(private db: any, private logger: any) {}
insert(row: object): any {
const sql = "INSERT INTO dbo.lendbook (rate, amount, period, timestamp, type, frr) VALUES (@rate, @amount, @period, @timestamp, @type, @frr)";
const ps = new mssql.PreparedStatement(this.db);
ps.input('rate', mssql.Decimal);
ps.input('amount', mssql.Decimal);
ps.input('period', mssql.Int);
ps.input('timestamp', mssql.DateTime);
ps.input('type', mssql.NVarChar);
ps.input('frr', mssql.NVarChar);
ps.prepare(sql, (err: any) => {
if (err) {
LendbookService.LOGGER.error('MSSQL prepare error', err);
}
else {
ps.execute(row, (err: any) => {
if (err) {
LendbookService.LOGGER.error('MSSQL execute error', err);
}
ps.unprepare((err: any) => {
if (err) {
LendbookService.LOGGER.error('MSSQL unprepare error', err);
}
});
});
}
});
return ps;
}
}
Versions: node: 6.9.1, mssql: 4.0.4