Data Access Documentation

Welcome to the MSDN Data Access documentation. This section provides comprehensive information on how to interact with various data sources, manage data operations, and implement efficient data handling strategies within your applications.

Overview of Data Access

Effective data management is crucial for building robust and scalable applications. MSDN provides a rich set of APIs and tools to simplify the process of connecting to, querying, and manipulating data. We support a wide range of data storage solutions, from local databases to cloud-based services.

Key Features:

Getting Started with Data Access

To begin using the data access features, you first need to set up your database connection. This typically involves configuring connection strings and defining your data models.

1. Installing Data Access Packages

Use our package manager to install the necessary libraries:


npm install @msdn/data-access
# or
yarn add @msdn/data-access
            

2. Configuring a Connection

Here's a simple example of how to configure a connection to a PostgreSQL database:


import { DatabaseConnection } from '@msdn/data-access';

const connection = new DatabaseConnection({
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'myuser',
    password: 'mypassword',
    database: 'mydatabase'
});

connection.connect()
    .then(() => console.log('Database connected successfully!'))
    .catch(err => console.error('Database connection error:', err));
            

Note: Always store sensitive credentials securely and avoid hardcoding them directly in your application code.

Working with Data Models

Define your data structures using classes or interfaces. MSDN's ORM can automatically map these models to your database tables.

Example: User Model


import { Model, PrimaryKey, AutoIncrement, Column } from '@msdn/data-access';

@Model('users')
export class User {
    @PrimaryKey()
    @AutoIncrement()
    id: number;

    @Column({ type: 'VARCHAR(100)', nullable: false })
    username: string;

    @Column({ type: 'VARCHAR(255)', nullable: true })
    email?: string;

    @Column({ type: 'TIMESTAMP', default: 'CURRENT_TIMESTAMP' })
    createdAt: Date;
}
            

Querying Data

MSDN provides a fluent query builder that makes it easy to construct complex queries.

Fetching All Users:


// Assuming 'connection' is an instance of DatabaseConnection
const userRepository = connection.getRepository(User);

userRepository.findAll()
    .then(users => {
        console.log('All users:', users);
    })
    .catch(err => console.error('Error fetching users:', err));
            

Fetching Users by Condition:


userRepository.find({
    where: { username: 'john_doe' }
})
    .then(users => {
        console.log('User found:', users);
    })
    .catch(err => console.error('Error finding user:', err));
            

Tip: Explore the advanced querying options, including joins, aggregations, and custom SQL execution, in the full API reference.

Performing Data Operations

Create, update, and delete records using simple methods.

Creating a New User:


const newUser = userRepository.create({
    username: 'jane_doe',
    email: 'jane.doe@example.com'
});

userRepository.save(newUser)
    .then(savedUser => {
        console.log('User created:', savedUser);
    })
    .catch(err => console.error('Error creating user:', err));
            

Updating a User:


userRepository.update(1, { email: 'john.doe.updated@example.com' })
    .then(updateResult => {
        console.log('Update successful:', updateResult);
    })
    .catch(err => console.error('Error updating user:', err));
            

Deleting a User:


userRepository.delete(1)
    .then(deleteResult => {
        console.log('User deleted:', deleteResult);
    })
    .catch(err => console.error('Error deleting user:', err));
            

Asynchronous Data Handling

All data access operations are inherently asynchronous. You can use Promises, async/await, or event emitters to manage them.

Using async/await:


async function getUserById(userId: number): Promise<User | null> {
    try {
        const user = await userRepository.findOne({ where: { id: userId } });
        return user;
    } catch (error) {
        console.error(`Error fetching user with ID ${userId}:`, error);
        return null;
    }
}

(async () => {
    const user = await getUserById(2);
    if (user) {
        console.log('Found user:', user);
    }
})();