turns-00026.parquet:31027
9999f4be6efa3b231bc52467
turn 2/3gpt-4o-2024-05-13EnglishRomania708 words
degenerate_repetitionAbsentFinal dense release
USER
async function importCompanies() {
const companies = new Map();
const networks: any[] = [];
fs.createReadStream('./prisma/companies.csv')
.pipe(parse({ columns: true, skip_empty_lines: true }))
.on('data', (row) => {
// Extract company and network data
const companyName = row['Company Name'];
const category = row['Category'];
const companyDescription = row['Description'];
const networkName = row['Contact Name'];
const networkEmail = row['Contact Email'];
const networkPhone = row['Contact Phone'];
const networkLinkedIn = row['Contact LinkedIn'];
const networkFacebook = row['Contact Facebook'];
const networkRole = row['Contact Role'];
const networkIsActive = row['Contact IsActive'] === 'true';
const networkIsPrimary = row['Contact IsPrimary'] === 'true';
const networkNotes = row['Contact Notes'];
if (!companies.has(companyName)) {
companies.set(companyName, {
name: companyName,
category: category,
description: companyDescription,
});
}
networks.push({
companyName,
name: networkName,
email: networkEmail,
phone: networkPhone,
linkedIn: networkLinkedIn === '' ? null : networkLinkedIn,
facebook: networkFacebook === '' ? null : networkFacebook,
role: networkRole,
isActive: networkIsActive,
isPrimary: networkIsPrimary,
notes: networkNotes,
});
})
.on('end', async () => {
// Insert companies into the database
const companyEntries = Array.from(companies.values());
await prisma.company.createMany({
data: companyEntries,
skipDuplicates: true,
});
// Map company names to IDs
const companyNames = companyEntries.map((company) => company.name);
const companyIdMap = new Map();
const fetchedCompanies = await prisma.company.findMany({
where: { name: { in: companyNames } },
select: { id: true, name: true },
});
fetchedCompanies.forEach((company) =>
companyIdMap.set(company.name, company.id),
);
// Insert networks into the database
await prisma.network.createMany({
data: networks.map((network) => ({
companyID: companyIdMap.get(network.companyName),
name: network.name,
email: network.email,
phone: network.phone,
linkedIn: network.linkedIn,
facebook: network.facebook,
role: network.role,
isActive: network.isActive,
isPrimary: network.isPrimary,
notes: network.notes,
})),
});
console.log('Companies and networks imported successfully.');
});
}
this is importCompanies. Could you rewrite it for me pls?ASSISTANT
Sure! We'll refactor the `importCompanies` function to return a `Promise`, just like we did with the `importEvents` function. This will allow us to use `await` and ensure that all database operations complete before moving on to the next step.
Here’s the refactored `importCompanies` function:
```javascript
async function importCompanies() {
return new Promise((resolve, reject) => {
const companies = new Map();
const networks: any[] = [];
fs.createReadStream('./prisma/companies.csv')
.pipe(parse({ columns: true, skip_empty_lines: true }))
.on('data', (row) => {
// Extract company and network data
const companyName = row['Company Name'];
const category = row['Category'];
const companyDescription = row['Description'];
const networkName = row['Contact Name'];
const networkEmail = row['Contact Email'];
const networkPhone = row['Contact Phone'];
const networkLinkedIn = row['Contact LinkedIn'];
const networkFacebook = row['Contact Facebook'];
const networkRole = row['Contact Role'];
const networkIsActive = row['Contact IsActive'] === 'true';
const networkIsPrimary = row['Contact IsPrimary'] === 'true';
const networkNotes = row['Contact Notes'];
if (!companies.has(companyName)) {
companies.set(companyName, {
name: companyName,
category: category,
description: companyDescription,
});
}
networks.push({
companyName,
name: networkName,
email: networkEmail,
phone: networkPhone,
linkedIn: networkLinkedIn === '' ? null : networkLinkedIn,
facebook: networkFacebook === '' ? null : networkFacebook,
role: networkRole,
isActive: networkIsActive,
isPrimary: networkIsPrimary,
notes: networkNotes,
});
})
.on('error', (error) => {
console.error('Error reading companies.csv', error);
reject(error);
})
.on('end', async () => {
try {
// Insert companies into the database
const companyEntries = Array.from(companies.values());
await prisma.company.createMany({
data: companyEntries,
skipDuplicates: true,
});
// Map company names to IDs
const companyNames = companyEntries.map((company) => company.name);
const companyIdMap = new Map();
const fetchedCompanies = await prisma.company.findMany({
where: { name: { in: companyNames } },
select: { id: true, name: true },
});
fetchedCompanies.forEach((company) =>
companyIdMap.set(company.name, company.id),
);
// Insert networks into the database
await prisma.network.createMany({
data: networks.map((network) => ({
companyID: companyIdMap.get(network.companyName),
name: network.name,
email: network.email,
phone: network.phone,
linkedIn: network.linkedIn,
facebook: network.facebook,
role: network.role,
isActive: network.isActive,
isPrimary: network.isPrimary,
notes: network.notes,
})),
});
console.log('Companies and networks imported successfully.');
resolve();
} catch (error) {
console.error('Error importing companies and networks', error);
reject(error);
}
});
});
}
```
### Explanation:
1. **Creating a Promise:**
- The `importCompanies` function now returns a `Promise`. This promise resolves when all CSV reading and database operations are concluded.
2. **Error Handling:**
- An `error` event listener has been added to the CSV read stream to catch and reject the promise in case of CSV reading errors.
3. **Resolving and Rejecting the Promise:**
- The promise is resolved upon successful completion of all operations within the `end` event listener, and rejected in case of errors during database operations.
4. **Usage in the `main` function:**
- Once refactored, you can call `await importCompanies()` within the `main` function to ensure it runs sequentially.
This refactoring ensures that `importCompanies` can be awaited, allowing you to control the execution order of your asynchronous code better.