import jsforce from 'jsforce';
export interface SalesforceConfig {
loginUrl: string;
username: string;
password: string;
securityToken?: string;
}
export class SalesforceClient {
private conn: jsforce.Connection;
private config: SalesforceConfig;
private isConnected: boolean = false;
constructor(config: SalesforceConfig) {
this.config = config;
this.conn = new jsforce.Connection({
loginUrl: config.loginUrl
});
}
async connect(): Promise<void> {
if (this.isConnected) return;
const password = this.config.securityToken
? `${this.config.password}${this.config.securityToken}`
: this.config.password;
await this.conn.login(this.config.username, password);
this.isConnected = true;
}
async query(soql: string): Promise<jsforce.QueryResult<unknown>> {
await this.connect();
return this.conn.query(soql);
}
async describeObject(objectName: string): Promise<jsforce.DescribeSObjectResult> {
await this.connect();
return this.conn.sobject(objectName).describe();
}
async create(objectName: string, data: Record<string, unknown>): Promise<jsforce.RecordResult> {
await this.connect();
return this.conn.sobject(objectName).create(data);
}
async update(objectName: string, data: Record<string, unknown>): Promise<jsforce.RecordResult> {
await this.connect();
return this.conn.sobject(objectName).update(data);
}
async delete(objectName: string, id: string): Promise<jsforce.RecordResult> {
await this.connect();
return this.conn.sobject(objectName).destroy(id);
}
}
export function createSalesforceClient(): SalesforceClient {
const config: SalesforceConfig = {
loginUrl: process.env.SF_LOGIN_URL || 'https://login.salesforce.com',
username: process.env.SF_USERNAME || '',
password: process.env.SF_PASSWORD || '',
securityToken: process.env.SF_SECURITY_TOKEN
};
if (!config.username || !config.password) {
throw new Error('SF_USERNAME and SF_PASSWORD environment variables are required');
}
return new SalesforceClient(config);
}