Mechanic
đŸ“Ŗ Shopify REST Deprecation
  • â›Šī¸Introduction
  • 🤓Hire a Mechanic developer
  • đŸ’¯status.mechanic.dev
  • đŸ“ŖShopify is deprecating the REST API
  • 🙋"I need something custom!"
  • 🧑‍đŸ’ģ"I need help with my custom task!"
  • 🤖"I need help with my AI-written task!"
  • Resources
    • âŦ‡ī¸Install Mechanic
    • 🧑‍đŸ’ģTask library
      • Contributing
      • Requesting
    • 🚀Slack community
    • 🤝Partner directory
    • 🧠Tutorials
      • Video walkthroughs
        • Auto-tag orders by originating staff member
        • Maintain a tag for orders processed today
        • Auto-tag orders with their tracking numbers
        • Sync inventory for shared SKUs
        • Auto-tag products when their SKU(s) change
        • Auto-publish new products
        • Email a report of customers who haven't ordered in X days
        • Upgrading a Mechanic task: Adding a time delay
        • Email the customer when tracking numbers are added to their order
        • Adding an optional time delay to your Mechanic task
        • Delete all orders
        • Send an email when a specific product is shipped
        • Send recurring reminders about unpaid orders
        • Send an email when a product's price goes below its cost
        • Auto-tag customers by sales channel
        • Creating products in bulk
      • Creating a Mechanic webhook
      • Practicing writing tasks
      • Triggering tasks from a contact form
      • Creating scheduled CSV feeds
      • Fetching data from a shared Google sheet
    • 🏆Converting tasks from Shopify REST to GraphQL
      • Conversion: Single resource lookups
      • Conversion: Resource loops to paginated queries
      • Conversion: Connections from a resource
      • Conversion: Metafield lookups from a resource
      • Conversion: Resource lookups in task option fields
  • Core Concepts
    • Events
      • Topics
      • Parent and child events
    • Tasks
      • Subscriptions
      • Code
        • Environment variables
        • Action objects
        • Error objects
        • Log objects
      • Options
        • Custom validation
      • Previews
        • Defining preview events
        • Stub data
      • Shopify API version
      • Advanced settings
        • Documentation
        • JavaScript
        • Perform action runs in sequence
      • Import and export
      • User Form
    • Actions
      • Cache
      • Echo
      • Email
      • Event
      • Files
      • Flow
      • FTP
      • Google Drive
      • Google Sheets
      • HTTP
      • Integrations
        • Report Toaster
      • Shopify
      • File generators
        • Base64
        • PDF
        • Plaintext
        • URL
        • ZIP
    • Runs
      • Scheduling
      • Concurrency
      • Ordering
      • Retries
    • Interacting with Shopify
      • Responding to events
        • Reconciling missing events
      • Reading data
        • âš ī¸Liquid objects
        • 🏆GraphQL in Liquid
        • Bulk operations
        • The Shopify action
      • Writing data
      • Shopify admin action links
      • API rate limit
      • API versions
  • Platform
    • 🔆Policies
      • Data
      • Plans
      • Pricing
      • Privacy
    • Cache
      • Cache endpoints
    • Email
      • Receiving email
      • Custom email addresses
      • DMARC
      • Email templates
    • Error handling
    • Events
      • Event topics
      • Event filters
    • GraphQL
      • Basics
        • Shopify Admin API GraphiQL explorer
        • Queries
        • Mutations
        • Pagination
      • Bulk operations
    • Integrations
      • Appstle Subscriptions
      • Google Drive and Google Sheets
      • Judge.me
      • Locksmith
      • Report Toaster
      • Shopify Flow
      • Run links
    • Liquid
      • Basics
        • Syntax
        • Data types
        • Variables
        • Comments
        • Filters
        • Operators
        • Control flow
          • Condition
          • Iteration
        • Whitespace
      • Liquid console
      • Mechanic filters
        • Deprecated filters
      • Mechanic keyword literals
        • array
        • hash
        • newline
      • Mechanic objects
        • Action object
        • Cache object
        • Event object
        • Options object
        • Task object
        • âš ī¸Shopify REST Admin API
          • đŸšĢArticle object
          • đŸšĢBlog object
          • đŸšĢCollection object
          • đŸšĢCustomer object
          • đŸšĢDiscount code object
          • đŸšĢDispute object
          • đŸšĢDraft order object
          • đŸšĢFulfillment object
          • đŸšĢFulfillment order object
          • đŸšĢFulfillment event object
          • đŸšĢGift card object
          • đŸšĢInventory item object
          • đŸšĢInventory level object
          • đŸšĢLine item object
          • đŸšĢLocation object
          • đŸšĢMetafields
            • Metafield object
            • Metafield representation object
            • Metafield collection object
          • đŸšĢOrder object
          • đŸšĢOrder risk object
          • đŸšĢPrice rule object
          • đŸšĢProduct object
          • đŸšĢProduct image object
          • đŸšĢRefund object
          • đŸšĢShipping zone object
          • đŸšĢShop object
          • đŸšĢTheme object
          • đŸšĢTheme asset object
          • đŸšĢTransaction object
          • đŸšĢVariant object
      • Mechanic tags
        • liquid
        • action
        • assign
        • error
        • log
      • Mechanic code snippets
    • Shopify
      • Custom authentication
      • "Read all orders"
    • Webhooks
  • Techniques
    • Preventing action loops
    • Writing a high-quality task
    • Tagging Shopify resources
    • Debouncing events
    • Responding to action results
    • Working with external APIs
      • JSON Web Signatures
      • AWS request signatures
    • Finding a resource ID
    • Migrating templates from Shopify to Mechanic
    • Securing Mechanic webhooks
    • Monitoring Mechanic
  • FAQ
    • The app isn't loading. What do I do?
    • How do I stop a large batch of runs?
    • A Shopify event is missing. Where is it?
    • Does Mechanic have an affiliate program?
    • Can non-owners install Mechanic?
    • Can I replace Shopify's order emails with Mechanic?
    • Can I manually set Shopify permissions for Mechanic?
    • Does my theme need to be updated for Mechanic?
    • Do you have a plan for development stores?
    • Why don't I see any events in my task's activity?
    • Can I read data back from my webhook submission?
    • My task added a tag, but now the tag is missing – why?
    • How do I add an unsubscribe link to my emails?
    • How do I send images with my emails?
    • Can I re-send order confirmation emails with Mechanic?
    • Why am I seeing a different price than on the app store?
    • Do you have a Partner-friendly plan?
    • Why are my tasks delayed or not running?
    • My task is failing because of a permissions problem. Why?
    • How do I preview email attachments?
    • Can I query external APIs?
    • Why can't I access the Shopify API during preview mode?
    • How do marketing preferences work with Mechanic?
    • Can I send data to Google Sheets?
    • What's possible with timeline comments?
    • I'm getting a "query param length is too long" error when using GraphQL.
    • Can my Mechanic concurrency limit be raised?
    • What IP address does Mechanic use?
    • Can Mechanic read or manage customer subscriptions?
    • Why is everything harder now?
    • Can task content be translated into multiple languages?
    • Can I add a time delay to my task?
    • Can I add another store to my existing Mechanic subscription?
    • How can I reduce memory usage of my task?
    • How do I connect PayPal to Shopify with Mechanic?
    • How do I add a Shopify access scope to my task?
    • Can I have my Mechanic data retained for more (or less) than 15 days?
