0.0.4 • Published 2 years ago

vendure-stellate-plugin v0.0.4

Weekly downloads
-
License
-
Repository
-
Last release
2 years ago

Vendure Stellate Plugin

This plugin integrates Stellate's GraphQL caching service with your Vendure server. The purpose of this plugin is to ensure your Stellate cache gets property purged in response to changes made to product & collection data in Vendure.

Status: This is a preview release. The plan is to eventually incorporate this into the Vendure core monorepo after a period of successful user testing.

Getting Started

  1. Set up your free Stellate account.
  2. Create a new service in the Stellate dashboard and point it at your Vendure Shop API.
  3. Ensure your Stellate config (see the "config" menu item in your Stellate dashboard) includes the following:

    const config: Config = {
      // ... originUrl etc omitted for brevity
    
      "keyFields": {
        "types": {
          "SearchResult": [
            "productId"
          ],
          "SearchResponseCacheIdentifier": [
            "collectionSlug"
          ]
        }
      },
      "rules": [
        {
          "types": [
            "Product",
            "Collection",
            "ProductVariant",
            "SearchResponse"
          ],
          "maxAge": 900,
          "swr": 900,
          "description": "Cache Products, Collections & SearchResponses"
        },
        {
          "types": [
            "Order",
            "Customer",
            "User"
          ],
          "maxAge": 0,
          "swr": 0,
          "description": "Do not cache user data"
        } 
      ],
    };

    You can add other types & keyFields etc., but these are the ones that will be used by the default setup of this plugin.

  4. Create a purging token via the Stellate dashboard. Keep a record of the token - you'll need it shortly.

  5. Install this plugin:
    npm i vendure-stellate-plugin
  6. Add the plugin to your VendureConfig:

    import { StellatePlugin, defaultPurgeRules } from 'vendure-stellate-plugin';
    
    export const config: VendureConfig = {
      // Full config omitted for brevity
      plugins: [
        StellatePlugin.init({
          // The serviceName is the name chosen in step 2 above.  
          serviceName: process.env.STELLATE_SERVICE_NAME,
          // The token created in step 4 above
          apiToken: process.env.STELLATE_PURGE_API_TOKEN,
          purgeRules: defaultPurgeRules,
        }),
      ],
    };
  7. Point your storefront at the Stellate api url rather than your origin server.

Storefront setup

First you'll need to configure your storefront to point to the Stellate CDN url, i.e. https://my-service.stellate.sh

For proper cache purging of search result lists based on collection slug (which is the common way to implement product list pages), modify your query to select the new cacheIdentifier field you'll find on the SearchResponse:

query {
  search(input: $input) {
    cacheIdentifier { collectionSlug } # Add this
    items {
      productId
      # ... etc
    }
    totalItems
  }
}

Logging

By default, this plugin will log whenever a purge request is sent to the Stellate API. These logs are visible at the Verbose level, so you'll need to have your logger set to log verbose messages:

import { VendureConfig, DefaultLogger, LogLevel } from '@vendure/core';

export const config: VendureConfig = {
  logger: new DefaultLogger({ level: LogLevel.Verbose }),
  // ...
}

You'll then see logs like:

verbose 02/11/22, 16:40 - [StellatePlugin] Purging cache: Product(1)

Debug Mode

For local development you don't want to send real requests to the Stellate API. In this case, set debugMode to true. You can additionally log detailed information about exactly what payload will get sent to the Stellate API by enabling debugLogging:

import { VendureConfig, DefaultLogger, LogLevel } from '@vendure/core';
import { StellatePlugin, defaultPurgeRules } from 'vendure-stellate-plugin';

export const config: VendureConfig = {
  logger: new DefaultLogger({ level: LogLevel.Debug }),
  // ...
  plugins: [
    StellatePlugin.init({
      serviceName: process.env.STELLATE_SERVICE_NAME,
      apiToken: process.env.STELLATE_PURGE_API_TOKEN,
      purgeRules: defaultPurgeRules,
      debugMode: true,
      debugLogging: true,
    }),  
  ]  
}

You'll then see logs like:

verbose 02/11/22, 16:40 - [StellatePlugin] Purging cache: Product(1)
debug 02/11/22, 16:40 - [StellatePlugin] DEBUG MODE: Purge arguments:
{
  "type": "Product",
  "keyFields": [
    {
      "name": "id",
      "value": "1"
    }
  ]
}

Custom Purge Rules

The defaultPurgeRules above define how we should react to Vendure events to purge cached records when changes occur inside Vendure. For example, when a product description is updated, there is a purgeProductsOnProductEvent rule which will tell the Stellate API that the given product should be purged from the cache.

It is also possible to define custom rules. Let's say you have a plugin which defines content articles, and you are also caching these in Stellate. You can create a rule that will purge the article when a Vendure event is published saying that an article has been changed:

import { StellatePlugin, defaultPurgeRules, PurgeRule } from 'vendure-stellate-plugin';
import { ArticleEvent } from './plugins/cms-plugin';
// ...

StellatePlugin.init({
  serviceName: process.env.STELLATE_SERVICE_NAME,
  apiToken: process.env.STELLATE_PURGE_API_TOKEN,
  purgeRules: [
      ...defaultPurgeRules,
      new PurgeRule({
          eventType: ArticleEvent,
          handler: ({ events, stellateService }) => {
              const articleIds = events.map((e) => e.article.id);
              Logger.verbose(`Purging cache: Articles(${articleIds.join(', ')})`);
              stellateService.purge('Article', articleIds);
          },
      }),
  ],
})

License

MIT

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago