Branch hook code based on run mode

Hooks often need to behave differently during testing versus production. The run mode is injected into the context of the hook, allowing you to write code that adapts its behavior based on whether it's running in test or production mode.

Common use cases

Here are typical scenarios where you'll want to branch code based on run mode:

  • Using sandbox/test API endpoints for third-party services
  • Limiting data processing in test mode
  • Enabling additional logging during testing
  • Mocking certain operations in test mode

Examples

Using test APIs

module.exports = async function (payload, actions, context) {
  const api = context.isTestMode ? 
                'https://dev.myapi.com' : 
                'https://myapi.com';

  const { data } = await actions.http.post(api, { a: 1 });
}

Enhanced logging in test mode

module.exports = async function (payload, actions, context) {
  if (context.isTestMode) {
    console.log('Payload received:', payload);
  }
  
  // Process payload...
}

Limiting operations

module.exports = async function (payload, actions, context) {
  const batchSize = context.isTestMode ? 5 : 100;
  
  // Process only a small batch in test mode
  return await processItems(payload.items.slice(0, batchSize));
}

Best practices

  • Always test both production and test mode paths
  • Use meaningful test endpoints that mirror production behavior
  • Keep branching logic simple and maintainable
  • Consider extracting complex branching logic into separate functions
  • Document any significant differences between test and production behavior