47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
import { cassandra as config } from "@config/environment";
|
|
import { logger } from "@creations.works/logger";
|
|
import { Client, auth } from "cassandra-driver";
|
|
|
|
class CassandraService {
|
|
private static instance: Client | null = null;
|
|
|
|
private constructor() {}
|
|
|
|
public static getClient(): Client {
|
|
if (!CassandraService.instance) {
|
|
CassandraService.instance = new Client({
|
|
contactPoints: config.contactPoints,
|
|
localDataCenter: config.datacenter,
|
|
keyspace: config.keyspace,
|
|
authProvider: config.authEnabled
|
|
? new auth.PlainTextAuthProvider(config.username, config.password)
|
|
: undefined,
|
|
protocolOptions: {
|
|
port: config.port,
|
|
},
|
|
});
|
|
}
|
|
|
|
return CassandraService.instance;
|
|
}
|
|
|
|
public static async connect(): Promise<void> {
|
|
try {
|
|
await CassandraService.getClient().connect();
|
|
logger.info("Connected to Cassandra successfully.");
|
|
} catch (error) {
|
|
logger.error(["Failed to connect to Cassandra:", error as Error]);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
public static async shutdown(): Promise<void> {
|
|
if (CassandraService.instance) {
|
|
await CassandraService.instance.shutdown();
|
|
logger.info("Cassandra client shut down.");
|
|
CassandraService.instance = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
export { CassandraService };
|