![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
@mcereal/nestjsdb2
Advanced tools
The @mcereal/nestjs
package is a powerful and flexible TypeScript library that integrates IBM DB2 database capabilities into NestJS applications. This package provides decorators, services, and utility functions to handle common database operations, connection management, caching, error handling, and transaction management, specifically tailored for IBM DB2 environments.
This package it under active development and is not yet ready for production use. Please use with caution and report any issues or bugs you encounter.
beginTransaction
, commitTransaction
, and rollbackTransaction
.npm install @mcereal/nestjsdb2 --save
Note: The @mcereal/nestjsdb2
package relies on the ibm_db package, which requires Rosetta 2 to run on Apple Silicon Macs. Please ensure Rosetta 2 is installed on your system. You can install Rosetta 2 by running:
softwareupdate --install-rosetta --agree-to-license
To get started, import the Db2Module into your NestJS application and configure it using the provided options.
import { Module } from '@nestjs/common';
import { Db2Module } from '@mcereal/nestjsdb2';
@Module({
imports: [
Db2Module.forRoot({
auth: {
authType: 'password',
username: 'db2user',
password: 'password',
},
host: 'localhost',
port: 50000,
database: 'sampledb',
useTls: false,
retry: {
maxReconnectAttempts: 5,
reconnectInterval: 3000,
},
queryTimeout: 10000, // in milliseconds
}),
],
})
export class AppModule {}
The Db2Module can be configured either synchronously or asynchronously:
import { Module } from '@nestjs/common';
import { Db2Module } from '@mcereal/nestjsdb2';
@Module({
imports: [
Db2Module.forRoot({
auth: {
authType: 'password',
username: 'db2user',
password: 'password',
},
host: 'localhost',
port: 50000,
database: 'sampledb',
useTls: false,
cacheEnabled: true,
retry: {
maxReconnectAttempts: 5,
reconnectInterval: 3000,
},
queryTimeout: 10000,
}),
],
})
export class AppModule {}
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Db2Module } from '@mcereal/nestjsdb2';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
Db2Module.forRootAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
auth: {
authType: 'password',
username: configService.get<string>('DB_USER'),
password: configService.get<string>('DB_PASS'),
},
host: configService.get<string>('DB_HOST'),
port: configService.get<number>('DB_PORT'),
useTls: configService.get<boolean>('DB2_SSL_CONNECTION'),
database: configService.get<string>('DB_NAME'),
sslCertificatePath: configService.get<string>('DB_SSL_CERT_PATH'),
retry: {
maxReconnectAttempts: configService.get<number>('DB_RETRY_MAX') || 5,
reconnectInterval:
configService.get<number>('DB_RETRY_INTERVAL') || 3000,
},
queryTimeout: configService.get<number>('DB_QUERY_TIMEOUT') || 10000,
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}
Ensure that the Db2Module is imported and configured in your root module (AppModule).
import { Module } from '@nestjs/common';
import { Db2Module } from '@mcereal/nestjsdb2';
@Module({
imports: [
Db2Module.forRoot({
auth: {
authType: 'password',
username: 'db2user',
password: 'password',
},
host: 'localhost',
port: 50000,
database: 'sampledb',
useTls: false,
cacheEnabled: true,
}),
],
})
export class AppModule {}
The query
method executes a SQL query and returns the result as an array of objects:
const result = await this.db2Service.query('SELECT * FROM users');
The batch
method executes multiple queries in a single batch operation:
const queries = [
{ sql: 'INSERT INTO users (name) VALUES (?)', params: ['Alice
{ sql: 'INSERT INTO users (name) VALUES (?)', params: ['Bob'] },
];
const results = await this.db2Service.batch(queries);
The beginTransaction
, commitTransaction
, and rollbackTransaction
methods provide support for transactions:
await this.db2Service.beginTransaction();
await this.db2Service.query('INSERT INTO users (name) VALUES (?)', ['Alice']);
await this.db2Service.commitTransaction();
The QueryBuilder
class provides a fluent API for building SQL queries with support for subqueries, parameterized queries, and more.
Create a new Query builder by providing the table name and an instance of th Db2Client class.
import { QueryBuilder } from '@mcereal/nestjsdb2';
const queryBuilder = new QueryBuilder('users', this.db2Service);
const result = await queryBuilder
.select(['id', 'name'])
.where('name', '=', 'Alice')
.orderBy('created_at', 'DESC')
.limit(10)
.execute();
console.log(result);
The @Transaction
, @Connection
, and `` decorators can be used to enforce connection state checks and cache results:
import { Transaction, Connection, Query, Param } from '@mcereal/nestjsdb2';
@Injectable()
export class UserService {
@Transaction()
async createUser(name: string) {
await this.db2Service.query('INSERT INTO users (name) VALUES (?)', [name]);
}
@Connection()
async getUserData(userId: string) {
return this.db2Service.query('SELECT * FROM users WHERE id = ?', [userId]);
}
@Query('SELECT * FROM users WHERE id = ?')
async getUserData(@Param('id') userId: string) {
return this.db2Service.query('SELECT * FROM users WHERE id = ?', [userId]);
}
The @mcereal/nestjsdb2
package provides a lightweight ORM-like inrerface for working with DB2. You can define schemas using the Schema
class and model classes using the Model
class.
@Entity
decorator, and define the schema using the Schema
class:import { Schema, Model } from '@mcereal/nestjsdb2';
import { Entity, Column, PrimaryKey } from '@mcereal/nestjsdb2';
@Entity({
entityType: 'table',
name: 'users',
})
export class User {
@PrimaryKey()
id!: string;
@Column()
name!: string;
@Column()
email!: string;
}
export const UserSchema = new Schema([User]);
const UserModel = new Model('users', UserSchema);
Schema
and Model
classes in the module configuration as providers:Db2Module.forRoot({
auth: {
authType: 'password',
host: 'localhost',
port: 50000,
database: 'sampledb',
useTls: false,
},
providers: [
{
provide: 'UserModel',
useValue: UserModel,
},
],
});
Db2Module.forFeature
to register the Schema
and Model
classes in a feature module:
@Module({
imports: [
Db2Module.forFeature({
auth: {
authType: 'password',
host: 'localhost',
port: 50000,
database: 'sampledb',
useTls: false,
},
providers: [
{
provide: 'UserModel',
useValue: UserModel,
},
],
}),
],
})
UserModel
class to perform CRUD operations on the users
table:import { Injectable, Inject } from '@nestjs/common';
@Injectable()
export class UserService {
constructor(@Inject('UserModel') private userModel: Model<UserModel>) {}
async createUser(name: string, email: string) {
return this.userModel.insert({ name, email });
}
async getUserById(id: string) {
return this.userModel.findOne({ id });
}
async updateUser(id: string, name: string, email: string) {
return this.userModel.update({ id }, { name, email });
}
async deleteUser(id: string) {
return this.userModel.delete({ id });
}
}
The @mcereal/nestjsdb2
package provides detailed error messages and stack traces for common database errors. You can import multiple error types like Db2Error
, Db2ConnectionError
, Db2QueryError
, and Db2TransactionError
to handle specific error scenarios:
import {
Db2Error,
Db2ConnectionError,
Db2QueryError,
Db2TransactionError,
} from '@mcereal/nestjsdb2';
try {
await this.db2Service.query('SELECT * FROM non_existent_table');
} catch (error) {
if (error instanceof Db2QueryError) {
console.error('Query error:', error.message);
} else if (error instanceof Db2ConnectionError) {
console.error('Connection error:', error.message);
} else if (error instanceof Db2TransactionError) {
console.error('Transaction error:', error.message);
} else if (error instanceof Db2Error) {
console.error('DB2 error:', error.message);
} else {
console.error('Unknown error:', error.message);
}
}
You can implement health checks for your NestJS application using the TerminusModule
and the Db2HealthIndicator
:
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { Db2HealthIndicator } from '@mcereal/nestjsdb2';
@Module({
imports: [
TerminusModule.forRoot({
healthChecks: {
db2: () => Db2HealthIndicator.pingCheck('db2'),
},
}),
],
})
export class HealthModule {}
You can find examples of how to use the @mcereal/nestjsdb2
package in the examples directory. This directory contains sample applications that demonstrate various features of the package, including basic query execution, batch operations, transaction management, and ORM support. To run the examples, follow the instructions in the examples/README.md file.
The @mcereal/nestjsdb2
package follows best practices for security, including:
Contributions are welcome! Please read our contributing guidelines to get started.
This project is licensed under the terms of the MIT License.
FAQs
NestJS module for interacting with IBM DB2 databases
We found that @mcereal/nestjsdb2 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.