import EventEmitter from 'events'; import * as jsforce from 'jsforce'; import * as types from './types'; export default class Salesforce { /** * SalesForce Connection. * * @var {Object} */ private connection: any; /** * The interval ID. * * @var {Object} */ private intervalID: any; /** * Plugin handler has started. * * @var {Boolean} */ private started: boolean = false; /** * The date of the last query. * * @var {String} */ private startTime: String = new Date().toISOString() /** * */ private subscriptions: Array = [] /** * @constructor * @param {Object} config * @param {EventEmitter} eventEmitter */ constructor(private config: types.Config, private eventEmitter: EventEmitter) { this.eventEmitter.emit('info', 'Initializing SalesForce'); } /** * Start listening for events. */ start() { if (!this.started) { const { loginurl, username, password, securitytoken, } = this.config; this.connection = new jsforce.Connection({ loginUrl: loginurl }); this.eventEmitter.emit('info', 'Connecting to SalesForce...'); this.connection.login(username, password + securitytoken, (err: string) => { if (err) throw new Error(err); this.eventEmitter.emit('success', 'Successfully connected to SalesForce!'); Object.keys(this.config.subscribe).forEach((name: string) => { if (this.isSubscribed(name)) { const Subscription = require(`./subscriptions/${this.getFormattedSubscriptionName(name)}`); const feed = new Subscription.default(this.connection, this.eventEmitter); feed.lastQueryTime = this.startTime; this.subscriptions.push(feed); } }); this.started = true; this.intervalID = setInterval(() => this.run(), this.getInterval()); }); } } /** * Stop listening for events. */ stop() { if (this.started) { this.started = false; clearInterval(this.intervalID); } } /** * Query for the most recent SF login events. */ run() { this.subscriptions.forEach(subscription => { this.eventEmitter.emit('info', `Querying SalesForce ${subscription.getName()} at ${subscription.lastQueryTime}`); subscription.run(); }); } /** * Get the formatted subscription name. * * @param {string} name */ getFormattedSubscriptionName(name: string): String { return name.charAt(0).toUpperCase() + name.slice(1); } /** * Get the interval for requests. * * @returns {Number} */ getInterval(): number { return (this.config.interval || 10) * 1000; } /** * */ isSubscribed(name: string): boolean { return this.config.subscribe[name] === true; } }