Get stores informations

Header

  • Composable Action: composables/useDjustAuth/useAuthApi.ts
  • API Route: Storyblok CMS (useAsyncStoryblok('stores'))

Detailed Description

The getStores action retrieves store configuration data from Storyblok CMS to provide dynamic store information for the application. This function serves as a bridge between the authentication system and the content management system, enabling dynamic store selection and configuration based on content managed in Storyblok.

This action is unique in the authentication system as it integrates with Storyblok CMS rather than traditional API endpoints. It provides a way to manage store information, configurations, and metadata through a user-friendly CMS interface while maintaining seamless integration with the authentication workflow.

The function is commonly used during application initialization, store selection interfaces, and administrative configuration management. It enables content managers to update store information without requiring code deployments.

Process Flow

sequenceDiagram
    participant U as User
    participant C as Vue Component
    participant UA as useDjustAuth
    participant SB as Storyblok CMS
    participant SS as Storyblok Store
    participant Cache as CMS Cache

    U->>C: Request store data
    C->>UA: getStores()
    UA->>SB: useAsyncStoryblok('stores')
    SB->>Cache: Check cached content
    Cache-->>SB: Return cached or fetch new
    SB-->>UA: Store configuration data
    UA->>SS: Update Storyblok store
    SS-->>C: Store updated
    C-->>U: Store data available

    alt CMS Error
        SB-->>UA: Connection error
        UA-->>C: Return null
        C-->>U: Show fallback content
    else Content Not Found
        SB-->>UA: 404 Not Found
        UA-->>C: Return null
        C-->>U: Use default configuration
    end

Call Parameters

Main Interface

const getStores = async (): Promise<any[] | null>

Detailed Parameters

ParameterTypeRequiredDefaultExampleImpact
None----No parameters needed

Example Call

const { getStores } = useDjustAuth();

try {
  const stores = await getStores();

  if (stores && stores.length > 0) {
    console.log("Available stores:", stores);
    // Display store selection interface
  } else {
    console.log("No stores available or CMS error");
    // Use default configuration
  }
} catch (error) {
  console.error("Failed to get stores:", error);
}

Returns from Composable

Success Response Format

interface Store {
  id: string;
  name: string;
  description?: string;
  configuration: StoreConfiguration;
  metadata: StoreMetadata;
  active: boolean;
}

interface StoreConfiguration {
  currency: string;
  locale: string;
  timezone: string;
  features: string[];
}

interface StoreMetadata {
  createdAt: string;
  updatedAt: string;
  version: number;
}

Example Success Response

[
  {
    "id": "store_main",
    "name": "Main Store",
    "description": "Primary e-commerce store",
    "configuration": {
      "currency": "EUR",
      "locale": "fr-FR",
      "timezone": "Europe/Paris",
      "features": ["cart", "quotes", "multi-account"]
    },
    "metadata": {
      "createdAt": "2024-01-01T00:00:00Z",
      "updatedAt": "2024-01-15T10:30:00Z",
      "version": 3
    },
    "active": true
  },
  {
    "id": "store_beta",
    "name": "Beta Store",
    "description": "Testing environment store",
    "configuration": {
      "currency": "USD",
      "locale": "en-US",
      "timezone": "America/New_York",
      "features": ["cart", "beta-features"]
    },
    "metadata": {
      "createdAt": "2024-01-10T00:00:00Z",
      "updatedAt": "2024-01-15T08:00:00Z",
      "version": 1
    },
    "active": true
  }
]

Null Response

// Returns null when:
// - Storyblok CMS is unavailable
// - 'stores' content not found in CMS
// - Network connectivity issues
// - CMS authentication fails
const result = null;

Error Management

Error Types and Returns

Error TypeCauseSystem ActionUser Message
Network ErrorCMS connection failureReturn null, log error"Store configuration unavailable"
Content Not Found'stores' content missing in CMSReturn null"Store information not found"
Auth ErrorCMS authentication failureReturn null, log error"Unable to load store configuration"
Parse ErrorInvalid CMS content formatReturn null, log error"Store configuration error"

Error Handling Code Example

const { getStores } = useDjustAuth();
const { $toast } = useNuxtApp();

