Certainly! Below is an example of how to write a TypeScript function using Prisma to import data from the described CSV files into a PostgreSQL database. This assumes you have Prisma, Node.js, and necessary CSV parsing libraries installed.
Dependencies
First, ensure you have the following dependencies installed:
npm install @prisma/client prisma csv-parse
Prisma Client Initialization
Make sure to generate your Prisma client before using it:
npx prisma generate
Import Function
import { prisma } from '@prisma/client';
import fs from 'fs';
import csvParse from 'csv-parse';
import path from 'path';
async function parseCSV(filePath: string, columns: string[]): Promise<any[]> {
return new Promise((resolve, reject) => {
const parser = fs.createReadStream(filePath).pipe(csvParse({
columns: columns,
skip_empty_lines: true,
}));
const result: any[] = [];
parser.on('data', (data) => result.push(data));
parser.on('end', () => resolve(result));
parser.on('error', (error) => reject(error));
});
}
async function importData(userId: string) {
const eventsFilePath = path.join(__dirname, 'events.csv'); // Adjust these paths as needed
const companiesFilePath = path.join(__dirname, 'companies.csv');
const contractsFilePath = path.join(__dirname, 'contracts.csv');
const [events, companies, contracts] = await Promise.all([
parseCSV(eventsFilePath, ['name', 'year', 'drive']),
parseCSV(companiesFilePath, ['companyName', 'category', 'description', 'contactName', 'contactEmail', 'contactPhone', 'contactLinkedIn', 'contactFacebook', 'contactRole', 'contactIsActive', 'contactIsPrimary', 'contactNotes']),
parseCSV(contractsFilePath, ['companyName', 'eventName', 'eventYear', 'status', 'notes']),
]);
// Insert companies and their networks
const companyPromises = companies.map(async (company) => {
const createdCompany = await prisma.company.create({
data: {
name: company.companyName,
category: company.category,
description: company.description,
networks: {
create: {
name: company.contactName,
email: company.contactEmail,
phone: company.contactPhone,
linkedIn: company.contactLinkedIn,
facebook: company.contactFacebook,
role: company.contactRole,
isActive: company.contactIsActive === 'TRUE',
isPrimary: company.contactIsPrimary === 'TRUE',
notes: company.contactNotes,
}
}
}
});
return createdCompany;
});
const createdCompanies = await Promise.all(companyPromises);
// Insert events
const eventPromises = events.map(async (eventData) => {
const createdEvent = await prisma.event.create({
data: {
name: eventData.name,
year: eventData.year,
drive: eventData.drive,
mdID: userId,
contracts: { create: [] }
}
});
return createdEvent;
});
const createdEvents = await Promise.all(eventPromises);
// Map to easily find created IDs
const companyMap = new Map(createdCompanies.map(company => [company.name, company.id]));
const eventMap = new Map(createdEvents.map(event => [event.name + event.year, event.id]));
// Insert contracts
const contractPromises = contracts.map(async (contract) => {
const companyId = companyMap.get(contract.companyName);
const eventId = eventMap.get(contract.eventName + contract.eventYear);
if (!companyId || !eventId) {
throw new Error(`Company or Event not found for contract: ${JSON.stringify(contract)}`);
}
const createdContract = await prisma.contract.create({
data: {
companyID: companyId,
eventID: eventId,
userID: userId,
status: contract.status,
notes: contract.notes
}
});
return createdContract;
});
await Promise.all(contractPromises);
}
// Call the import function
const userId = 'yourUserIdHere';
importData(userId).then(() => {
console.log('Data imported successfully.');
}).catch(error => {
console.error('Error importing data:', error);
});
Explanation
- CSV Parsing: The
parseCSV function reads and parses the CSV files into arrays of objects.
- Inserting Data:
- Companies and Networks: Insert the companies and their associated networks.
- Events: Insert the events.
- Contracts: Insert the contracts, linking them to the right events and companies.
- Mapping IDs: Use maps to easily find IDs of already-inserted companies and events, needed for creating contracts.
Note
Ensure that the events.csv, companies.csv, and contracts.csv paths are correct. Adjust according to your project structure. Also, error handling in the real world should be more comprehensive.