import { GraphQLClient, gql } from 'graphql-request';
import dotenv from 'dotenv';
dotenv.config();
const client = new GraphQLClient(process.env.CONSUELO_GRAPHQL_URL, {
headers: {
authorization: `Bearer ${process.env.CONSUELO_API_KEY}`,
},
});
const CREATE_PERSON = gql`
mutation CreatePerson($data: PersonCreateInput!) {
createPerson(data: $data) {
id
email
}
}
`;
const UPSERT_PERSON = gql`
mutation UpsertPerson($data: PersonUpsertInput!) {
upsertPerson(data: $data) {
id
email
}
}
`;
async function importRecords(records) {
const results = { upserted: 0, failed: 0, errors: [] };
for (const record of records) {
try {
// Map external data to Consuelo format
const personData = {
email: record.email,
firstName: record.first_name,
lastName: record.last_name,
companyId: record.company_id,
};
// Use upsert to avoid duplicates
await client.request(UPSERT_PERSON, { data: personData });
results.upserted++;
} catch (error) {
results.failed++;
results.errors.push({ record, error: error.message });
}
// Rate limit protection
await new Promise(resolve => setTimeout(resolve, 100));
}
return results;
}
export { importRecords };