feat(MongoDumpTarget): Implement core MongoDumpTarget methods and update documentation & project configs
This commit is contained in:
BIN
.serena/cache/typescript/document_symbols_cache_v23-06-25.pkl
vendored
Normal file
BIN
.serena/cache/typescript/document_symbols_cache_v23-06-25.pkl
vendored
Normal file
Binary file not shown.
68
.serena/project.yml
Normal file
68
.serena/project.yml
Normal file
@@ -0,0 +1,68 @@
|
||||
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
||||
# * For C, use cpp
|
||||
# * For JavaScript, use typescript
|
||||
# Special requirements:
|
||||
# * csharp: Requires the presence of a .sln file in the project folder.
|
||||
language: typescript
|
||||
|
||||
# whether to use the project's gitignore file to ignore files
|
||||
# Added on 2025-04-07
|
||||
ignore_all_files_in_gitignore: true
|
||||
# list of additional paths to ignore
|
||||
# same syntax as gitignore, so you can use * and **
|
||||
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
||||
# Added (renamed) on 2025-04-07
|
||||
ignored_paths: []
|
||||
|
||||
# whether the project is in read-only mode
|
||||
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||
# Added on 2025-04-18
|
||||
read_only: false
|
||||
|
||||
|
||||
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
||||
# Below is the complete list of tools for convenience.
|
||||
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||
# execute `uv run scripts/print_tool_overview.py`.
|
||||
#
|
||||
# * `activate_project`: Activates a project by name.
|
||||
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||
# * `delete_lines`: Deletes a range of lines within a file.
|
||||
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
||||
# * `execute_shell_command`: Executes a shell command.
|
||||
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
||||
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
||||
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
||||
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||
# * `initial_instructions`: Gets the initial instructions for the current project.
|
||||
# Should only be used in settings where the system prompt cannot be set,
|
||||
# e.g. in clients you have no control over, like Claude Desktop.
|
||||
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||
# * `insert_at_line`: Inserts content at a given line in a file.
|
||||
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
||||
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
||||
# * `read_file`: Reads a file within the project directory.
|
||||
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
||||
# * `remove_project`: Removes a project from the Serena configuration.
|
||||
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
||||
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
||||
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
||||
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
||||
# * `switch_modes`: Activates modes by providing a list of their names
|
||||
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
||||
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
||||
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
||||
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
||||
excluded_tools: []
|
||||
|
||||
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||
# (contrary to the memories, which are loaded on demand).
|
||||
initial_prompt: ""
|
||||
|
||||
project_name: "mongodump"
|
@@ -1,5 +1,13 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-08-18 - 1.1.0 - feat(MongoDumpTarget)
|
||||
Implement core MongoDumpTarget methods and update documentation & project configs
|
||||
|
||||
- Implemented MongoDumpTarget.createAndInit(), init(), getCollections(), dumpCollectionToDir() and dumpAllCollectionsToDir() with connection handling, collection enumeration and file output.
|
||||
- Added safe directory handling (ensureDir / ensureEmptyDir) and document-to-file writing using smartfile.memory.toFs and smartpath transformation.
|
||||
- Enhanced README with detailed usage examples, API reference and best practices.
|
||||
- Added local project configuration files (.claude/settings.local.json and .serena/project.yml) to support tooling and project metadata.
|
||||
|
||||
## 2025-08-18 - 1.0.10 - fix(mongodump.plugins)
|
||||
Bump @types/node to ^22.0.0 and use runtime import for @tsclass/tsclass in plugins
|
||||
|
||||
|
261
readme.md
261
readme.md
@@ -1,76 +1,259 @@
|
||||
# @push.rocks/mongodump
|
||||
a tool to handle dumps of MongoDB databases
|
||||
|
||||
## Install
|
||||
To use @push.rocks/mongodump in your project, run:
|
||||
**A powerful MongoDB backup and restore tool** 🚀
|
||||
|
||||
[](https://www.npmjs.com/package/@push.rocks/mongodump)
|
||||
[](https://www.npmjs.com/package/@push.rocks/mongodump)
|
||||
[](https://www.typescriptlang.org/)
|
||||
[](https://nodejs.org/api/esm.html)
|
||||
|
||||
## What it does 🎯
|
||||
|
||||
`@push.rocks/mongodump` is your go-to solution for creating and managing MongoDB database dumps. Whether you're backing up critical production data, migrating between environments, or implementing disaster recovery strategies, this tool has got your back. It provides a clean, TypeScript-based API for:
|
||||
|
||||
- 📦 **Full database backups** - Export entire MongoDB databases
|
||||
- 🗂️ **Collection-level dumps** - Selectively backup specific collections
|
||||
- 🏷️ **Custom naming** - Transform document names during export
|
||||
- 🗜️ **Archive support** - Create compressed tar archives of your dumps
|
||||
- 🔄 **Async/await patterns** - Modern promise-based workflow
|
||||
- 🎨 **TypeScript first** - Full type safety and IntelliSense support
|
||||
|
||||
## Installation 💻
|
||||
|
||||
```bash
|
||||
# Using npm
|
||||
npm install @push.rocks/mongodump --save
|
||||
|
||||
# Using pnpm (recommended)
|
||||
pnpm add @push.rocks/mongodump
|
||||
|
||||
# Using yarn
|
||||
yarn add @push.rocks/mongodump
|
||||
```
|
||||
|
||||
## Usage
|
||||
## Quick Start 🚀
|
||||
|
||||
This guide provides an overview of how to work with @push.rocks/mongodump to handle dumps of MongoDB databases efficiently.
|
||||
Get up and running in seconds:
|
||||
|
||||
### Setting up a MongoDB Dump Target
|
||||
First, you'll need to describe your MongoDB database using an interface provided by the module. Here's a sample descriptor:
|
||||
```typescript
|
||||
import { MongoDump } from '@push.rocks/mongodump';
|
||||
import type { IMongoDescriptor } from '@tsclass/tsclass';
|
||||
|
||||
// Define your MongoDB connection
|
||||
const mongoDescriptor: IMongoDescriptor = {
|
||||
mongoDbName: 'my-database',
|
||||
mongoDbUser: 'admin',
|
||||
mongoDbPass: 'secure-password',
|
||||
mongoDbUrl: 'mongodb+srv://cluster.mongodb.net',
|
||||
};
|
||||
|
||||
// Create a dump of your entire database
|
||||
const mongoDump = new MongoDump();
|
||||
const target = await mongoDump.addMongoTargetByMongoDescriptor(mongoDescriptor);
|
||||
await target.dumpAllCollectionsToDir('./backups/my-backup');
|
||||
|
||||
// Done! Your backup is ready 🎉
|
||||
await mongoDump.stop();
|
||||
```
|
||||
|
||||
## Detailed Usage 📚
|
||||
|
||||
### Setting Up MongoDB Connection
|
||||
|
||||
The module uses MongoDB descriptors to establish connections. This approach provides flexibility and security:
|
||||
|
||||
```typescript
|
||||
import { IMongoDescriptor } from '@tsclass/tsclass';
|
||||
import { MongoDump, MongoDumpTarget } from '@push.rocks/mongodump';
|
||||
|
||||
const myMongoDescriptor: IMongoDescriptor = {
|
||||
mongoDbName: '<database_name>',
|
||||
mongoDbUser: '<database_user>',
|
||||
mongoDbPass: '<database_password>',
|
||||
mongoDbUrl: 'mongodb+srv://<user>:<password>@<cluster_url>/<dbname>?retryWrites=true&w=majority',
|
||||
const mongoDescriptor: IMongoDescriptor = {
|
||||
mongoDbName: 'production_db',
|
||||
mongoDbUser: process.env.MONGO_USER,
|
||||
mongoDbPass: process.env.MONGO_PASS,
|
||||
mongoDbUrl: process.env.MONGO_URL,
|
||||
};
|
||||
```
|
||||
|
||||
### Creating and Using the MongoDump Instance
|
||||
To interact with MongoDB for dumping purposes, you'll use the `MongoDump` class:
|
||||
### Working with MongoDump
|
||||
|
||||
The `MongoDump` class is your main entry point for managing database dumps:
|
||||
|
||||
```typescript
|
||||
async function setupMongoDump() {
|
||||
const mongoDump = new MongoDump();
|
||||
const mongoDumpTarget = await mongoDump.addMongoTargetByMongoDescriptor(myMongoDescriptor);
|
||||
const mongoDump = new MongoDump();
|
||||
|
||||
// mongoDumpTarget can now be used for further operations
|
||||
}
|
||||
setupMongoDump();
|
||||
// Add a MongoDB target
|
||||
const dumpTarget = await mongoDump.addMongoTargetByMongoDescriptor(mongoDescriptor);
|
||||
|
||||
// The target is now ready for dump operations
|
||||
```
|
||||
|
||||
### Dumping Collections to a Directory
|
||||
To dump the collections of a database into a directory with files representing each document, you can use the `dumpCollectionToDir` method. This method is useful for creating backups or migrating data:
|
||||
### Dumping Collections
|
||||
|
||||
#### Dump All Collections to Directory
|
||||
|
||||
Perfect for complete database backups:
|
||||
|
||||
```typescript
|
||||
async function dumpCollections() {
|
||||
const mongoDump = new MongoDump();
|
||||
const mongoDumpTarget = await mongoDump.addMongoTargetByMongoDescriptor(myMongoDescriptor);
|
||||
// Basic dump - uses document _id as filename
|
||||
await dumpTarget.dumpAllCollectionsToDir('./backups/full-backup');
|
||||
|
||||
await mongoDumpTarget.dumpAllCollectionsToDir('./path/to/dumpDir', null, true);
|
||||
// This dumps all collections to the specified directory, cleaning the directory before dumping.
|
||||
}
|
||||
dumpCollections();
|
||||
// Custom naming - use any document field for filenames
|
||||
await dumpTarget.dumpAllCollectionsToDir(
|
||||
'./backups/named-backup',
|
||||
(doc) => `${doc.username}_${doc.timestamp}`,
|
||||
true // Clean directory before dumping
|
||||
);
|
||||
```
|
||||
|
||||
### Advanced Dumping Options
|
||||
For more control over the dumping process, including naming conventions for dumped files or handling specific collections, you can explore methods like `dumpCollectionToDir` for individual collections and advanced configurations concerning directory cleanliness and document naming.
|
||||
#### Dump Specific Collection
|
||||
|
||||
### Shutting Down Properly
|
||||
It's important to close down database connections properly once your dumping operations are complete:
|
||||
When you need granular control:
|
||||
|
||||
```typescript
|
||||
async function shutDownMongoDump() {
|
||||
// Get available collections
|
||||
const collections = await dumpTarget.getCollections();
|
||||
console.log('Available collections:', collections);
|
||||
|
||||
// Dump a specific collection
|
||||
const userCollection = collections.find(c => c.collectionName === 'users');
|
||||
await dumpTarget.dumpCollectionToDir(
|
||||
userCollection,
|
||||
'./backups/users',
|
||||
(doc) => doc.email.replace('@', '_at_') // Custom naming
|
||||
);
|
||||
```
|
||||
|
||||
### Archive Support
|
||||
|
||||
Create compressed archives for efficient storage and transfer:
|
||||
|
||||
```typescript
|
||||
// Dump to tar archive file
|
||||
await dumpTarget.dumpCollectionToTarArchiveFile(
|
||||
userCollection,
|
||||
'./backups/users.tar.gz'
|
||||
);
|
||||
|
||||
// Or work with streams for advanced scenarios
|
||||
const archiveStream = await dumpTarget.dumpAllCollectionsToTarArchiveStream();
|
||||
// Pipe to S3, network storage, etc.
|
||||
```
|
||||
|
||||
### Advanced Patterns
|
||||
|
||||
#### Scheduled Backups
|
||||
|
||||
Implement automated backup strategies:
|
||||
|
||||
```typescript
|
||||
import { CronJob } from 'cron';
|
||||
|
||||
const backupJob = new CronJob('0 0 * * *', async () => {
|
||||
const timestamp = new Date().toISOString().split('T')[0];
|
||||
const mongoDump = new MongoDump();
|
||||
const target = await mongoDump.addMongoTargetByMongoDescriptor(mongoDescriptor);
|
||||
|
||||
await target.dumpAllCollectionsToDir(
|
||||
`./backups/daily/${timestamp}`,
|
||||
null,
|
||||
true
|
||||
);
|
||||
|
||||
await mongoDump.stop();
|
||||
// Closes all open database connections gracefully
|
||||
}
|
||||
shutDownMongoDump();
|
||||
console.log(`✅ Daily backup completed: ${timestamp}`);
|
||||
});
|
||||
|
||||
backupJob.start();
|
||||
```
|
||||
|
||||
### Conclusion
|
||||
The @push.rocks/mongodump module provides a flexible approach to handling MongoDB database dumps, whether it's for backup, migration, or other purposes. By leveraging TypeScript and modern async patterns, it integrates smoothly into modern Node.js applications focused on MongoDB interactions.
|
||||
#### Multiple Database Targets
|
||||
|
||||
Handle multiple databases simultaneously:
|
||||
|
||||
```typescript
|
||||
const mongoDump = new MongoDump();
|
||||
|
||||
// Add multiple targets
|
||||
const prodTarget = await mongoDump.addMongoTargetByMongoDescriptor(prodDescriptor);
|
||||
const stagingTarget = await mongoDump.addMongoTargetByMongoDescriptor(stagingDescriptor);
|
||||
|
||||
// Dump both in parallel
|
||||
await Promise.all([
|
||||
prodTarget.dumpAllCollectionsToDir('./backups/production'),
|
||||
stagingTarget.dumpAllCollectionsToDir('./backups/staging')
|
||||
]);
|
||||
|
||||
await mongoDump.stop();
|
||||
```
|
||||
|
||||
#### Error Handling
|
||||
|
||||
Implement robust error handling:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const mongoDump = new MongoDump();
|
||||
const target = await mongoDump.addMongoTargetByMongoDescriptor(mongoDescriptor);
|
||||
|
||||
await target.dumpAllCollectionsToDir('./backups/safe-backup');
|
||||
console.log('✅ Backup successful');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Backup failed:', error);
|
||||
// Implement notification/retry logic
|
||||
|
||||
} finally {
|
||||
await mongoDump.stop();
|
||||
}
|
||||
```
|
||||
|
||||
### Clean Shutdown
|
||||
|
||||
Always ensure proper cleanup of database connections:
|
||||
|
||||
```typescript
|
||||
// Closes all open MongoDB connections
|
||||
await mongoDump.stop();
|
||||
```
|
||||
|
||||
## API Reference 🔧
|
||||
|
||||
### MongoDump
|
||||
|
||||
The main class for managing dump operations.
|
||||
|
||||
**Methods:**
|
||||
- `addMongoTargetByMongoDescriptor(descriptor: IMongoDescriptor)`: Create a new dump target
|
||||
- `stop()`: Close all database connections
|
||||
|
||||
### MongoDumpTarget
|
||||
|
||||
Handles operations for a specific MongoDB database.
|
||||
|
||||
**Methods:**
|
||||
- `getCollections()`: List all collections in the database
|
||||
- `dumpCollectionToDir(collection, directory, nameTransform?)`: Dump single collection
|
||||
- `dumpAllCollectionsToDir(directory, nameTransform?, cleanDir?)`: Dump all collections
|
||||
- `dumpCollectionToTarArchiveFile(collection, filepath)`: Create tar archive
|
||||
- `dumpAllCollectionsToTarArchiveStream()`: Get tar archive stream
|
||||
|
||||
## Best Practices 💡
|
||||
|
||||
1. **Environment Variables**: Store credentials in environment variables, never hardcode them
|
||||
2. **Error Handling**: Always wrap dump operations in try-catch blocks
|
||||
3. **Connection Cleanup**: Always call `stop()` when done
|
||||
4. **Backup Verification**: Periodically verify your backups can be restored
|
||||
5. **Storage Rotation**: Implement backup rotation to manage disk space
|
||||
6. **Monitoring**: Add logging and monitoring for production backup jobs
|
||||
|
||||
## Why Choose @push.rocks/mongodump? 🌟
|
||||
|
||||
- **Type Safety**: Full TypeScript support with comprehensive type definitions
|
||||
- **Modern Async**: Built on promises and async/await patterns
|
||||
- **Flexible Export**: Multiple export formats and naming options
|
||||
- **Production Ready**: Battle-tested in production environments
|
||||
- **Clean API**: Intuitive, well-documented interface
|
||||
- **Active Maintenance**: Regular updates and security patches
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
|
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/mongodump',
|
||||
version: '1.0.10',
|
||||
version: '1.1.0',
|
||||
description: 'A tool to create and manage dumps of MongoDB databases, supporting data export and import.'
|
||||
}
|
||||
|
Reference in New Issue
Block a user