Powered by GitBook

Important Updates

  • đŸ“Ŗ Shopify REST Deprecation
On this page
  • Purposes
  • For users
  • For developers
  • For Mechanic
  • Sources
  • Detecting preview events
  • Rendering preview actions
  • Static preview actions
  • Dynamic preview actions

Was this helpful?

Edit on GitHub
Export as PDF
  1. Core Concepts
  2. Tasks

Previews

PreviousCustom validationNextDefining preview events

Last updated 1 year ago

Was this helpful?

A task uses its preview to demonstrate what actions the task intends to generate. Among other purposes (see below), this is also how tasks request the Shopify permissions they require.

Mechanic generates a task preview by rendering the task code using a preview event, which resembles a live event that the task may see. The task is then responsible for rendering preview actions in response to the preview event, actions which are visually presented to the user and are analyzed by the platform, but are never actually performed.

Task previews cannot access the Mechanic cache or the Shopify Admin API. This restriction is made to increase the predictability and performance of task previews.

To provide tasks with relevant sample data during preview, developers can (to construct relevant scenarios at the event level) or use (to swap in predefined values for , or for the results of data that would otherwise come from the Mechanic cache or the Shopify Admin API).

Purposes

A preview has three critical purposes:

  1. Showing the user that the task will do what they expect it to do

  2. Showing the task developer that the task code is functioning as intended

  3. Showing the Mechanic platform what permissions the task requires

For users

Core to the design of Mechanic is the idea that we can make it easy to make it easy – in this case, making it easy for developers to show their users what a Mechanic task can be expected to do.

By rendering preview actions, a task can prove to the user that it is interpreting their configuration as they intended. For example, by rendering a preview action, a task can show the user that their configured email content is appearing as expected inside the email body. This increases trust in the task, and allows users confidence in the task's outcome, even before the task processes a live event.

For developers

Developers may think of previews as a sort of test, using preview actions to prove that their task code is functioning as intended. A quality task will exercise all of its code in response to a preview event; doing so gives the developer instant feedback on task results, without actually having to run the task with a live event.

For Mechanic

At the platform level, Mechanic uses previews to determine what permissions a task requires.

