@mich4l/nestjs-cassandra
v1.0.2
Published
Cassandra Nest.js connector module
Downloads
591
Maintainers
Readme
Nest.js Cassandra module
Cassandra module based on npm library cassandra-driver
.
Features:
- Simple codebase
- Graceful shutdown
- Multiple connections
- Simple lifecycle hooks (
onReady
,beforeShutdown
)
Installation
npm
npm install @mich4l/nestjs-cassandra cassandra-driver
Yarn
yarn add @mich4l/nestjs-cassandra cassandra-driver
Examples
app.module.ts
import { Module } from '@nestjs/common';
import { CassandraModule } from 'mich4l/nestjs-cassandra';
@Module({
imports: [
CassandraModule.forRoot({
keyspace: 'my_keyspace',
contactPoints: ['127.0.0.1'],
localDataCenter: 'datacenter1',
}),
controllers: [],
providers: [],
})
export class AppModule {}
example.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { InjectCassandra } from '@mich4l/nestjs-cassandra';
import { Client } from 'cassandra-driver';
@Injectable()
export class ExampleService {
constructor(
@InjectCassandra()
private readonly dbClient: Client,
) {}
async getAllPosts() {
const query = 'SELECT * FROM posts';
const result = await this.dbClient.execute(query);
return result.rows[0];
}
}
Async register example
@Module({
imports: [
ConfigModule.forRoot({
cache: true,
}),
CassandraModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (config: ConfigService) => {
return {
keyspace: config.get('CASSANDRA_KEYSPACE'),
localDataCenter: config.get('CASSANDRA_DATACENTER'),
contactPoints: ['127.0.0.1'],
}
}
})
],
controllers: [],
providers: [],
})
export class AppModule {}
Graceful shutdown
Module closes connection using onApplicationShutdown
hook. You may need:
main.ts
...
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
});
app.enableShutdownHooks();
await app.listen(3000);
}
bootstrap();