Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Improve SDK querying interface

Damian Legawiec23de0f1a1a9e
diff --git a/packages/next/README.md b/packages/next/README.md
index 30599cbee0..238e45086b 100644
--- a/packages/next/README.md
+++ b/packages/next/README.md
@@ -40,7 +40,7 @@ import { listProducts, getProduct, listTaxons } from '@spree/next';
export default async function ProductsPage() {
const products = await listProducts({ per_page: 12 });
- const categories = await listTaxons({ 'q[depth_eq]': 1 });
+ const categories = await listTaxons({ depth_eq: 1 });
return (
<div>
@@ -104,7 +104,7 @@ const filters = await getProductFilters({ taxon_id: 'txn_123' });
import { listTaxons, getTaxon, listTaxonProducts } from '@spree/next';
import { listTaxonomies, getTaxonomy } from '@spree/next';
-const taxons = await listTaxons({ 'q[depth_eq]': 1 });
+const taxons = await listTaxons({ depth_eq: 1 });
const taxon = await getTaxon('categories/clothing');
const products = await listTaxonProducts('categories/clothing', { per_page: 12 });
diff --git a/packages/next/src/actions/orders.ts b/packages/next/src/actions/orders.ts
index 47370473cb..54dc6a545a 100644
--- a/packages/next/src/actions/orders.ts
+++ b/packages/next/src/actions/orders.ts
@@ -1,6 +1,6 @@
'use server';
-import type { StoreOrder, PaginatedResponse } from '@spree/sdk';
+import type { StoreOrder, PaginatedResponse, OrderListParams } from '@spree/sdk';
import { withAuthRefresh } from '../auth-helpers';
import { getClient } from '../config';
@@ -8,7 +8,7 @@ import { getClient } from '../config';
* List the authenticated customer's orders.
*/
export async function listOrders(
- params?: Record<string, unknown>
+ params?: OrderListParams
): Promise<PaginatedResponse<StoreOrder>> {
return withAuthRefresh(async (options) => {
return getClient().store.customer.orders.list(params, options);
diff --git a/packages/next/src/data/products.ts b/packages/next/src/data/products.ts
index ab1ebfc57d..e5258eb961 100644
--- a/packages/next/src/data/products.ts
+++ b/packages/next/src/data/products.ts
@@ -1,4 +1,4 @@
-import type { StoreProduct, PaginatedResponse, ProductFiltersResponse } from '@spree/sdk';
+import type { StoreProduct, PaginatedResponse, ProductFiltersResponse, ProductListParams } from '@spree/sdk';
import { getClient } from '../config';
import type { SpreeNextOptions } from '../types';
@@ -6,7 +6,7 @@ import type { SpreeNextOptions } from '../types';
* List products with optional filtering, sorting, and pagination.
*/
export async function listProducts(
- params?: Record<string, unknown>,
+ params?: ProductListParams,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreProduct>> {
return getClient().store.products.list(params, {
diff --git a/packages/next/src/data/taxons.ts b/packages/next/src/data/taxons.ts
index 6e23a6d7ce..f3ace60582 100644
--- a/packages/next/src/data/taxons.ts
+++ b/packages/next/src/data/taxons.ts
@@ -1,4 +1,4 @@
-import type { StoreTaxon, StoreProduct, PaginatedResponse } from '@spree/sdk';
+import type { StoreTaxon, StoreProduct, PaginatedResponse, TaxonListParams, ProductListParams } from '@spree/sdk';
import { getClient } from '../config';
import type { SpreeNextOptions } from '../types';
@@ -6,7 +6,7 @@ import type { SpreeNextOptions } from '../types';
* List taxons (categories) with optional filtering and pagination.
*/
export async function listTaxons(
- params?: Record<string, unknown>,
+ params?: TaxonListParams,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreTaxon>> {
return getClient().store.taxons.list(params, {
@@ -34,7 +34,7 @@ export async function getTaxon(
*/
export async function listTaxonProducts(
taxonId: string,
- params?: Record<string, unknown>,
+ params?: ProductListParams,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreProduct>> {
return getClient().store.taxons.products.list(taxonId, params, {
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index e37f52d0fe..2fd4919fd1 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -148,7 +148,8 @@ const store = await client.store.store.get();
const products = await client.store.products.list({
page: 1,
per_page: 25,
- 'q[name_cont]': 'shirt',
+ name_cont: 'shirt',
+ sort: 'price asc',
includes: 'variants,images,taxons',
});
@@ -178,8 +179,8 @@ const categories = await client.store.taxonomies.get('tax_123', {
// List taxons with filtering
const taxons = await client.store.taxons.list({
- 'q[depth_eq]': 1, // Top-level categories only
- 'q[taxonomy_id_eq]': '123', // Filter by taxonomy
+ depth_eq: 1, // Top-level categories only
+ taxonomy_id_eq: '123', // Filter by taxonomy
});
// Get single taxon by ID or permalink
diff --git a/packages/sdk/src/params.ts b/packages/sdk/src/params.ts
new file mode 100644
index 0000000000..4c94815fc5
--- /dev/null
+++ b/packages/sdk/src/params.ts
@@ -0,0 +1,42 @@
+/**
+ * Keys that are passed through to the API without wrapping in q[...].
+ */
+const PASSTHROUGH_KEYS = new Set(['page', 'per_page', 'includes', 'include']);
+
+/**
+ * Transforms flat SDK params into Ransack-compatible query params.
+ *
+ * - `page`, `per_page`, `includes`, `include` pass through unchanged
+ * - `sort` maps to `q[s]`
+ * - Keys already in `q[...]` format pass through (backward compat)
+ * - All other keys are wrapped: `name_cont` → `q[name_cont]`
+ */
+export function transformListParams(
+ params: Record<string, unknown>
+): Record<string, string | number | undefined> {
+ const result: Record<string, string | number | undefined> = {};
+
+ for (const [key, value] of Object.entries(params)) {
+ if (value === undefined) continue;
+
+ if (PASSTHROUGH_KEYS.has(key)) {
+ result[key] = value as string | number;
+ continue;
+ }
+
+ if (key === 'sort') {
+ result['q[s]'] = value as string;
+ continue;
+ }
+
+ // Backward compat: already-wrapped q[...] keys pass through
+ if (key.startsWith('q[')) {
+ result[key] = value as string | number;
+ continue;
+ }
+
+ result[`q[${key}]`] = value as string | number;
+ }
+
+ return result;
+}
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index 9599d43f4c..772471d0cc 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -1,4 +1,5 @@
import type { RequestFn, RequestOptions } from './request';
+import { transformListParams } from './params';
import type {
AuthTokens,
LoginCredentials,
@@ -98,7 +99,7 @@ export class StoreClient {
): Promise<PaginatedResponse<StoreProduct>> =>
this.request<PaginatedResponse<StoreProduct>>('GET', '/products', {
...options,
- params: params as Record<string, string | number | undefined>,
+ params: params ? transformListParams(params) : undefined,
}),
/**
@@ -169,7 +170,7 @@ export class StoreClient {
): Promise<PaginatedResponse<StoreTaxon>> =>
this.request<PaginatedResponse<StoreTaxon>>('GET', '/taxons', {
...options,
- params: params as Record<string, string | number | undefined>,
+ params: params ? transformListParams(params) : undefined,
}),
/**
@@ -203,7 +204,7 @@ export class StoreClient {
`/taxons/${taxonId}/products`,
{
...options,
- params: params as Record<string, string | number | undefined>,
+ params: params ? transformListParams(params) : undefined,
}
),
},
@@ -756,7 +757,7 @@ export class StoreClient {
): Promise<PaginatedResponse<StoreOrder>> =>
this.request<PaginatedResponse<StoreOrder>>('GET', '/customer/orders', {
...options,
- params: params as Record<string, string | number | undefined>,
+ params: params ? transformListParams(params) : undefined,
}),
},
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index f81f789cc4..f0c24f74d7 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -54,23 +54,44 @@ export interface ListParams {
}
export interface ProductListParams extends ListParams {
- 'q[name_cont]'?: string;
- 'q[price_gte]'?: number;
- 'q[price_lte]'?: number;
- 'q[taxons_id_eq]'?: string;
+ /** Sort order, e.g. 'price asc', 'created_at desc' */
+ sort?: string;
+ /** Full-text search across name and SKU */
+ multi_search?: string;
+ /** Filter: name contains */
+ name_cont?: string;
+ /** Filter: price >= value */
+ price_gte?: number;
+ /** Filter: price <= value */
+ price_lte?: number;
+ /** Filter: products in taxon */
+ taxons_id_eq?: string;
+ /** Any additional Ransack predicate */
+ [key: string]: string | number | boolean | undefined;
}
export interface TaxonListParams extends ListParams {
- 'q[taxonomy_id_eq]'?: string | number;
- 'q[parent_id_eq]'?: string | number;
- 'q[depth_eq]'?: number;
- 'q[name_cont]'?: string;
+ /** Sort order, e.g. 'name asc', 'created_at desc' */
+ sort?: string;
+ /** Filter: name contains */
+ name_cont?: string;
+ taxonomy_id_eq?: string | number;
+ parent_id_eq?: string | number;
+ depth_eq?: number;
+ /** Any additional Ransack predicate */
+ [key: string]: string | number | boolean | undefined;
}
export interface OrderListParams extends ListParams {
- 'q[state_eq]'?: string;
- 'q[completed_at_gte]'?: string;
- 'q[completed_at_lte]'?: string;
+ /** Sort order, e.g. 'completed_at desc' */
+ sort?: string;
+ /** Full-text search across number, email, customer name */
+ multi_search?: string;
+ state_eq?: string;
+ completed_at_gte?: string;
+ completed_at_lte?: string;
+ /** Any additional Ransack predicate */
+ [key: string]: string | number | boolean | undefined;
}
// Cart operations
diff --git a/packages/sdk/tests/params.test.ts b/packages/sdk/tests/params.test.ts
new file mode 100644
index 0000000000..29f2f7efc5
--- /dev/null
+++ b/packages/sdk/tests/params.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect } from 'vitest';
+import { transformListParams } from '../src/params';
+
+describe('transformListParams', () => {
+ it('passes through pagination params unchanged', () => {
+ const result = transformListParams({ page: 2, per_page: 10 });
+ expect(result).toEqual({ page: 2, per_page: 10 });
+ });
+
+ it('passes through includes param unchanged', () => {
+ const result = transformListParams({ includes: 'variants,images' });
+ expect(result).toEqual({ includes: 'variants,images' });
+ });
+
+ it('passes through include param unchanged', () => {
+ const result = transformListParams({ include: 'variants' });
+ expect(result).toEqual({ include: 'variants' });
+ });
+
+ it('transforms sort to q[s]', () => {
+ const result = transformListParams({ sort: 'price asc' });
+ expect(result).toEqual({ 'q[s]': 'price asc' });
+ });
+
+ it('wraps filter keys in q[...]', () => {
+ const result = transformListParams({
+ name_cont: 'shirt',
+ price_gte: 20,
+ price_lte: 100,
+ });
+ expect(result).toEqual({
+ 'q[name_cont]': 'shirt',
+ 'q[price_gte]': 20,
+ 'q[price_lte]': 100,
+ });
+ });
+
+ it('transforms multi_search', () => {
+ const result = transformListParams({ multi_search: 'shirt' });
+ expect(result).toEqual({ 'q[multi_search]': 'shirt' });
+ });
+
+ it('passes through already-wrapped q[...] keys (backward compat)', () => {
+ const result = transformListParams({ 'q[name_cont]': 'shirt' });
+ expect(result).toEqual({ 'q[name_cont]': 'shirt' });
+ });
+
+ it('skips undefined values', () => {
+ const result = transformListParams({ name_cont: undefined, page: 1 });
+ expect(result).toEqual({ page: 1 });
+ });
+
+ it('handles a full combined query', () => {
+ const result = transformListParams({
+ page: 1,
+ per_page: 12,
+ includes: 'images,default_variant',
+ sort: 'created_at desc',
+ name_cont: 'shirt',
+ price_gte: 20,
+ taxons_id_eq: 'txn_abc123',
+ });
+ expect(result).toEqual({
+ page: 1,
+ per_page: 12,
+ includes: 'images,default_variant',
+ 'q[s]': 'created_at desc',
+ 'q[name_cont]': 'shirt',
+ 'q[price_gte]': 20,
+ 'q[taxons_id_eq]': 'txn_abc123',
+ });
+ });
+});
diff --git a/packages/sdk/tests/products.test.ts b/packages/sdk/tests/products.test.ts
index d9afefb108..4674c7a507 100644
--- a/packages/sdk/tests/products.test.ts
+++ b/packages/sdk/tests/products.test.ts
@@ -21,7 +21,7 @@ describe('products', () => {
const result = await client.store.products.list({
page: 2,
per_page: 10,
- 'q[name_cont]': 'shirt',
+ name_cont: 'shirt',
});
// MSW handler returns the same fixture regardless of params,
diff --git a/packages/sdk/tests/taxons.test.ts b/packages/sdk/tests/taxons.test.ts
index a9b96451df..5ce4f05c5a 100644
--- a/packages/sdk/tests/taxons.test.ts
+++ b/packages/sdk/tests/taxons.test.ts
@@ -18,7 +18,7 @@ describe('taxons', () => {
it('passes query parameters', async () => {
const result = await client.store.taxons.list({
- 'q[taxonomy_id_eq]': 'tax_1',
+ taxonomy_id_eq: 'tax_1',
});
expect(result.data).toBeDefined();
});