const loadStoreConfiguration = async () => {
  try {
    const stores = await getStores();

    if (stores && stores.length > 0) {
      // Success: Use dynamic store configuration
      console.log("Loaded stores from CMS:", stores.length);
      return stores;
    } else {
      // Fallback: Use default store configuration
      console.warn("CMS stores not available, using defaults");

      const defaultStores = [
        {
          id: "default",
          name: "Default Store",
          configuration: {
            currency: "EUR",
            locale: "en-US",
            timezone: "UTC",
          },
        },
      ];

      return defaultStores;
    }
  } catch (error) {
    console.error("Store configuration error:", error);

    // Always provide fallback
    $toast.warning("Using default store configuration");
    return getDefaultStoreConfig();
  }
};

Use Cases

  1. Dynamic Store Configuration

    • Content managers update store settings in Storyblok CMS
    • Application loads updated configuration without deployment
    • Store features and settings are dynamically applied
    • Multi-tenant applications adapt to different store configs
  2. Store Selection Interface

    • Display available stores to users during onboarding
    • Allow users to switch between different store contexts
    • Show store-specific branding and configuration
    • Implement store-based access control
  3. Administrative Management

    • Administrators manage store configurations through CMS
    • Content versioning for store configuration changes
    • A/B testing different store configurations
    • Rollback capability for configuration changes
  4. Fallback and Resilience

    • Graceful degradation when CMS is unavailable
    • Default configuration ensures application functionality
    • Error recovery mechanisms for CMS connectivity issues
    • Offline capability with cached store data

Important Points

Performance

The function optimizes CMS integration with intelligent caching through Storyblok's built-in cache, minimal API calls using useAsyncStoryblok, efficient content loading with version control, and smart fallback mechanisms to prevent blocking.

Security

Security considerations include CMS authentication validation, content validation and sanitization, secure API key management, and protection against malicious content injection through proper content parsing.

Flexibility

The system provides flexible content management with dynamic store configuration updates, version-controlled content changes, support for multiple store configurations, and extensible content structure for future requirements.

Integration

Deep integration includes seamless Storyblok CMS connectivity, coordination with authentication workflows, integration with store selection logic, and consistent error handling across the application.

Technical Implementation

/**
 * Retrieves store configuration data from Storyblok CMS
 * @returns Promise<any[] | null> - Array of store configurations or null if unavailable
 * @throws {Error} - CMS or network errors (handled gracefully)
 */
const getStores = async () => {
  try {
    // Access Storyblok store for state management
    const storyStore = useStoryblokStore();

    // Fetch store content from Storyblok CMS
    const story = await useAsyncStoryblok("stores", {
      version: "published", // Use published content only
    });

    // Update store state if content is available
    if (story?.value) {
      storyStore.setStory("stores", story.value?.content?.Stores);
    }

    // Return stores data
    return story.value?.content?.Stores;
  } catch (error) {
    console.error("Failed to get stores:", error);
    return null;
  }
};

Execution Flow

  1. Store Access

    const storyStore = useStoryblokStore();
  2. CMS Content Fetch

    const story = await useAsyncStoryblok("stores", {
      version: "published",
    });
  3. Content Validation

    if (story?.value) {
      // Process valid content
    }
  4. Store Update

    storyStore.setStory("stores", story.value?.content?.Stores);
  5. Return Data

    return story.value?.content?.Stores; // Stores array or undefined
  6. Error Handling

    catch (error) {
      console.error('Failed to get stores:', error);
      return null; // Graceful failure
    }

Storyblok Integration

Content Structure

{
  "content": {
    "Stores": [
      {
        "component": "store",
        "id": "store_main",
        "name": "Main Store",
        "active": true,
        "configuration": {
          "currency": "EUR",
          "locale": "fr-FR"
        }
      }
    ]
  }
}

CMS Configuration

// Storyblok configuration in nuxt.config.ts
export default defineNuxtConfig({
  modules: ["@storyblok/nuxt"],
  storyblok: {
    accessToken: process.env.STORYBLOK_ACCESS_TOKEN,
    apiOptions: {
      region: "us", // or 'eu', 'ap', 'ca'
    },
  },
});

Store Management

// Storyblok store integration
const useStoryblokStore = () => {
  const setStory = (key: string, content: any) => {
    // Store CMS content for application use
    storyblokStore[key] = content;
  };

  return { setStory };
};

Best Practices

Content Management

  • Use published content versions in production
  • Implement proper content validation
  • Provide meaningful defaults for missing content
  • Version control CMS schema changes

Error Handling

  • Always provide fallback configurations
  • Log CMS errors for monitoring
  • Implement graceful degradation
  • Cache content for offline scenarios

Performance

  • Leverage Storyblok's CDN and caching
  • Minimize CMS requests
  • Use appropriate cache headers
  • Implement efficient content loading