Sails.js技术问题:启动时让控制器订阅Salesforce Socket并接收流
Got it, let's tackle this problem step by step. You're trying to subscribe to Salesforce's Socket notifications when your Sails.js app starts up so your controller can receive those messages—here's how to make that happen:
Sails.js has a built-in bootstrap hook that runs once right after your app initializes. This is the ideal place to set up your Salesforce Socket subscription, since it guarantees the code executes as soon as the app is ready.
If you don't already have one, create a config/bootstrap.js file in your project root—this is where we'll put the subscription logic.
Assuming you're using Salesforce's Streaming API (which uses WebSockets for real-time notifications), the official jsforce package is the easiest way to handle the connection and subscription. First install it:
npm install jsforce
Add this code to your config/bootstrap.js file. We'll log in to Salesforce, subscribe to your target channel, and route incoming messages to your existing controller logic:
module.exports.bootstrap = async function(done) { const jsforce = require('jsforce'); const conn = new jsforce.Connection({ loginUrl: 'https://login.salesforce.com' // use https://test.salesforce.com for sandboxes }); try { // Log in to Salesforce (use env vars instead of hardcoding credentials!) await conn.login( process.env.SALESFORCE_USERNAME, `${process.env.SALESFORCE_PASSWORD}${process.env.SALESFORCE_SECURITY_TOKEN}` ); // Subscribe to your Salesforce topic/channel const subscription = await conn.streaming.subscribe('/topic/YourTargetTopic', async (message) => { console.log('Received Salesforce notification:', message); // Pass the message to your controller's business logic await sails.controllers.yourcontroller.handleSalesforceNotification(message); }); console.log('Successfully subscribed to Salesforce Streaming API'); // Handle unexpected disconnections with retry logic conn.streaming.on('error', async (err) => { console.error('Salesforce Socket disconnected:', err); // Add retry logic here if needed, e.g., re-subscribe after a delay }); } catch (err) { console.error('Failed to set up Salesforce Socket subscription:', err); // Decide whether to exit the app or continue based on your needs } // Don't forget to call done() to finish bootstrap done(); };
Update your existing controller to accept the incoming message and run your business logic. For example, in api/controllers/YourController.js:
module.exports = { // Your existing HTTP route handlers... handleSalesforceNotification: async function(message) { // Run your existing business logic here // e.g., save notification data to your database, trigger workflows, etc. await SalesforceNotification.create({ payload: message, receivedAt: new Date() }); // No need to return a response—this runs in the background } };
- Never hardcode credentials: Store Salesforce username, password, and security token in environment variables or Sails.js
config/local.js(keep this file out of version control!). - Add reconnection logic: Salesforce may drop the Socket connection occasionally—use the
errorevent handler to retry subscriptions after a short delay. - Validate incoming messages: Always sanitize and validate the Salesforce payload before processing it to avoid security risks.
That's it! Now when your Sails.js app starts up, it will automatically connect to Salesforce, subscribe to the Socket channel, and pass all incoming notifications to your controller's business logic.
内容的提问来源于stack exchange,提问作者blackbird

