Getting Started with @inceptools/db
Learn how to install and set up @inceptools/db in your project.
Installation
Install @inceptools/db using your preferred package manager:
npm install @inceptools/db
Basic Usage
Here's a simple example of how to use @inceptools/db with MongoDB:
import { MongoService, SUPPORTED_DBS } from "@inceptools/db";
import mongoose from "mongoose";
// Define your MongoDB schemas
const schemas = {
users: new mongoose.Schema({
name: String,
email: String,
createdAt: { type: Date, default: Date.now },
}),
};
// Create a MongoDB service instance
const mongoService = new MongoService({
type: SUPPORTED_DBS.MONGO_DB,
connectionString: "mongodb://localhost:27017/myapp",
models: schemas,
});
// Connect to MongoDB
await mongoService.connect();
// Use your models
const newUser = await mongoService.users.create({
name: "John Doe",
email: "[email protected]",
});
// Close the connection when done
await mongoService.closeConnection();
Multiple Database Types
@inceptools/db allows you to connect to multiple database types simultaneously:
import { DBService, SUPPORTED_DBS } from "@inceptools/db";
import mongoose from "mongoose";
import { Sequelize, DataTypes } from "sequelize";
// Define your database schemas/models
const db = {
mongodb: {
users: new mongoose.Schema({
name: String,
email: String,
}),
},
postgres: {
contacts: (sequelize: Sequelize) => {
return sequelize.define("Contact", {
name: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
});
},
},
};
// Configure your database connections
const config = {
mongodb: {
type: SUPPORTED_DBS.MONGO_DB,
connectionString: "mongodb://localhost:27017/myapp",
models: db.mongodb,
},
postgres: {
type: SUPPORTED_DBS.SQL,
connectionString: "postgresql://user:password@localhost:5432/myapp",
models: db.postgres,
configOptions: {
dialect: "postgres",
},
},
redis: {
type: SUPPORTED_DBS.REDIS,
connectionString: "redis://localhost:6379",
},
};
// Create a database service instance
const dbService = new DBService(config);
// Connect to all databases
await dbService.connect();
// Use your database models
const users = await dbService.mongodb.users.find();
const contacts = await dbService.postgres.contacts.findAll();
await dbService.redis.set("key", "value");
// Close all connections when done
await dbService.closeConnection();
Next Steps
Now that you've learned the basics, explore more detailed documentation for each database type: