# scandipwa/persisted-query

> ScandiPWA persisted query module

`composer require scandipwa/persisted-query`

Canonical URL: https://packagento.com/scandipwa/persisted-query

## At a glance

- **Vendor**: scandipwa (https://packagento.com/scandipwa.md)
- **Latest version**: 3.1.1 — released 2023-04-12
- **Pricing**: Free
- **Package type**: Magento 2 module
- **Status**: active, accepting new buyers

## Installation

Packagento is licence-gated, so even free packages need a licence on a project before Composer can resolve them.

1. **Sign in or create an account** at https://packagento.com/customer/account/.

2. **Add the package to your account.** Open https://packagento.com/scandipwa/persisted-query and complete the free checkout. A licence is minted automatically.

3. **Create or pick a project, then activate the licence on it.**
   - Projects represent the Magento installs you deploy to. Manage them at https://packagento.com/projects/.
   - Activate the new licence on the project you'll deploy this package to. Activation is what generates the Composer credentials scoped to that project.

4. **Add the project credentials to your Magento codebase.**

   Grab the project's public + private key from https://packagento.com/projects/ (open the project, then its Credentials tab), and add them to `auth.json`:

   ```json
   {
     "http-basic": {
       "packagento.com": {
         "username": "ppk_live_...",
         "password": "psk_live_..."
       }
     }
   }
   ```

   Add the Packagento Composer repository to `composer.json`:

   ```json
   {
     "repositories": [
       { "type": "composer", "url": "https://packagento.com" }
     ]
   }
   ```

5. **Install and apply.**

   ```bash
   composer require scandipwa/persisted-query:*
   bin/magento setup:upgrade
   bin/magento setup:di:compile
   bin/magento cache:flush
   ```

## What it does

ScandiPWA persisted query module

## README

The main goal of persisted query approach is to reduce the amount of data transfered from the client to the server within a POST body containing GraphQl Document.
However, current module extends the usage of persisted queries to actually cache the responses in Varnish or CDN node
 for fast responses. (avg. 5ms vs 5000ms on dev machine)

### Prerequisites
1. Varnish
2. Redis
3. PHP ext-phpredis is suggested for faster serialization and deserialization 

### Config
#### magento setup:config:set
For the convenience there are additional flags available for `php bin/magento setup:config:set` command:

`--pq-host`[mandatory] - persisted query redis host  (`redis` for ScandiPWA docker setup)

`--pq-port`[mandatory] - persisted query redis port (`6379` for ScandiPWA docker setup)

`--pq-database`[mandatory] - persisted query redis database (`5` for ScandiPWA docker setup)

`--pq-scheme`[mandatory] - persisted query redis scheme

`--pq-password`[optional, **empty password is not allowed**] - persisted query redis password

#### Manual configuration
Configuration for custom Redis storage, where hashes and GraphQl documents are kept in environment config 
(`app/etc/env.php`) -> `cache/persisted-query` and can be configured manually:
```
	'persisted-query' => [
		'redis' => [
			'host' => 'redis',
			'scheme' => 'tcp',
			'port' => '6379',
			'database' => '5'
		]
	]
```

### Cache control

Available from v1.3.0

CLI command `magento cache:flush` and admin panel `Cache Management` has necessary logic to flush GraphQl responses 
stored in varnish.

`persisted_query_response` - can be disabled, controls `varnish` caches (graphql response caches).

`bin/magento scandipwa:pq:flush` - flushes persisted query REDIS storage(query body)



### Usage
Dynamic persisted query suppose Client to register unknown queries with a series of request-response.

Recommended usage:
1) Optimistically request query execution, referencing query by hash, passing necessary query variables as request 
parameters: `GET 
/graphql?hash=135811058&hideChildren=true`
2) Server has multiple options:
- respond with resolved query (status code `200`)
- respond with Unknown query error (status code `410`)
3) Status code `410` - client must issue PUT request, with the same hash and **entire GraphQl query document within 
the body**. `PUT /graphql?hash=135811058`
4) Server responds with status code `201` on successful query registration.
5) Server will now executes the registered query referenced by hash`GET /graphql?hash=135811058`

In order to effectively utilize persisted query mechanism and avoid unnecessary time-consuming request-response 
interactions GraphQl query must utilize variables.

#### Variables
Variables must be passed in pseudo-json format. You must keep the structure, but skip usage of quotes.

##### Array
Array is a list of values, separated with coma, i.e.: `cmsBlocks_identifiers=homepage-promo-categories,homepage-top-items,homepage-about-us`

Let's consider the details:
`cmsBlocks_identifiers` - GraphQl variable name
`homepage-promo-categories,homepage-top-items,homepage-about-us` - Array of values

##### Complex structures
Complex structures must keep structures described with special chars `{`, `}`, `:`.
Array within complex structs MUST use special chars: `[`, `]`.

Example:

`_filter={category_url_path:{eq:men},max_price:{lteq:300},color:{in:[74,75]}}`
Let's consider the details:
`_filter` - GraphQl variable name
`{
	category_url_path:
	{
		eq:men
	},
	max_price:{
		lteq:300
	},
	color:{
		in:[74,75]
	}
}` - "Object", passed as GET parameter. It has not quotation marks, as these are automatically added by the server 
during the processing.

---
#### Examples
Query body:

`query ($cmsBlocks_identifiers:[String]) {cmsBlocks:cmsBlocks(identifiers:$cmsBlocks_identifiers){ items{ title, content, identifier } }}`

Request URI:

`GET /graphql?hash=2443957263&cmsBlocks_identifiers=homepage-promo-categories,homepage-top-items,homepage-about-us`

---
Query body:

`"query ($_currentPage:Int!, $_pageSize:Int!, $_filter:ProductFilterInput!, $category_url_path:String!) {products(currentPage:$_currentPage, pageSize:$_pageSize, filter:$_filter){ total_count, items{ id, name, short_description, url_key, special_price, sku, categories{ name, url_path, breadcrumbs{ category_name, category_url_key } }, price{ regularPrice{ amount{ value, currency } }, minimalPrice{ amount{ value, currency } } }, thumbnail, thumbnail_label, small_image, small_image_label, brand, color, size, shoes_size, type_id }, filters{ name, request_var, filter_items{ label, value_string, ... on SwatchLayerFilterItem { label, swatch_data{ type, value } } } } }, category:category(url_path:$category_url_path){ id, name, description, url_path, image, url_key, product_count, meta_title, meta_description, breadcrumbs{ category_name, category_url_key, category_level }, children{ id, name, description, url_path, image, url_key, product_count, meta_title, meta_description, breadcrumbs{ category_name, category_url_key, category_level } } }}"`

Request URI:

`https://scandipwa.local/graphql?hash=1713013963&_currentPage=1&_pageSize=12&_filter={category_url_path:{eq:men},max_price:{lteq:300}}&category_url_path=men`

## Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### [Unreleased]

### [2.1.0] - 2019-10-28
#### Changed
- Replace predis/predis with `colinmollenhour/credis`, that supports `PhpRedis` module for high load.

### [1.5.0] - 2019-10-25
#### Changed
- Replace predis/predis with `colinmollenhour/credis`, that supports `PhpRedis` module for high load.

### [2.0.2] - 2019-10-23
#### Changed
- Fix argument value partial escaping

### [1.4.8] - 2019-10-23
#### Changed
- Fix argument value partial escaping

### [2.0.1] - 2019-10-18
#### Changed
- Fix float parameter handling 

### [1.4.7] - 2019-10-18
#### Changed
- Fix float parameter handling 

### [2.0.0] - 2019-07-29
#### Changed
- Magento 2.3.2 adoption
- Fixes

### [1.4.3] - 2019-07-26
#### Added
- verbose error messages for Varnish flush requests

### [1.3.0] - 2019-05-23
#### Added
-  Event observer for`bin/magento cache:flush` to trigger persisted query varnish storage flush (happens also on 
setup:upgrade)
- `bin/magento scandipwa:pq:flush` - command for flushing query document (redis) storage (does not happen on 
setup:upgrade)

#### Removed
- `persisted_query` cache is unlisted in CLI and Admin cache control menu

#### Changed
- File restructuring improving readability
- Updating README.md & CHANGELOG.md
- Update Magento module version to fit release tag
- Minor CS improvements

### [1.2.0] - 2019-05-07
#### Added
- flush option for persisted query redis
- cache control for PQ and PQ responses
- flushing logic for varnish and redis

#### Removed
- version tag in composer.json  

#### Changed    
- Update README.md    
- improve code styling and comments

### [1.1.1] - 2019-03-20
#### Changed
- `--pq-scheme` is not setting `tcp` by default.
- Move CHANGELOG.md to the root of the module
- README.md

### [1.1.0] - 2019-03-20
#### Added
- Added custom flags to `setup:config:set` CLI command

#### Changed
- Changed README.md 

### [1.0.0] - 2019-03-08
#### Added
- Initial commit
- predis/predis as dependency
- persisted query support
- Magento 2 module registration: ScandiPWA_PersistedQuery
- `Plugin\PersistedQuery` registered for `Magento\GraphQl\Controller\GraphQl`
- `Plugin\PersistedQuery` registered for `ScandiPWA\GraphQl\Controller\GraphQl`

## Recent Versions

| Version | Released |
|---|---|
| 3.1.1 | 2023-04-12 |
| 3.1.0 | 2023-04-04 |
| 3.0.5 | 2022-06-11 |
| 3.0.4 | 2022-06-09 |
| 3.0.3 | 2022-01-25 |
| 3.0.2 | 2021-09-22 |
| 3.0.1 | 2020-11-05 |
| 2.5.2 | 2020-11-05 |
| 3.0.0 | 2020-11-05 |
| 2.5.1 | 2020-11-05 |

Showing 10 of 40 versions. Full release history on https://packagento.com/scandipwa/persisted-query.

## Dependencies

### Require

| Package | Constraint |
|---|---|
| colinmollenhour/credis | ^1.10 |
| magento/framework | * |
| magento/module-cache-invalidate | * |
| magento/module-graph-ql | ^100.3 |
| magento/module-page-cache | * |
| magento/module-store | * |

### Suggest

| Package | Constraint |
|---|---|
| magento/module-catalog | To invalidate persisted_query cache after full reindex |

## Quality

Latest release (3.1.1) fails the Packagento QA pipeline. Verdicts below are per-cell (Magento line × PHP version) for the matrixed tools, and run-once for the static / security tiers.


### Compatibility

Each Magento line is installed on its supported PHP versions, then the module is built (DI compile + static-content deploy). Cells show passed / failed / untested; staircase gaps render as `–`.

| Magento | PHP 8.2 | PHP 8.3 | PHP 8.4 | PHP 8.5 |
|---|---|---|---|---|
| 2.4.7 | Pass | Pass | – | – |
| 2.4.8 | – | Pass | 1 | – |
| 2.4.9 | – | – | 1 | 1 |


### Code Quality

Advisory checks against the module's source. Never affect the Compatibility verdict — a phpcs finding can't make a module incompatible.

#### Static Analysis

Coding standards (phpcs), mess detection (phpmd), copy-pasted code (cpd), PHP cross-version compatibility, composer.json validity. Each runs once for the whole module.

| Tool | Status | Findings | Summary |
|---|---|---|---|
| PHPCS | Warning | 42 | 42 warnings (ruleset: Magento2) — 30 auto-fixable with phpcbf |
| PHPMD | Warning | 7 | 7 rule violations (UnusedFormalParameter:5, ExcessiveParameterList:1, NPathComplexity:1) |
| Cpd | Pass | 0 |  |
| Composer validate | Info | 4 | valid; 4 advisory notes (composer validate --strict) |

#### PHPStan

Type-checks the module against a real Magento install. Re-runs per Magento + PHP version because resolvable symbols differ between releases.

| Magento | PHP 8.2 | PHP 8.3 | PHP 8.4 | PHP 8.5 |
|---|---|---|---|---|
| 2.4.7 | 21 | 21 | – | – |
| 2.4.8 | – | 21 | 29 | – |
| 2.4.9 | – | – | 31 | 31 |


### Tests

Unit and integration suites run per Magento + PHP cell. Test failures speak to the module's behaviour, not its compatibility with a line, so they're reported here separately.

#### Unit Tests

| Magento | PHP 8.2 | PHP 8.3 | PHP 8.4 | PHP 8.5 |
|---|---|---|---|---|
| 2.4.7 | N/A | N/A | – | – |
| 2.4.8 | – | N/A | N/A | – |
| 2.4.9 | – | – | N/A | N/A |

#### Integration Tests

| Magento | PHP 8.2 | PHP 8.3 | PHP 8.4 | PHP 8.5 |
|---|---|---|---|---|
| 2.4.7 | N/A | N/A | – | – |
| 2.4.8 | – | N/A | N/A | – |
| 2.4.9 | – | – | N/A | N/A |


### Security

Dependency-advisory audit (composer audit) plus a source malware scan. A malware detection fails the version outright.

| Tool | Status | Findings | Summary |
|---|---|---|---|
| Composer audit | Pass | 0 |  |
| Malware scan | Pass | 0 |  |

## Licence and pricing

Free. A licence is still minted on checkout and bound to your project for Composer access — no payment step.

Refundable within 14 days of first purchase via https://packagento.com/account/refunds/.

## Install via Claude Code or any MCP client

The Packagento MCP server can run the licence + project + Composer steps above in one tool call:

```
purchase_and_install_packages(
  composer_names=["scandipwa/persisted-query"],
  project_id="proj_xxx"
)
```

This handles cart, checkout, licence minting, project activation, and writes auth.json credentials. Connect a client with `claude mcp add packagento https://mcp.packagento.com`. Full setup at https://packagento.com/docs/mcp-setup.

## Vendor

scandipwa is a Magento 2 vendor on Packagento. See https://packagento.com/scandipwa.md for their full catalogue.