Mechanic gets this information from the actions that a task generates during preview, as well as from analysis of the Liquid lookups and GraphQL queries that a task uses during runtime.

Sources

Previews are generated using synthetic, temporary, non-persisted events – at least one for each event topic that the task subscribes to. These events are sourced from one of three places, in order of priority:

  1. Or, if the Mechanic account has a recent event with a matching topic on file, the preview will use data from that event;

Detecting preview events

A preview event is identical to a live event in all respects but one: it contains a preview attribute, set to true, identifying it as a preview event.

For live events, the preview attribute does not exist. This means that event.preview == false is not a valid way to detect a live event. Instead, use event.preview != true, or event.preview == nil.

{% if event.preview %}
  {% log "This is a preview event, generated by Mechanic." %}
{% else %}
  {% log "This is a live event, received by Shopify." %}
{% endif %}

{% if event.preview != true %}
  {% log "This is a live event, received by Shopify." %}
{% else %}
  {% log "This is a preview event, generated by Mechanic." %}
{% endif %}

A preview event's data is taken from the Mechanic account's event history, providing a realistic sample of the data a task can expect to see. (If the account history has no events for a given topic just yet, Mechanic will attempt to use anonymous sample event data of its own.)

Rendering preview actions

A developer can choose between rendering static and dynamic preview actions. Static preview actions are hard-coded, written to appear whenever event.preview is true. Dynamic preview actions are the result of the task code running normally, using event data in preview in the same way that it would use that event data with a live event. Because dynamic preview actions are the result of meaningfully exercising the task's code, they can provide a good indicator of how the task will behave with a live event. By contrast, static preview actions do not provide useful feedback on how a task is coded.

Static preview actions

In the following example, a static preview action demonstrates that the task intends to tag incoming orders with "web". In actuality, the task's intent is to only tag orders that arrive via the Online Store channel; because the task can't be sure whether or not the preview event will contain such an order, a static preview action is used to ensure that a preview event always results in a tagging action.

Branching a task like this has two problems:

  1. The actual condition of the task is not exercised during preview. The task will need to be tested with live orders from multiple channels, in order to verify that the task works properly.

  2. Duplicating code makes it easier for one copy of the code to fall out of date. By using completely different code for the preview and live actions, it becomes easier for developers to forget to keep the two copies in sync as the task evolves.

{% if event.preview %}
  {% action "shopify" %}
    mutation {
      tagsAdd(id: "gid://shopify/Order/1234567890", tags: "web") {
        userErrors { field, message }
      }
    }
  {% endaction %}
{% elsif order.source_name == "web" %}
  {% action "shopify" %}
    mutation {
      tagsAdd(id: {{ order.admin_graphql_api_id | json }}, tags: "web") {
        userErrors { field, message }
      }
    }
  {% endaction %}
{% endif %}
shopify/orders/create

Dynamic preview actions

A dynamic preview action is the natural result of exercising a task's code as completely as possible, without adding any business logic that responds to event.preview. Put another way, the idea is to make the preview (that appears during task editing) look as similar to a live event as possible.

Example
{% if some_evaluated_condition %}
  {% action "shopify" %}
    mutation {
      tagsAdd(id: {{ order.admin_graphql_api_id | json }}, tags: "web") {
        userErrors { field, message }
      }
    }
  {% endaction %}
{% endif %}

There are two techniques available for "steering" the task towards desired outcomes during preview.

For example, if a task renders a action containing a mutation, Mechanic will prompt the user to grant access to the write_customers Shopify OAuth scope. If Mechanic observes a task using shop.customers, or observes the filter receiving a customer-related GraphQL query, it will prompt for the read_customers scope.

Some GraphQL mutations have multiple potential scope requirements, like or . Because the requirements of these mutations hinge on their arguments, make sure that your preview actions are rendered with realistic ID strings (e.g. id: "gid://shopify/Product/12345"). Mechanic will look for these IDs to determine what scopes to request.

If the task for a given topic, the preview will use the defined event;

Or, if the event topic is standard and known to Mechanic (i.e. not a part of ), the preview will use illustrative example event data defined by the Mechanic platform.

A static preview action is rendered in direct response to event.preview. In general, it's better to use , but an understanding of both techniques is useful.

Use to control preview event data, without ever having to add preview-related code to the task itself. This is the cleanest way to control data provided by the event during preview.

Use to dynamically swap in preview-friendly values. This is generally not necessary for preview event data, but may be necessary when querying Shopify for data during a task: because the Shopify API is disabled during preview, using stub data can be useful for swapping in realistic values that would be returned during a live run.

define preview events
stub data
environment variables
Email
tagsAdd
metafieldsSet
defines its own preview event
the User domain
defined preview events
stub data
dynamic preview actions
Shopify
customerCreate
shopify