feat(documentation): Enhance project metadata and documentation with comprehensive usage examples, updated descriptions, and improved keywords.

This commit is contained in:
Philipp Kunz 2025-04-09 06:26:52 +00:00
parent 25147deb7f
commit b768b67641
5 changed files with 607 additions and 168 deletions

View File

@ -1,5 +1,13 @@
# Changelog # Changelog
## 2025-04-09 - 1.5.0 - feat(documentation)
Enhance project metadata and documentation with comprehensive usage examples, updated descriptions, and improved keywords.
- Updated npmextra.json and package.json to refine the project description and keyword list.
- Expanded readme.md with detailed sections on environment setup, CRUD operations, bulk JSONL processing, and advanced Handelsregister integrations.
- Included advanced workflow examples and error handling strategies in the documentation.
- Adjusted test cases (e.g. in test/test.handelsregister.ts) to reflect changes in company name usage.
## 2025-04-08 - 1.4.6 - fix(tests & jsonl) ## 2025-04-08 - 1.4.6 - fix(tests & jsonl)
Improve test structure and refine JSONL parsing for incomplete data Improve test structure and refine JSONL parsing for incomplete data

View File

@ -5,25 +5,26 @@
"githost": "gitlab.com", "githost": "gitlab.com",
"gitscope": "fin.cx", "gitscope": "fin.cx",
"gitrepo": "opendata", "gitrepo": "opendata",
"description": "A TypeScript library for accessing, managing, and updating open business data, focused on German companies and integrating with MongoDB.", "description": "A comprehensive TypeScript library that manages open business data for German companies by integrating MongoDB, processing JSONL bulk data, and automating browser interactions for Handelsregister data retrieval.",
"npmPackagename": "@fin.cx/opendata", "npmPackagename": "@fin.cx/opendata",
"license": "MIT", "license": "MIT",
"projectDomain": "fin.cx", "projectDomain": "fin.cx",
"keywords": [ "keywords": [
"TypeScript", "TypeScript",
"open data", "open data",
"business data",
"German companies", "German companies",
"data management", "business data",
"business registry",
"npm package",
"MongoDB", "MongoDB",
"JSONL",
"bulk processing",
"data management",
"automation", "automation",
"data integration", "browser automation",
"database", "Handelsregister",
"data processing", "web scraping",
"data retrieval", "file processing",
"data update" "business registry",
"data retrieval"
] ]
} }
}, },

View File

@ -2,7 +2,7 @@
"name": "@fin.cx/opendata", "name": "@fin.cx/opendata",
"version": "1.4.6", "version": "1.4.6",
"private": false, "private": false,
"description": "A TypeScript library for accessing, managing, and updating open business data, focused on German companies and integrating with MongoDB.", "description": "A comprehensive TypeScript library that manages open business data for German companies by integrating MongoDB, processing JSONL bulk data, and automating browser interactions for Handelsregister data retrieval.",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"type": "module", "type": "module",
@ -64,18 +64,19 @@
"keywords": [ "keywords": [
"TypeScript", "TypeScript",
"open data", "open data",
"business data",
"German companies", "German companies",
"data management", "business data",
"business registry",
"npm package",
"MongoDB", "MongoDB",
"JSONL",
"bulk processing",
"data management",
"automation", "automation",
"data integration", "browser automation",
"database", "Handelsregister",
"data processing", "web scraping",
"data retrieval", "file processing",
"data update" "business registry",
"data retrieval"
], ],
"packageManager": "pnpm@10.7.0+sha512.6b865ad4b62a1d9842b61d674a393903b871d9244954f652b8842c2b553c72176b278f64c463e52d40fff8aba385c235c8c9ecf5cc7de4fd78b8bb6d49633ab6" "packageManager": "pnpm@10.7.0+sha512.6b865ad4b62a1d9842b61d674a393903b871d9244954f652b8842c2b553c72176b278f64c463e52d40fff8aba385c235c8c9ecf5cc7de4fd78b8bb6d49633ab6"
} }

685
readme.md
View File

@ -1,220 +1,649 @@
# @fin.cx/opendata # @fin.cx/opendata
A TypeScript library for accessing, managing, and updating open business data, focused on German companies and integrating with MongoDB.
A TypeScript-based library for accessing and managing open business data, specifically for German companies.
## Install ## Install
To install the `@fin.cx/opendata` package, you can use npm or yarn as your package manager. Here's how you can do it: To install the @fin.cx/opendata package, you can use npm or yarn as your package manager. The installation process is simple and straightforward.
Using npm: Using npm:
```bash npm install @fin.cx/opendata
npm install @fin.cx/opendata
```
Using yarn: Using yarn:
```bash yarn add @fin.cx/opendata
yarn add @fin.cx/opendata
```
## Usage ## Usage
The `@fin.cx/opendata` package provides a comprehensive set of functionalities for handling open business data, focusing on German business data. Let's explore the detailed capabilities of this library through extensive examples and instructions. The @fin.cx/opendata library is a versatile tool that empowers developers to integrate comprehensive open business data into their systems. This library is particularly tailored for German companies, offering functionalities that include creating, retrieving, updating, and deleting business records as well as processing large volumes of JSONL data from external sources. In addition to core database operations via MongoDB, the library provides integration with web-based services, primarily through a hands-on Handelsregister processor that utilizes browser automation for searching and downloading documents.
### Setting Up the Environment In this section, we will extensively detail multiple usage scenarios, ensuring that every feature the module offers is thoroughly explored. All examples in this documentation employ ECMAScript Module (ESM) syntax and TypeScript, highlighting proper asynchronous handling, error management, and advanced integration with other dependencies. We will walk you through environment setup, initializing the package, managing business records, processing bulk JSONL data, interacting with the Handelsregister for on-demand document retrieval, and much more. Each example is constructed to expose every nuance of the module's behavior and usage.
First, make sure you've set up the necessary environment variables for MongoDB. You will need the following environment variables: For clarity, we will split this section into multiple parts:
- `MONGODB_URL`: The URL for your MongoDB instance.
- `MONGODB_NAME`: The name of the database to use.
- `MONGODB_USER`: A valid username for accessing the database.
- `MONGODB_PASS`: The password associated with the MongoDB user.
These variables can be configured in a `.env` file or managed through a specific service used for secure environment variables handling. 1. Environment Setup and Initializing the Library
2. Managing Business Records (CRUD Operations)
3. Bulk Data Processing and Importing via JSONL Streams
4. Integrating with the Handelsregister: Detailed Demonstrations
5. Advanced Examples: Combined Operations and Edge Cases
6. Error Handling and Data Validation
7. Testing and Automated Workflows
### Importing and Initializing the Library Throughout these examples, we will examine how each class and method interacts with the underlying MongoDB database and the system's file structure. We assume you have a running MongoDB instance and that your environment is configured with the necessary variables.
To start working with the library, import the necessary classes and initialize the `OpenData` class. ────────────────────────────────────────────
### 1. Environment Setup and Initializing the Library
Before diving into any operations, ensure that your development environment is properly configured. The @fin.cx/opendata library mandates several environment variables for connecting to your MongoDB instance. For a smooth experience, it is advisable to use a .env file or any secure secrets management tool that suits your workflow. The required environment variables include:
• MONGODB_URL The connection string URL for your MongoDB instance.
• MONGODB_NAME The name of the database that the module will interact with.
• MONGODB_USER MongoDB username required for authentication.
• MONGODB_PASS The password for the MongoDB user.
Below is an example .env file for local development:
------------------------------------------------------------
MONGODB_URL=mongodb://localhost:27017
MONGODB_NAME=opendataDB
MONGODB_USER=myUser
MONGODB_PASS=myPass
------------------------------------------------------------
Once these variables are set, the library can fetch them using the integrated qenv tool. The following code snippet demonstrates how to import and initialize the library:
```typescript ```typescript
import { OpenData } from '@fin.cx/opendata'; import { OpenData } from '@fin.cx/opendata';
const initializeOpenData = async () => { const startOpenDataInstance = async () => {
const openData = new OpenData(); const openData = new OpenData();
try { try {
console.log('Starting OpenData instance...');
await openData.start(); await openData.start();
console.log('OpenData instance has started successfully.'); console.log('OpenData instance started successfully.');
// Example usage: // Invoke sample operations:
await createAndManageBusinessRecords(openData); await demonstrateBusinessRecordsOperations(openData);
await demonstrateBulkDataProcessing(openData);
await demonstrateHandelsregisterOperations(openData);
} catch (error) { } catch (error) {
console.error('Error starting OpenData:', error); console.error('Error during initialization:', error);
} finally { } finally {
console.log('Stopping OpenData instance...');
await openData.stop(); await openData.stop();
console.log('OpenData instance has stopped.'); console.log('OpenData instance stopped.');
} }
}; };
initializeOpenData(); startOpenDataInstance();
``` ```
### Managing Business Records In this snippet, we import the OpenData class from the module and execute its start and stop routines to ensure that the MongoDB connection is properly initialized and terminated. Notice that we move on to different demonstration functions that showcase individual features.
The `BusinessRecord` class represents a company's data. Let's explore how you can create, retrieve, update, and manage these records. ────────────────────────────────────────────
### 2. Managing Business Records (CRUD Operations)
#### Creating a New BusinessRecord Central to the @fin.cx/opendata library is the management of business records. The BusinessRecord class encapsulates data pertaining to companies, allowing you to create new records, retrieve existing ones, update information, and delete entries when necessary. The following examples illustrate each operation within a robust context.
Creating a new business record involves instantiating the `BusinessRecord` class and setting the relevant properties. #### a) Creating a Business Record
Creating a new business record in the openData instance is straightforward. You instantiate a new record and populate its data properties with relevant details such as company name, address, registration number, managing directors, and much more. The sample below uses the embedded CBusinessRecord manager to generate a new record:
```typescript ```typescript
import { BusinessRecord } from '@fin.cx/opendata'; import { OpenData } from '@fin.cx/opendata';
const createBusinessRecord = async (openData: OpenData) => { export const createBusinessRecordExample = async (openData: OpenData) => {
const businessRecord = new openData.CBusinessRecord(); const businessRecord = new openData.CBusinessRecord();
businessRecord.data = { businessRecord.data = {
name: "Tech Innovations GmbH", name: "Innovative Solutions GmbH",
address: "Tech Park 42", address: "Musterstraße 1",
postalCode: "80333", postalCode: "10115",
city: "Munich", city: "Berlin",
country: "Germany", country: "Germany",
phone: "+49 89 123456", phone: "+49 30 123456",
email: "info@techinnovations.de", email: "contact@innovativesolutions.de",
website: "https://techinnovations.de", website: "https://innovativesolutions.de",
businessType: "GmbH", businessType: "GmbH",
registrationNumber: "HRB 654321", registrationId: "District court Berlin HRB 987654",
registrationCourt: "Munich",
legalForm: "GmbH", legalForm: "GmbH",
managingDirectors: ["Alice Müller", "Bob Schmidt"], managingDirectors: ["Max Mustermann", "Erika Musterfrau"],
foundingDate: new Date("2020-01-01").toISOString(), foundingDate: new Date("2018-05-10").toISOString(),
capital: "100,000 EUR", capital: "250,000 EUR",
purpose: "Developing innovative tech solutions", purpose: "Technology development and consulting services",
lastUpdate: new Date().toISOString() lastUpdate: new Date().toISOString()
}; };
try {
await businessRecord.save(); await businessRecord.save();
console.log('BusinessRecord saved:', businessRecord); console.log('BusinessRecord created successfully:', businessRecord);
}; } catch (error) {
``` console.error('Error creating business record:', error);
#### Retrieving Business Records
You can retrieve existing business records by querying the database using various data fields.
```typescript
const retrieveBusinessRecords = async (openData: OpenData) => {
const records = await openData.db
.collection<BusinessRecord>('businessrecords')
.find({ city: "Munich" })
.toArray();
console.log('Found Business Records:', records);
};
```
#### Updating Existing Records
To update an existing `BusinessRecord`, you retrieve the record, modify its data, and save it again.
```typescript
const updateBusinessRecord = async (openData: OpenData, recordId: string) => {
const businessRecord = await openData.CBusinessRecord.getInstance(recordId);
if (businessRecord) {
businessRecord.data.phone = "+49 89 987654";
businessRecord.data.lastUpdate = new Date().toISOString();
await businessRecord.save();
console.log('BusinessRecord updated:', businessRecord);
} else {
console.log('BusinessRecord not found for id:', recordId);
} }
}; };
``` ```
#### Deleting a Business Record In this example, after setting the business record fields, the record is saved to the MongoDB collection using the save method. The system ensures that the newly created record receives a unique identifier by generating a new ID when saving the document.
You can delete a business record using its unique identifier. #### b) Retrieving Business Records
To retrieve business records, you can search by various fields such as city, business name, or registration details. The system utilizes MongoDB queries to filter and return relevant documents. Below is a sample function that retrieves all records for companies based in a particular city:
```typescript ```typescript
const deleteBusinessRecord = async (openData: OpenData, recordId: string) => { import { OpenData } from '@fin.cx/opendata';
import type { BusinessRecord } from '@fin.cx/opendata';
export const retrieveRecordsByCity = async (openData: OpenData, city: string) => {
try {
const records = await openData.db
.collection<BusinessRecord>('businessrecords')
.find({ city })
.toArray();
console.log(`Retrieved ${records.length} records for city ${city}.`);
console.log(records);
return records;
} catch (error) {
console.error('Error retrieving business records:', error);
}
};
```
This method queries the "businessrecords" collection using a simple filter and converts the cursor into an array of records. You can extend the query to filter by more sophisticated criteria as needed.
#### c) Updating an Existing Business Record
Modifying the details of an exisiting record is a common operation. First, you need to retrieve the record from the database. Once the record is loaded, you can make changes to its properties and then save the updated record back to the database. The following example demonstrates this with a change to the companys phone number and last update timestamp:
```typescript
import { OpenData } from '@fin.cx/opendata';
export const updateBusinessRecordExample = async (openData: OpenData, recordId: string) => {
try {
// Retrieve the record by its id using the managers helper
const businessRecord = await openData.CBusinessRecord.getInstance(recordId);
if (!businessRecord) {
console.log(`No business record found with id: ${recordId}`);
return;
}
// Update some fields
businessRecord.data.phone = "+49 30 654321";
businessRecord.data.lastUpdate = new Date().toISOString();
// Save the updated record into the database
await businessRecord.save();
console.log("Business record updated successfully:", businessRecord);
} catch (error) {
console.error('Error updating business record:', error);
}
};
```
This code snippet presents a robust pattern where errors are caught and logged, ensuring that any update issues can be diagnosed easily.
#### d) Deleting a Business Record
The deletion of a record is as vital as its creation and modification. The library provides a delete method that removes the specified record from the database. Below is a simple function to delete a business record by its identifier:
```typescript
import { OpenData } from '@fin.cx/opendata';
export const deleteBusinessRecordExample = async (openData: OpenData, recordId: string) => {
try {
const businessRecord = await openData.CBusinessRecord.getInstance(recordId); const businessRecord = await openData.CBusinessRecord.getInstance(recordId);
if (businessRecord) { if (businessRecord) {
await businessRecord.delete(); await businessRecord.delete();
console.log(`BusinessRecord with id ${recordId} deleted successfully.`); console.log(`Successfully deleted business record with id: ${recordId}`);
} else { } else {
console.log('No record found for the provided id:', recordId); console.log(`No business record found with id: ${recordId}`);
} }
};
```
### Updating German Business Data
The package includes functionalities to keep your business data up-to-date by downloading from official German open data repositories.
```typescript
const updateGermanBusinessData = async (openData: OpenData) => {
try {
await openData.germanBusinesses.update();
console.log('German business data has been updated successfully.');
} catch (error) { } catch (error) {
console.error('Error updating German business data:', error); console.error('Error deleting business record:', error);
} }
}; };
``` ```
This function fetches the latest open data regarding German companies, processes it, and updates your local database. Through this example, you can integrate safe deletion practices in your application, removing outdated or incorrect records without compromising database integrity.
### Detailed Class Insights ────────────────────────────────────────────
### 3. Bulk Data Processing and Importing via JSONL Streams
#### OpenData Class One of the powerful features of the @fin.cx/opendata module is its ability to process large datasets provided in the JSON Lines (JSONL) format. The JsonlDataProcessor class is designed to handle streaming data, processing each record concurrently, and efficiently updating the database.
The `OpenData` class serves as the core of the library, initializing necessary components and controlling data flows: This bulk data ingestion mechanism is particularly useful when dealing with large-scale datasets such as the German companies' open data that the module fetches from official data portals. The process involves decompressing, streaming, and parsing data by leveraging pipelines of smart streams and concurrent processors.
- **db**: Represents the connection to your MongoDB database. Below is an extended example demonstrating how to process a JSONL data file from a given URL:
- **germanBusinesses**: An instance handling specific operations related to German business data updates.
```typescript ```typescript
class OpenData { import { OpenData } from '@fin.cx/opendata';
db: plugins.smartdata.SmartdataDb;
germanBusinesses: GermanBusinessData;
private serviceQenv = new plugins.qenv.Qenv(paths.packageDir, paths.nogitDir); // This function demonstrates bulk data processing using the JSONL data processor.
// The dataUrl parameter is optional and, if not provided, defaults to the official open data URL.
public async start() { export const demonstrateBulkDataProcessing = async (openData: OpenData, dataUrl?: string) => {
// Database initialization logic try {
console.log('Starting bulk data processing...');
await openData.jsonLDataProcessor.processDataFromUrl(dataUrl);
console.log('Bulk data processing completed successfully.');
} catch (error) {
console.error('Error during bulk data processing:', error);
} }
};
public async stop() {
// Cleanup logic
}
}
``` ```
#### GermanBusinessData Class In the processDataFromUrl implementation, the library uses a pipeline of smart streams. After downloading the compressed file, it decompresses it and splits the content into discrete JSON lines. The processor then concurrently applies a handler function to each JSON entry. This function extracts relevant company details, instantiates a new BusinessRecord, associates parsed data (for example, registration attributes from German registers), and saves the record to MongoDB.
This class deals specifically with German company data — fetching, processing, and updating local databases consistently with official German data sources. A deeper dive into the processing mechanism:
• The JSONL data is received as a binary (Buffer) stream.
• The stream is piped into a duplex stream that splits the text by newline characters.
• Each line is parsed into a JSON object and passed into an asynchronous processing function.
• This function creates a new business record and sets properties such as the company name and its registration details, derived from the JSON entry.
• As the processor moves through the stream, it logs progress every 10,000 records to give feedback on its bulk processing status.
By supporting concurrency (with a configurable concurrency limit, e.g., 1000 simultaneous operations), the library ensures that even gigabytes of data are processed efficiently without hitting memory bottlenecks.
────────────────────────────────────────────
### 4. Integrating with the Handelsregister: Detailed Demonstrations
In addition to CRUD operations and bulk processing, the module includes an integrated Handelsregister system. This sophisticated component leverages a headless browser (via the smartbrowser instance) to interact with the official Handelsregister website. Through this integration, you can search for companies, navigate to specific pages, trigger file downloads (such as PDF or XML data), and parse the downloaded content for further processing.
#### a) Starting the Handelsregister
Before executing any search or download operations, the Handelsregister system must be started. The start method initializes required resources including starting a headless browser, ensuring download directories are created, and preparing asynchronous stacks for exclusive execution.
```typescript ```typescript
class GermanBusinessData { import { OpenData } from '@fin.cx/opendata';
public async start() {
await this.update();
}
public async update() { export const demonstrateHandelsregisterStart = async (openData: OpenData) => {
// Logic for updating business data using import streams and parsing JSON lines. try {
console.log('Starting Handelsregister services...');
await openData.handelsregister.start();
console.log('Handelsregister ready.');
} catch (error) {
console.error('Error starting Handelsregister service:', error);
} }
} };
``` ```
### Ensuring Data Accuracy and Integrity #### b) Searching for a Company Using the Handelsregister
When working with business data, ensuring integrity and accuracy is crucial. Each record should be checked for validity before being saved or updated, minimizing inconsistencies. Moreover, robust error handling is essential in every step, from data retrieval to database operations, particularly when dealing with external data sources. A common use case is to search for a company by its name. The Handelsregister system creates a dedicated browser page, enters the search criteria into the input fields, selects the appropriate options (such as radio buttons for search type), and clicks the “Find” button. The following function demonstrates how to incorporate these actions:
```typescript
import { OpenData } from '@fin.cx/opendata';
export const searchCompanyExample = async (openData: OpenData, companyName: string, limit: number = 100) => {
try {
console.log(`Searching for company with name "${companyName}"...`);
const records = await openData.handelsregister.searchCompany(companyName, limit);
console.log(`Found ${records.length} matching records for "${companyName}".`);
console.log('Records:', records);
return records;
} catch (error) {
console.error('Error searching for company:', error);
}
};
```
In this scenario, the Handelsregister component uses internal helper functions:
• getNewPage to create a new browser page with file download behavior enabled.
• navigateToPage which navigates to the “Normal search” page.
• Input events to simulate typing in search criteria.
• UI interactions to select options and trigger the search.
#### c) Retrieving Detailed Data and Triggering Downloads
After obtaining general search results, you may wish to retrieve more detailed information about a specific company. Provided you have the parsed registration data (which typically includes the registration court, type, and number), you can instruct the system to navigate to a detailed view and trigger file downloads. These files might include the companys official registry entry (as an XML file) and additional documents (such as a PDF summary).
The example below details how to use the Handelsregister functionality to focus on a specific company by leveraging its registration details, then download both SI and AD files:
```typescript
import { OpenData } from '@fin.cx/opendata';
export const getDetailedCompanyData = async (openData: OpenData, registrationData: { court?: string; type?: 'HRA' | 'HRB' | 'GnR' | 'PR' | 'VR' | 'GsR'; number?: string; }) => {
try {
console.log('Retrieving detailed company data...');
const result = await openData.handelsregister.getSpecificCompany(registrationData);
console.log('Retrieved detailed company data.');
console.log('Business Records:', result.businessRecords);
console.log('Downloaded Files:', result.files);
return result;
} catch (error) {
console.error('Error retrieving detailed company data:', error);
}
};
```
In the above example:
• The getSpecificCompany method triggers navigation through various UI elements:
Selecting the register type via a dropdown.
Inputting the register number.
Choosing the appropriate register court.
• Then, after clicking the “Find” button, the system waits for the results, verifies the visual components on the page, and initiates file downloads.
• The downloaded files are renamed according to their type (SI for XML and AD for PDF) and are returned for further processing or storage.
#### d) Downloading and Processing Files
The Handelsregister component not only triggers file downloads but also includes utility functions that wait for downloads to complete, clear temporary directories, and output the file objects. You may want to use these file objects to persist data locally, parse file content, or send the data downstream for further analysis.
Below is an example that covers downloading and saving the files into a custom directory for post-download analysis:
```typescript
import { OpenData } from '@fin.cx/opendata';
import * as path from 'path';
export const downloadAndSaveFilesExample = async (openData: OpenData, registrationData: { court?: string; type?: 'HRA' | 'HRB' | 'GnR' | 'PR' | 'VR' | 'GsR'; number?: string; }) => {
try {
console.log('Initiating specific company download...');
const result = await openData.handelsregister.getSpecificCompany(registrationData);
const saveDirectory = path.join(process.cwd(), 'downloaded_files');
// Save each downloaded file to the specified directory
for (const file of result.files) {
await file.writeToDir(saveDirectory);
console.log(`File saved: ${file.path}`);
}
} catch (error) {
console.error('Error during file download and save process:', error);
}
};
```
This function demonstrates a complete flow from launching the Handelsregister detailed company search to saving the downloaded files to disk. This example is particularly useful in scenarios where the downloaded documents need to be processed further, such as converting XML to JSON or extracting text from PDFs.
────────────────────────────────────────────
### 5. Advanced Examples: Combined Operations and Edge Cases
Given the numerous functionalities offered by the library, you can combine various operations to create more complex workflows. One such example is an end-to-end pipeline that:
1. Initializes the open data instance.
2. Processes an initial bulk data import.
3. Searches for key business records that match specific criteria.
4. Updates individual records based on additional data retrieved from the Handelsregister.
5. Handles error conditions and retries processes where necessary.
The following advanced example integrates these steps:
```typescript
import { OpenData } from '@fin.cx/opendata';
const advancedWorkflowExample = async () => {
const openData = new OpenData();
try {
console.log('Starting advanced workflow...');
await openData.start();
// Step 1: Bulk data import from external JSONL source
console.log('Building initial database from bulk import...');
await openData.buildInitialDb();
// Step 2: Search for companies in a selected area (for instance, Munich)
console.log('Retrieving companies located in Munich...');
const munichRecords = await openData.db
.collection('businessrecords')
.find({ city: "Munich" })
.toArray();
console.log(`Found ${munichRecords.length} companies in Munich.`);
// Step 3: For each record, perform an update operation based on new file downloads
for (const record of munichRecords) {
try {
console.log(`Updating record for company: ${record.data.name}`);
// Assuming the record contains parsed registration info
if (record.data.germanParsedRegistration) {
const detailedData = await openData.handelsregister.getSpecificCompany(record.data.germanParsedRegistration);
// Update business record with new information (e.g., registration files or updated details)
record.data.lastUpdate = new Date().toISOString();
// You might want to add additional fields based on the downloaded file data
await record.save();
console.log(`Updated record for ${record.data.name}.`);
} else {
console.log(`No registration data available for ${record.data.name}; skipping update.`);
}
} catch (innerError) {
console.error(`Error updating record for ${record.data.name}:`, innerError);
}
}
// Step 4: Demonstrate retrieval and deletion
const recordToDeleteId = munichRecords.length > 0 ? munichRecords[0].id : null;
if (recordToDeleteId) {
console.log(`Deleting record with id: ${recordToDeleteId}`);
const recordToDelete = await openData.CBusinessRecord.getInstance(recordToDeleteId);
if (recordToDelete) {
await recordToDelete.delete();
console.log(`Record ${recordToDeleteId} deleted successfully.`);
}
}
} catch (error) {
console.error('Advanced workflow encountered an error:', error);
} finally {
console.log('Ending advanced workflow and stopping OpenData instance.');
await openData.stop();
}
};
advancedWorkflowExample();
```
This advanced workflow not only illustrates the coordinated use of bulk data import, search, update, and delete operations but also demonstrates the integration of browser automation for fetching detailed data. The error handling at each step ensures that even if a particular operation fails, the workflow continues in a controlled fashion.
────────────────────────────────────────────
### 6. Error Handling and Data Validation
Robust systems must gracefully handle errors and ensure data consistency. The @fin.cx/opendata library has built-in error handling for asynchronous operations, whether connecting to MongoDB, processing JSON streams, or interacting with web pages. In addition, each BusinessRecord instance provides a validate method that performs basic checks (for instance, ensuring that a company name is present) before a record is saved into the database.
The snippet below shows how to wrap operations in try/catch blocks and use the validate method:
```typescript
import { OpenData } from '@fin.cx/opendata';
export const validateAndSaveRecord = async (openData: OpenData) => {
const record = new openData.CBusinessRecord();
record.data = {
name: "Validation Test Corp",
address: "Teststraße 99",
postalCode: "12345",
city: "Teststadt",
country: "Germany",
phone: "+49 123 456789",
email: "test@testcorp.de",
businessType: "AG",
registrationId: "District court Teststadt HRB 111111",
legalForm: "AG",
managingDirectors: ["Test Director"],
foundingDate: new Date().toISOString(),
capital: "1,000,000 EUR",
purpose: "Testing for data validation",
lastUpdate: new Date().toISOString()
};
try {
// Validate record data before saving.
await record.validate();
await record.save();
console.log("Record validated and saved successfully.");
} catch (error) {
console.error("Error validating or saving record:", error);
}
};
```
Using proper error handling ensures that the entire system remains reliable, and any data validation issues are caught early during development or in production.
────────────────────────────────────────────
### 7. Testing and Automated Workflows
To support continuous integration and adherence to best practices, the @fin.cx/opendata module includes tests written with @push.rocks/tapbundle. You should consider incorporating these tests in your development workflow. The tests verify all main functionalities including instance initialization, bulk data import, Handelsregister operations, and CRUD operations for BusinessRecords.
Below is an example of a simple test written in TypeScript using ESM that makes use of the module:
```typescript
import { expect, tap } from '@push.rocks/tapbundle';
import { OpenData } from '@fin.cx/opendata';
let testOpenDataInstance: OpenData;
tap.test('Instance creation', async () => {
testOpenDataInstance = new OpenData();
expect(testOpenDataInstance).toBeInstanceOf(OpenData);
});
tap.test('Start instance', async () => {
await testOpenDataInstance.start();
});
tap.test('Perform bulk import', async () => {
await testOpenDataInstance.buildInitialDb();
});
tap.test('Stop instance', async () => {
await testOpenDataInstance.stop();
});
tap.start();
```
This test code is designed to verify that the OpenData instance is successfully created, started, performs the critical bulk import operation, and is properly shutdown. Integration tests for the Handelsregister functionality follow a similar pattern and ensure that the browser automation routines and file download processes complete without errors.
────────────────────────────────────────────
### Comprehensive Example: Full Cycle from Initialization to Cleanup
To better illustrate how one might combine several aspects of the module in a production scenario, here's a comprehensive example that ties together initialization, CRUD operations, bulk processing, and Handelsregister interactions. This full-cycle example is written in TypeScript using ESM syntax and demonstrates how to build a production-grade data update and management pipeline.
```typescript
import { OpenData } from '@fin.cx/opendata';
const runFullCyclePipeline = async () => {
const openData = new OpenData();
try {
// Initialize the module and connect to MongoDB
console.log('Initializing the OpenData module...');
await openData.start();
// Step 1: Bulk Import - Build the initial database from downloaded open data
console.log('Starting bulk data import from JSONL source...');
await openData.buildInitialDb();
// Step 2: Business Record Management - Create a sample business record
console.log('Creating a new business record...');
const sampleRecord = new openData.CBusinessRecord();
sampleRecord.data = {
name: "Sample Enterprise GmbH",
address: "Innovation Avenue 101",
postalCode: "80807",
city: "Munich",
country: "Germany",
phone: "+49 89 111222",
email: "info@sampleenterprise.de",
website: "https://sampleenterprise.de",
businessType: "GmbH",
registrationId: "District court Munich HRB 555555",
legalForm: "GmbH",
managingDirectors: ["Director A", "Director B"],
foundingDate: new Date("2015-06-15").toISOString(),
capital: "500,000 EUR",
purpose: "Holistic business solutions and data processing",
lastUpdate: new Date().toISOString()
};
await sampleRecord.save();
console.log('Sample business record created with id:', sampleRecord.id);
// Step 3: Retrieve business records for a specific location
console.log('Retrieving business records for Munich...');
const munichRecords = await openData.db
.collection('businessrecords')
.find({ city: "Munich" })
.toArray();
console.log(`Found ${munichRecords.length} records for Munich.`);
// Step 4: Update an existing record
if (munichRecords.length > 0) {
const recordToUpdateId = munichRecords[0].id;
console.log(`Updating business record with id: ${recordToUpdateId}`);
const recordToUpdate = await openData.CBusinessRecord.getInstance(recordToUpdateId);
if (recordToUpdate) {
recordToUpdate.data.phone = "+49 89 999888";
recordToUpdate.data.lastUpdate = new Date().toISOString();
await recordToUpdate.save();
console.log('Business record updated:', recordToUpdate);
}
}
// Step 5: Use Handelsregister to search for a specific company
console.log('Using Handelsregister to search for a specific company...');
const searchResults = await openData.handelsregister.searchCompany("Step Beyond GmbH", 20);
if (searchResults && searchResults.length > 0) {
const registrationData = searchResults[0].germanParsedRegistration;
console.log('Retrieved registration data:', registrationData);
// Step 6: Retrieve detailed info and download files for the specific company
console.log('Fetching detailed data for the identified company...');
const detailedInfo = await openData.handelsregister.getSpecificCompany(registrationData);
console.log('Detailed company data received:', detailedInfo);
// Optionally, save the downloaded files to a designated directory
for (const downloadedFile of detailedInfo.files) {
await downloadedFile.writeToDir('./output_files');
console.log(`Downloaded file saved at: ${downloadedFile.path}`);
}
} else {
console.log('No matching records found for detailed company data retrieval.');
}
// Step 7: Validate and save a record to demonstrate error handling and validation
console.log('Validating and saving a new test record...');
await validateAndSaveRecord(openData);
} catch (error) {
console.error('An error occurred during the full cycle pipeline operation:', error);
} finally {
// Final cleanup: Stop the OpenData module and release all resources
console.log('Finalizing: stopping the OpenData module...');
await openData.stop();
console.log('Pipeline completed and all resources have been cleaned up.');
}
};
runFullCyclePipeline();
```
In this example, the entire processing cycle is constructed to mimic a realistic scenario. The pipeline:
• Starts by connecting to your database.
• Imports extensive JSONL open data.
• Creates, retrieves, updates, and deletes business records.
• Interacts with the Handelsregister for advanced company-specific operations.
• Implements robust error handling and validation routines, ensuring that each step is verifiable.
• Finally, ensures that resources such as MongoDB connections and headless browser sessions are responsibly closed.
────────────────────────────────────────────
### Final Thoughts on Module Integration
The @fin.cx/opendata library is designed to cater to a wide range of business data management needs. Whether you are an enterprise looking to integrate updated open data for decision-making or a developer looking to build data-rich applications with a focus on German companies, this library provides the tools and abstractions necessary to build robust solutions.
Every component—from the smart data management for business records to the advanced streaming and concurrent processing of JSONL files—is built with scalability and ease of use in mind. Integration with the Handelsregister via browser automation further extends its reach, providing dynamic access to official data sources in real-time.
As demonstrated in the examples above, each sub-component of the library is independent yet harmoniously integrated into a cohesive user experience. The use of ESM syntax throughout the module and the strict adherence to TypeScript definitions enhances reliability, maintainability, and the overall developer experience.
By following the usage scenarios provided in this documentation, you should now have a deep understanding of how to:
• Set up your environment and initialize the OpenData instance.
• Perform CRUD operations on business records.
• Efficiently process thousands of records from external JSONL sources.
• Integrate and automate Handelsregister interactions for detailed company data retrieval.
• Combine all building blocks into advanced automated workflows that support large-scale enterprise applications.
Feel free to explore, extend, and customize these examples to suit your projects unique requirements. The library is designed with extensibility in mind, and additional utility functions or integrations can be added based on your needs.
We encourage you to integrate these practices into your development processes, run the provided tests, and contribute to further enhancements that can benefit the entire community of developers working on open data management systems.
Happy coding and data integrating!
The `@fin.cx/opendata` module provides an extensive toolset for accessing and managing business data, particularly for companies based in Germany. Its functionalities include creating, updating, retrieving, and deleting business records, as well as keeping them current with the latest open data releases. This makes it an invaluable asset for developers aiming to integrate open data seamlessly into their systems, ensuring robust data management capabilities within their applications.
Happy exploring and integrating open data into your projects!
## License and Legal Information ## License and Legal Information

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@fin.cx/opendata', name: '@fin.cx/opendata',
version: '1.4.6', version: '1.5.0',
description: 'A TypeScript library for accessing, managing, and updating open business data, focused on German companies and integrating with MongoDB.' description: 'A comprehensive TypeScript library that manages open business data for German companies by integrating MongoDB, processing JSONL bulk data, and automating browser interactions for Handelsregister data retrieval.'
} }