Raw
1 import { TypeList, Tabs, TabsList, TabsTriggerVertical, TabsContent, TabsContentWrapper, Prerequisites, CodeTabs, CodeTab } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Query`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you’ll learn about Query and how to use it to fetch data from modules.
10
11 ## What is Query?
12
13 Query fetches data across modules. It's a set of methods registered in the Medusa container under the `query` key.
14
15 In all resources that can access the [Medusa Container](../medusa-container/page.mdx), such as API routes or workflows, you can resolve Query to fetch data across custom modules and Medusa's Commerce Modules.
16
17 <Note title="Best Practices">
18
19 Prefer Query for read operations (list and retrieve) in API routes. It integrates with the [`validateAndTransformQuery` middleware](#request-query-configurations) and resolves cross-module links automatically.
20
21 </Note>
22
23 ---
24
25 ## Query Example
26
27 For example, create the route `src/api/query/route.ts` with the following content:
28
29 export const exampleHighlights = [
30 ["13", "", "Resolve Query from the Medusa container."],
31 ["15", "graph", "Run a query to retrieve data."],
32 ["16", "entity", "The name of the data model you're querying."],
33 ["17", "fields", "An array of the data model’s properties to retrieve in the result."],
34 ]
35
36 ```ts title="src/api/query/route.ts" highlights={exampleHighlights} collapsibleLines="1-8" expandButtonLabel="Show Imports"
37 import {
38 MedusaRequest,
39 MedusaResponse,
40 } from "@medusajs/framework/http"
41 import {
42 ContainerRegistrationKeys,
43 } from "@medusajs/framework/utils"
44
45 export const GET = async (
46 req: MedusaRequest,
47 res: MedusaResponse
48 ) => {
49 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
50
51 const { data: posts } = await query.graph({
52 entity: "post",
53 fields: ["id", "title"],
54 })
55
56 res.json({ posts })
57 }
58 ```
59
60 In the above example, you resolve Query from the Medusa container using the `ContainerRegistrationKeys.QUERY` (`query`) key.
61
62 Then, you run a query using its `graph` method. This method accepts as a parameter an object with the following required properties:
63
64 - `entity`: The data model's name, as specified in the first parameter of the `model.define` method used for the data model's definition.
65 - `fields`: An array of the data model’s properties to retrieve in the result.
66
67 The method returns an object that has a `data` property, which holds an array of the retrieved data. For example:
68
69 ```json title="Returned Data"
70 {
71 "data": [
72 {
73 "id": "123",
74 "title": "My Post"
75 }
76 ]
77 }
78 ```
79
80 ### Query Usage in Workflows
81
82 To retrieve data with Query in a [workflow](../workflows/page.mdx), use the [useQueryGraphStep](!resources!/references/helper-steps/useQueryGraphStep).
83
84 For example:
85
86 ```ts title="src/workflows/query.ts"
87 import { createWorkflow, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
88 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
89
90 const myWorkflow = createWorkflow(
91 "my-workflow",
92 () => {
93 const { data: posts } = useQueryGraphStep({
94 entity: "post",
95 fields: ["id", "title"],
96 })
97
98 return new WorkflowResponse({
99 posts,
100 })
101 }
102 )
103 ```
104
105 You can learn more about this step in the [useQueryGraphStep](!resources!/references/helper-steps/useQueryGraphStep) reference.
106
107 ---
108
109 ## Querying the Graph
110
111 When you use the `query.graph` method, you're running a query through an internal graph that the Medusa application creates.
112
113 This graph collects data models of all modules in your application, including commerce and custom modules, and identifies relations and links between them.
114
115 ---
116
117 ## Select Specific Fields
118
119 Always list in `fields` the properties you need, rather than passing `*` or `{relation}.*` to retrieve every property.
120
121 Selecting specific fields keeps the query cheaper for the database, the response smaller, and the cached result easier to invalidate. Retrieving all properties also loads relations and computed properties that you may not use.
122
123 For example, instead of retrieving all properties of a post and its author:
124
125 <CodeTabs group="query">
126 <CodeTab label="query.graph" value="query.graph">
127
128 ```ts title="Avoid"
129 const { data: posts } = await query.graph({
130 entity: "post",
131 fields: ["*", "author.*"],
132 })
133 ```
134
135 </CodeTab>
136 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
137
138 ```ts title="Avoid"
139 const { data: posts } = useQueryGraphStep({
140 entity: "post",
141 fields: ["*", "author.*"],
142 })
143 ```
144
145 </CodeTab>
146 </CodeTabs>
147
148 Retrieve only the properties you use:
149
150 <CodeTabs group="query">
151 <CodeTab label="query.graph" value="query.graph">
152
153 ```ts title="Prefer"
154 const { data: posts } = await query.graph({
155 entity: "post",
156 fields: [
157 "id",
158 "title",
159 "author.id",
160 "author.name",
161 ],
162 })
163 ```
164
165 </CodeTab>
166 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
167
168 ```ts title="Prefer"
169 const { data: posts } = useQueryGraphStep({
170 entity: "post",
171 fields: [
172 "id",
173 "title",
174 "author.id",
175 "author.name",
176 ],
177 })
178 ```
179
180 </CodeTab>
181 </CodeTabs>
182
183 ### Avoid Retrieving All Fields of Carts and Orders
184
185 Selecting specific fields matters most for the `cart` and `order` data models, along with their related data models, such as `return` and `order_change`.
186
187 These data models have computed total properties, such as `total`, `subtotal`, and `tax_total`. Medusa calculates these totals in the application, not the database, and it only calculates them when you request at least one total property, or when you pass `*`.
188
189 So, when you pass `*` in `fields`, Medusa:
190
191 - Calculates all totals for every retrieved record.
192 - Loads the relations required for that calculation, including `items`, `credit_lines`, `items.tax_lines`, `items.adjustments`, `shipping_methods`, `shipping_methods.tax_lines`, and `shipping_methods.adjustments`, even if you don't use them.
193
194 For a list of orders, this turns a simple query into a much heavier one. So, request totals only when you display them:
195
196 <CodeTabs group="query">
197 <CodeTab label="query.graph" value="query.graph">
198
199 ```ts title="Prefer"
200 const { data: orders } = await query.graph({
201 entity: "order",
202 fields: [
203 "id",
204 "display_id",
205 "status",
206 "currency_code",
207 // request totals only if you use them:
208 "total",
209 "items.id",
210 "items.title",
211 ],
212 })
213 ```
214
215 </CodeTab>
216 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
217
218 ```ts title="Prefer"
219 const { data: orders } = useQueryGraphStep({
220 entity: "order",
221 fields: [
222 "id",
223 "display_id",
224 "status",
225 "currency_code",
226 // request totals only if you use them:
227 "total",
228 "items.id",
229 "items.title",
230 ],
231 })
232 ```
233
234 </CodeTab>
235 </CodeTabs>
236
237 ---
238
239 ## Retrieve Linked Records
240
241 Retrieve the records of a linked data model by passing in `fields` the data model's name suffixed with the `.{field}` notation, where `{field}` is the property of the linked data model you want to retrieve.
242
243 For example:
244
245 <CodeTabs group="query">
246 <CodeTab label="query.graph" value="query.graph">
247
248 ```ts highlights={[["6"], ["7"]]}
249 const { data: posts } = await query.graph({
250 entity: "post",
251 fields: [
252 "id",
253 "title",
254 "product.id",
255 "product.title",
256 ],
257 })
258 ```
259
260 </CodeTab>
261 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
262
263 ```ts highlights={[["6"], ["7"]]}
264 const { data: posts } = useQueryGraphStep({
265 entity: "post",
266 fields: [
267 "id",
268 "title",
269 "product.id",
270 "product.title",
271 ],
272 })
273 ```
274
275 </CodeTab>
276 </CodeTabs>
277
278 In the example above, you retrieve only the `id` and `title` properties of the `product` linked to a `post`.
279
280 Alternatively, you can pass `.*` to retrieve all properties of the linked data model. Use this only when you need every property, as explained in the [Select Specific Fields](#select-specific-fields) section.
281
282 For example:
283
284 <CodeTabs group="query">
285 <CodeTab label="query.graph" value="query.graph">
286
287 ```ts
288 const { data: posts } = await query.graph({
289 entity: "post",
290 fields: [
291 "id",
292 "title",
293 "product.*",
294 ],
295 })
296 ```
297
298 </CodeTab>
299 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
300
301 ```ts
302 const { data: posts } = useQueryGraphStep({
303 entity: "post",
304 fields: [
305 "id",
306 "title",
307 "product.*",
308 ],
309 })
310 ```
311
312 </CodeTab>
313 </CodeTabs>
314
315 ### Retrieve List Link Records
316
317 If the linked data model has `isList` enabled in the link definition, pass in `fields` the data model's plural name suffixed with `.{field}`.
318
319 For example:
320
321 <CodeTabs group="query">
322 <CodeTab label="query.graph" value="query.graph">
323
324 ```ts highlights={[["6"]]}
325 const { data: posts } = await query.graph({
326 entity: "post",
327 fields: [
328 "id",
329 "title",
330 "products.id",
331 ],
332 })
333 ```
334
335 </CodeTab>
336 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
337
338 ```ts highlights={[["6"]]}
339 const { data: posts } = useQueryGraphStep({
340 entity: "post",
341 fields: [
342 "id",
343 "title",
344 "products.id",
345 ],
346 })
347 ```
348
349 </CodeTab>
350 </CodeTabs>
351
352 In the example above, you retrieve all products linked to a post.
353
354 ### Retrieve Nested Relations
355
356 You can chain relations and links across multiple levels by separating each relation's name with a dot (`.`) in the `fields` array. There's no limit on how deep the chain can be, and a chain can traverse relations within the same module and links between different modules.
357
358 For example, the Fulfillment Module's `ShippingOption` belongs to a `ServiceZone`, which belongs to a `FulfillmentSet`, which [links to a stock location](!resources!/commerce-modules/fulfillment/links-to-other-modules#stock-location-module) in the Stock Location Module. To retrieve a shipping option along with its service zone, fulfillment set, and the fulfillment set's stock location in a single query:
359
360 <CodeTabs group="query">
361 <CodeTab label="query.graph" value="query.graph">
362
363 ```ts highlights={[["5"], ["6"]]}
364 const { data: shippingOptions } = await query.graph({
365 entity: "shipping_option",
366 fields: [
367 "id",
368 "service_zone.fulfillment_set.location.id",
369 "service_zone.fulfillment_set.location.name",
370 ],
371 })
372 ```
373
374 </CodeTab>
375 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
376
377 ```ts highlights={[["5"], ["6"]]}
378 const { data: shippingOptions } = useQueryGraphStep({
379 entity: "shipping_option",
380 fields: [
381 "id",
382 "service_zone.fulfillment_set.location.id",
383 "service_zone.fulfillment_set.location.name",
384 ],
385 })
386 ```
387
388 </CodeTab>
389 </CodeTabs>
390
391 In the example above, each level in the `service_zone.fulfillment_set.location` path is a relation or link that Query resolves in order. Select the properties you need at the last level, as explained in the [Select Specific Fields](#select-specific-fields) section.
392
393 The returned `data` nests each level under the previous one. For example:
394
395 ```json title="Example Result"
396 [{
397 "id": "so_123",
398 "service_zone": {
399 "id": "serzo_123",
400 "fulfillment_set": {
401 "id": "fuset_123",
402 "location": {
403 "id": "sloc_123",
404 "name": "Warehouse"
405 }
406 }
407 }
408 }]
409 ```
410
411 <Note>
412
413 Filtering by a linked data model's property isn't supported at any level of the chain. Refer to the [Apply Filters](#apply-filters) section for details.
414
415 </Note>
416
417 ### Apply Filters and Pagination on Linked Records
418
419 Consider that you want to apply filters or pagination configurations on the product(s) linked to a `post`. To do that, you must query the module link's table instead.
420
421 As mentioned in the [Module Link](../module-links/page.mdx) documentation, Medusa creates a table for your module link. So, not only can you retrieve linked records, but you can also retrieve the records in a module link's table.
422
423 A module link's definition, exported by a file under `src/links`, has a special `entryPoint` property. Use this property when specifying the `entity` property in Query's `graph` method.
424
425 For example:
426
427 export const queryLinkTableHighlights = [
428 ["1", "", "Import the module link."],
429 ["6", "ProductPostLink.entryPoint", "Pass the `entryPoint` property of the link to Query"],
430 ["11", `"product.id"`, "Retrieve the ID of a product record linked to a `Post` record."],
431 ["13", `"post.id"`, "Retrieve the ID of a `Post` record linked to a product record."]
432 ]
433
434 ```ts highlights={queryLinkTableHighlights}
435 import ProductPostLink from "../../../links/product-post"
436
437 // ...
438
439 const { data: productCustoms } = await query.graph({
440 entity: ProductPostLink.entryPoint,
441 fields: [
442 "id",
443 "product_id",
444 "post_id",
445 "product.id",
446 "product.title",
447 "post.id",
448 "post.title",
449 ],
450 pagination: {
451 take: 5,
452 skip: 0,
453 },
454 })
455 ```
456
457 In the object passed to the `graph` method:
458
459 - You pass the `entryPoint` property of the link definition as the value for `entity`. So, Query will retrieve records from the module link's table.
460 - You pass in the `fields` property:
461 - The link table's columns, such as `id`, `product_id`, and `post_id`. You can also select [custom columns](../module-links/custom-columns/page.mdx) that you defined in the link table.
462 - `product.id` and `product.title` to retrieve those properties of a product record linked to a `Post` record.
463 - `post.id` and `post.title` to retrieve those properties of a `Post` record linked to a product record.
464
465 You can then apply any [filters](#apply-filters) or [pagination configurations](#apply-pagination) on the module link's table. For example, you can apply filters on the `product_id`, `post_id`, and any other custom columns you defined in the link table.
466
467 The returned `data` is similar to the following:
468
469 ```json title="Example Result"
470 [{
471 "id": "123",
472 "product_id": "prod_123",
473 "post_id": "123",
474 "product": {
475 "id": "prod_123",
476 "title": "Shirt"
477 },
478 "post": {
479 "id": "123",
480 "title": "My Post"
481 }
482 }]
483 ```
484
485 ---
486
487 ## Apply Filters
488
489 <CodeTabs group="query">
490 <CodeTab label="query.graph" value="query.graph">
491
492 ```ts highlights={[["4"], ["5"], ["6"]]}
493 const { data: posts } = await query.graph({
494 entity: "post",
495 fields: ["id", "title"],
496 filters: {
497 id: "post_123",
498 },
499 })
500 ```
501
502 </CodeTab>
503 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
504
505 ```ts highlights={[["4"], ["5"], ["6"]]}
506 const { data: posts } = useQueryGraphStep({
507 entity: "post",
508 fields: ["id", "title"],
509 filters: {
510 id: "post_123",
511 },
512 })
513 ```
514
515 </CodeTab>
516 </CodeTabs>
517
518 The `query.graph` function accepts a `filters` property. You can use this property to filter retrieved records.
519
520 In the example above, you filter the `post` records by the ID `post_123`.
521
522 You can also filter by multiple values of a property. For example:
523
524 <CodeTabs group="query">
525 <CodeTab label="query.graph" value="query.graph">
526
527 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"], ["9"]]}
528 const { data: posts } = await query.graph({
529 entity: "post",
530 fields: ["id", "title"],
531 filters: {
532 id: [
533 "post_123",
534 "post_321",
535 ],
536 },
537 })
538 ```
539
540 </CodeTab>
541 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
542
543 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"], ["9"]]}
544 const { data: posts } = useQueryGraphStep({
545 entity: "post",
546 fields: ["id", "title"],
547 filters: {
548 id: [
549 "post_123",
550 "post_321",
551 ],
552 },
553 })
554 ```
555
556 </CodeTab>
557 </CodeTabs>
558
559 In the example above, you filter the `post` records by multiple IDs.
560
561 <Note>
562
563 Filters don't apply on fields of linked data models from other modules. Refer to the [Retrieve Linked Records](#retrieve-linked-records) section for an alternative solution.
564
565 </Note>
566
567 ### Advanced Query Filters
568
569 Under the hood, Query uses one of the following methods from the data model's module's service to retrieve records:
570
571 - `listX` if you don't pass [pagination parameters](#apply-pagination). For example, `listPosts`.
572 - `listAndCountX` if you pass pagination parameters. For example, `listAndCountPosts`.
573
574 Both methods accept a filter object that can be used to filter records.
575
576 Those filters don't just allow you to filter by exact values. You can also filter by properties that don't match a value, match multiple values, and other filter types.
577
578 Refer to the [Service Factory Reference](!resources!/service-factory-reference/tips/filtering) for examples of advanced filters. The following sections provide some quick examples.
579
580 #### Filter by Not Matching a Value
581
582 <CodeTabs group="query">
583 <CodeTab label="query.graph" value="query.graph">
584
585 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"]]}
586 const { data: posts } = await query.graph({
587 entity: "post",
588 fields: ["id", "title"],
589 filters: {
590 title: {
591 $ne: null,
592 },
593 },
594 })
595 ```
596
597 </CodeTab>
598 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
599
600 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"]]}
601 const { data: posts } = useQueryGraphStep({
602 entity: "post",
603 fields: ["id", "title"],
604 filters: {
605 title: {
606 $ne: null,
607 },
608 },
609 })
610 ```
611
612 </CodeTab>
613 </CodeTabs>
614
615 In the example above, only posts that have a title are retrieved.
616
617 #### Filter by Not Matching Multiple Values
618
619 <CodeTabs group="query">
620 <CodeTab label="query.graph" value="query.graph">
621
622 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"]]}
623 const { data: posts } = await query.graph({
624 entity: "post",
625 fields: ["id", "title"],
626 filters: {
627 title: {
628 $nin: ["My Post", "Another Post"],
629 },
630 },
631 })
632 ```
633
634 </CodeTab>
635 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
636
637 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"]]}
638 const { data: posts } = useQueryGraphStep({
639 entity: "post",
640 fields: ["id", "title"],
641 filters: {
642 title: {
643 $nin: ["My Post", "Another Post"],
644 },
645 },
646 })
647 ```
648
649 </CodeTab>
650 </CodeTabs>
651
652 In the example above, only posts that don't have the title `My Post` or `Another Post` are retrieved.
653
654 #### Filter by a Range
655
656 <CodeTabs group="query">
657 <CodeTab label="query.graph" value="query.graph">
658
659 ```ts highlights={[["10"], ["11"], ["12"], ["13"], ["14"], ["15"]]}
660 const startToday = new Date()
661 startToday.setHours(0, 0, 0, 0)
662
663 const endToday = new Date()
664 endToday.setHours(23, 59, 59, 59)
665
666 const { data: posts } = await query.graph({
667 entity: "post",
668 fields: ["id", "title"],
669 filters: {
670 published_at: {
671 $gt: startToday,
672 $lt: endToday,
673 },
674 },
675 })
676 ```
677
678 </CodeTab>
679 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
680
681 ```ts highlights={[["10"], ["11"], ["12"], ["13"], ["14"], ["15"]]}
682 const startToday = new Date()
683 startToday.setHours(0, 0, 0, 0)
684
685 const endToday = new Date()
686 endToday.setHours(23, 59, 59, 59)
687
688 const { data: posts } = useQueryGraphStep({
689 entity: "post",
690 fields: ["id", "title"],
691 filters: {
692 published_at: {
693 $gt: startToday,
694 $lt: endToday,
695 },
696 },
697 })
698 ```
699
700 </CodeTab>
701 </CodeTabs>
702
703 In the example above, only posts that were published today are retrieved.
704
705 #### Filter Text by Like Value
706
707 <Note>
708
709 This filter only applies to text-like properties, including `text`, `id`, and `enum` properties.
710
711 </Note>
712
713 <CodeTabs group="query">
714 <CodeTab label="query.graph" value="query.graph">
715
716 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"]]}
717 const { data: posts } = await query.graph({
718 entity: "post",
719 fields: ["id", "title"],
720 filters: {
721 title: {
722 $like: "%My%",
723 },
724 },
725 })
726 ```
727
728 </CodeTab>
729 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
730
731 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"]]}
732 const { data: posts } = useQueryGraphStep({
733 entity: "post",
734 fields: ["id", "title"],
735 filters: {
736 title: {
737 $like: "%My%",
738 },
739 },
740 })
741 ```
742
743 </CodeTab>
744 </CodeTabs>
745
746 In the example above, only posts that have the word `My` in their title are retrieved.
747
748 #### Filter a Relation's Property
749
750 <CodeTabs group="query">
751 <CodeTab label="query.graph" value="query.graph">
752
753 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"]]}
754 const { data: posts } = await query.graph({
755 entity: "post",
756 fields: ["id", "title"],
757 filters: {
758 author: {
759 name: "John",
760 },
761 },
762 })
763 ```
764
765 </CodeTab>
766 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
767
768 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"]]}
769 const { data: posts } = useQueryGraphStep({
770 entity: "post",
771 fields: ["id", "title"],
772 filters: {
773 author: {
774 name: "John",
775 },
776 },
777 })
778 ```
779
780 </CodeTab>
781 </CodeTabs>
782
783 While it's not possible to filter by a linked data model's property, you can filter by a relation's property (that is, the property of a related data model that is defined in the same module).
784
785 In the example above, only posts that have an author with the name `John` are retrieved.
786
787 #### Filter by Relation Property Not Matching Value
788
789 <CodeTabs group="query">
790 <CodeTab label="query.graph" value="query.graph">
791
792 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"], ["9"], ["10"], ["11"], ["12"], ["13"], ["14"], ["15"], ["16"], ["17"], ["18"]]}
793 const { data: posts } = await query.graph({
794 entity: "post",
795 fields: ["id", "title"],
796 filters: {
797 author: {
798 $or: [
799 {
800 name: {
801 $eq: null,
802 },
803 },
804 {
805 name: {
806 $ne: "John",
807 },
808 },
809 ],
810 },
811 },
812 })
813 ```
814
815 </CodeTab>
816 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
817
818 ```ts highlights={[["4"], ["5"], ["6"], ["7"], ["8"], ["9"], ["10"], ["11"], ["12"], ["13"], ["14"], ["15"], ["16"], ["17"], ["18"]]}
819 const { data: posts } = useQueryGraphStep({
820 entity: "post",
821 fields: ["id", "title"],
822 filters: {
823 author: {
824 $or: [
825 {
826 name: {
827 $eq: null,
828 },
829 },
830 {
831 name: {
832 $ne: "John",
833 },
834 },
835 ],
836 },
837 },
838 })
839 ```
840
841 </CodeTab>
842 </CodeTabs>
843
844 To filter by a relationship property whose value doesn't match a specific condition, use an `$or` operator that applies the following conditions:
845
846 1. The relationship's property is not set. This is necessary to exclude posts that don't have an author.
847 2. The relationship's property is not equal to the specific value.
848
849 So, in the example above, the query retrieves posts that either don't have an author or have an author whose name is not "John".
850
851 ---
852
853 ## Apply Pagination
854
855 <CodeTabs group="query">
856 <CodeTab label="query.graph" value="query.graph">
857
858 ```ts highlights={[["8", "skip", "The number of records to skip before fetching the results."], ["9", "take", "The number of records to fetch."]]}
859 const {
860 data: posts,
861 metadata: { count, take, skip } = {},
862 } = await query.graph({
863 entity: "post",
864 fields: ["id", "title"],
865 pagination: {
866 skip: 0,
867 take: 10,
868 },
869 })
870 ```
871
872 </CodeTab>
873 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
874
875 ```ts highlights={[["8", "skip", "The number of records to skip before fetching the results."], ["9", "take", "The number of records to fetch."]]}
876 const {
877 data: posts,
878 metadata,
879 } = useQueryGraphStep({
880 entity: "post",
881 fields: ["id", "title"],
882 pagination: {
883 skip: 0,
884 take: 10,
885 },
886 })
887 ```
888
889 </CodeTab>
890 </CodeTabs>
891
892 The `graph` method's object parameter accepts a `pagination` property to configure the pagination of retrieved records.
893
894 To paginate the returned records, pass the following properties to `pagination`:
895
896 - `skip`: (required to apply pagination) The number of records to skip before fetching the results.
897 - `take`: The number of records to fetch.
898
899 <Note>
900
901 The `metadata` property is only returned when `skip` is provided. Passing `take` without `skip` returns records but no `metadata`.
902
903 </Note>
904
905 When you provide the pagination fields, the `query.graph` method's returned object has a `metadata` property. Its value is an object having the following properties:
906
907 <TypeList types={[
908 {
909 name: "skip",
910 type: "`number`",
911 description: "The number of records skipped."
912 },
913 {
914 name: "take",
915 type: "`number`",
916 description: "The number of records requested to fetch."
917 },
918 {
919 name: "count",
920 type: "`number`",
921 description: "The total number of records."
922 }
923 ]} sectionTitle="Apply Pagination" />
924
925 ### Retrieve Only the Count
926
927 To retrieve only the total count of records without loading any rows, use `{ skip: 0, take: 0 }`. This is useful for building dashboards or checking set size before deciding how to fetch data.
928
929 <CodeTabs group="query">
930 <CodeTab label="query.graph" value="query.graph">
931
932 ```ts
933 const {
934 metadata: { count } = {},
935 } = await query.graph({
936 entity: "post",
937 fields: ["id"],
938 pagination: {
939 skip: 0,
940 take: 0,
941 },
942 })
943 ```
944
945 </CodeTab>
946 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
947
948 ```ts
949 const {
950 metadata,
951 } = useQueryGraphStep({
952 entity: "post",
953 fields: ["id"],
954 pagination: {
955 skip: 0,
956 take: 0,
957 },
958 })
959 ```
960
961 </CodeTab>
962 </CodeTabs>
963
964 This emits a `SELECT COUNT(*)` query and returns `metadata.count` with the total record count. No rows are loaded, keeping memory usage low regardless of catalog size.
965
966 ---
967
968 ### Sort Records
969
970 <CodeTabs group="query">
971 <CodeTab label="query.graph" value="query.graph">
972
973 ```ts highlights={[["5"], ["6"], ["7"]]}
974 const { data: posts } = await query.graph({
975 entity: "post",
976 fields: ["id", "title"],
977 pagination: {
978 order: {
979 name: "DESC",
980 },
981 },
982 })
983 ```
984
985 </CodeTab>
986 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
987
988 ```ts highlights={[["5"], ["6"], ["7"]]}
989 const { data: posts } = useQueryGraphStep({
990 entity: "post",
991 fields: ["id", "title"],
992 pagination: {
993 order: {
994 name: "DESC",
995 },
996 },
997 })
998 ```
999
1000 </CodeTab>
1001 </CodeTabs>
1002
1003 <Note>
1004
1005 Sorting doesn't work on fields of linked data models from other modules.
1006
1007 </Note>
1008
1009 To sort returned records, pass an `order` property to `pagination`.
1010
1011 The `order` property is an object whose keys are property names, and values are either:
1012
1013 - `ASC` to sort records by that property in ascending order.
1014 - `DESC` to sort records by that property in descending order.
1015
1016 <Note title="Sorting in API routes">
1017
1018 The `order` object shown above applies when you call `query.graph` or `useQueryGraphStep` in your code. When clients sort through an API route that uses the [`validateAndTransformQuery` middleware](#request-query-configurations), they pass a top-level `order` query parameter instead. Its value is a string set to the field name to sort by, and the sort order is ascending by default. To sort in descending order, prefix the field name with `-`, as in `?order=-created_at`. Learn more in the [Request Query Configurations](#request-query-configurations) section.
1019
1020 </Note>
1021
1022 ---
1023
1024 ## Retrieve Deleted Records
1025
1026 By default, Query doesn't retrieve deleted records. To retrieve all records including deleted records, you can pass the `withDeleted` property to the `query.graph` method.
1027
1028 <Note>
1029
1030 The `withDeleted` property is available from [Medusa v2.8.5](https://github.com/medusajs/medusa/releases/tag/v2.8.5).
1031
1032 </Note>
1033
1034 For example:
1035
1036 <CodeTabs group="query">
1037 <CodeTab label="query.graph" value="query.graph">
1038
1039 ```ts highlights={[["4", "withDeleted", "Include deleted posts in the results."]]}
1040 const { data: posts } = await query.graph({
1041 entity: "post",
1042 fields: ["id", "title"],
1043 withDeleted: true,
1044 })
1045 ```
1046
1047 </CodeTab>
1048 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1049
1050 ```ts highlights={[["4", "withDeleted", "Include deleted posts in the results."]]}
1051 const { data: posts } = useQueryGraphStep({
1052 entity: "post",
1053 fields: ["id", "title"],
1054 withDeleted: true,
1055 })
1056 ```
1057
1058 </CodeTab>
1059 </CodeTabs>
1060
1061 In the example above, you retrieve all posts, including deleted ones.
1062
1063 ### Retrieve Only Deleted Records
1064
1065 To retrieve only deleted records, you can add a `deleted_at` filter and set its value to not `null`. For example:
1066
1067 export const withDeletedHighlights = [
1068 ["5", "deleted_at", "Filter to retrieve posts whose `deleted_at` property is not `null`."],
1069 ["9", "withDeleted", "Include deleted posts in the results."],
1070 ]
1071
1072 <CodeTabs group="query">
1073 <CodeTab label="query.graph" value="query.graph">
1074
1075 ```ts highlights={withDeletedHighlights}
1076 const { data: posts } = await query.graph({
1077 entity: "post",
1078 fields: ["id", "title"],
1079 filters: {
1080 deleted_at: {
1081 $ne: null,
1082 },
1083 },
1084 withDeleted: true,
1085 })
1086 ```
1087
1088 </CodeTab>
1089 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1090
1091 ```ts highlights={withDeletedHighlights}
1092 const { data: posts } = useQueryGraphStep({
1093 entity: "post",
1094 fields: ["id", "title"],
1095 filters: {
1096 deleted_at: {
1097 $ne: null,
1098 },
1099 },
1100 withDeleted: true,
1101 })
1102 ```
1103
1104 </CodeTab>
1105 </CodeTabs>
1106
1107 In the example above, you retrieve only deleted posts by enabling the `withDeleted` property and adding a filter to only retrieve records where the `deleted_at` property is not `null`.
1108
1109 ---
1110
1111 ## Retrieve Localized Data
1112
1113 <Prerequisites
1114 items={[
1115 {
1116 text: "Medusa v2.12.4 or later",
1117 link: "https://github.com/medusajs/medusa/releases/tag/v2.12.4"
1118 },
1119 {
1120 text: "Translation Module Configured",
1121 link: "!resources!/commerce-modules/translation#configure-translation-module",
1122 },
1123 ]}
1124 />
1125
1126 To retrieve localized data for data models that have translations, pass a `locale` property in the second parameter object of the `query.graph` method.
1127
1128 <CodeTabs group="query">
1129 <CodeTab label="query.graph" value="query.graph">
1130
1131 ```ts highlights={[["7", "locale", "Pass the locale to retrieve localized data."]]}
1132 const { data: products } = await query.graph(
1133 {
1134 entity: "product",
1135 fields: ["id", "title", "description"],
1136 },
1137 {
1138 locale: "fr-FR",
1139 }
1140 )
1141 ```
1142
1143 </CodeTab>
1144 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1145
1146 ```ts highlights={[["5", "locale", "Pass the locale to retrieve localized data."]]}
1147 const { data: products } = useQueryGraphStep({
1148 entity: "product",
1149 fields: ["id", "title", "description"],
1150 options: {
1151 locale: "fr-FR",
1152 },
1153 })
1154 ```
1155
1156 </CodeTab>
1157 </CodeTabs>
1158
1159 The `locale` property is a string representing the locale code following the [IETF BCP 47 standard](https://gist.github.com/typpo/b2b828a35e683b9bf8db91b5404f1bd1).
1160
1161 The returned products will have their `title` and `description` properties in French (`fr-FR`), if translations are available.
1162
1163 Learn more in the [Translation Module](!resources!/commerce-modules/translation) documentation.
1164
1165 ---
1166
1167 ## Configure Query to Throw Error
1168
1169 By default, if Query doesn't find records matching your query, it returns an empty array. You can configure Query to throw an error when no records are found.
1170
1171 The `query.graph` method accepts as a second parameter an object that can have a `throwIfKeyNotFound` property. Its value is a boolean indicating whether to throw an error if no record is found when filtering by IDs. By default, it's `false`.
1172
1173 For example:
1174
1175 <CodeTabs group="query">
1176 <CodeTab label="query.graph" value="query.graph">
1177
1178 ```ts
1179 const { data: posts } = await query.graph({
1180 entity: "post",
1181 fields: ["id", "title"],
1182 filters: {
1183 id: "post_123",
1184 },
1185 }, {
1186 throwIfKeyNotFound: true,
1187 })
1188 ```
1189
1190 </CodeTab>
1191 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1192
1193 ```ts
1194 const { data: posts } = useQueryGraphStep({
1195 entity: "post",
1196 fields: ["id", "title"],
1197 filters: {
1198 id: "post_123",
1199 },
1200 options: {
1201 throwIfKeyNotFound: true,
1202 },
1203 })
1204 ```
1205
1206 </CodeTab>
1207 </CodeTabs>
1208
1209 In the example above, if no post is found with the ID `post_123`, Query throws an error. This is useful to stop execution when a record is expected to exist.
1210
1211 ### Throw Error on Related Data Model
1212
1213 The `throwIfKeyNotFound` option can also be used to throw an error if the ID of a related data model's record (in the same module) is passed in the filters, and the related record doesn't exist.
1214
1215 For example:
1216
1217 <CodeTabs group="query">
1218 <CodeTab label="query.graph" value="query.graph">
1219
1220 ```ts
1221 const { data: posts } = await query.graph({
1222 entity: "post",
1223 fields: ["id", "title", "author.id"],
1224 filters: {
1225 id: "post_123",
1226 author_id: "author_123",
1227 },
1228 }, {
1229 throwIfKeyNotFound: true,
1230 })
1231 ```
1232
1233 </CodeTab>
1234 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1235
1236 ```ts
1237 const { data: posts } = useQueryGraphStep({
1238 entity: "post",
1239 fields: ["id", "title", "author.id"],
1240 filters: {
1241 id: "post_123",
1242 author_id: "author_123",
1243 },
1244 options: {
1245 throwIfKeyNotFound: true,
1246 },
1247 })
1248 ```
1249
1250 </CodeTab>
1251 </CodeTabs>
1252
1253 In the example above, Query throws an error either if no post is found with the ID `post_123` or if it's found but its author ID isn't `author_123`.
1254
1255 In the above example, it's assumed that a post belongs to an author, so it has an `author_id` property. However, this also works in the opposite case, where an author has many posts.
1256
1257 For example:
1258
1259 <CodeTabs group="query">
1260 <CodeTab label="query.graph" value="query.graph">
1261
1262 ```ts
1263 const { data: posts } = await query.graph({
1264 entity: "author",
1265 fields: ["id", "name", "posts.id"],
1266 filters: {
1267 id: "author_123",
1268 posts: {
1269 id: "post_123",
1270 },
1271 },
1272 }, {
1273 throwIfKeyNotFound: true,
1274 })
1275 ```
1276
1277 </CodeTab>
1278 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1279
1280 ```ts
1281 const { data: posts } = useQueryGraphStep({
1282 entity: "author",
1283 fields: ["id", "name", "posts.id"],
1284 filters: {
1285 id: "author_123",
1286 posts: {
1287 id: "post_123",
1288 },
1289 },
1290 options: {
1291 throwIfKeyNotFound: true,
1292 },
1293 })
1294 ```
1295
1296 </CodeTab>
1297 </CodeTabs>
1298
1299 In the example above, Query throws an error if no author is found with the ID `author_123` or if the author is found but doesn't have a post with the ID `post_123`.
1300
1301 ---
1302
1303 ## Cache Query Results
1304
1305 <Prerequisites
1306 items={[
1307 {
1308 text: "Caching Module installed with a provider.",
1309 link: "!resources!/infrastructure-modules/caching#install-the-caching-module"
1310 }
1311 ]}
1312 />
1313
1314 <Note>
1315
1316 Caching options are available from [Medusa v2.11.0](https://github.com/medusajs/medusa/releases/tag/v2.11.0).
1317
1318 </Note>
1319
1320 You can cache Query results to improve performance and reduce database load. To do that, you can pass a `cache` property in the second parameter of the `query.graph` method.
1321
1322 For example, to enable caching for a query:
1323
1324 <CodeTabs group="query">
1325 <CodeTab label="query.graph" value="query.graph">
1326
1327 ```ts highlights={[["6", "enable", "Enable caching for this query."]]}
1328 const { data: products } = await query.graph({
1329 entity: "product",
1330 fields: ["id", "title"],
1331 }, {
1332 cache: {
1333 enable: true,
1334 },
1335 })
1336 ```
1337
1338 </CodeTab>
1339 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1340
1341 ```ts highlights={[["6", "enable", "Enable caching for this query."]]}
1342 const { data: products } = useQueryGraphStep({
1343 entity: "product",
1344 fields: ["id", "title"],
1345 options: {
1346 cache: {
1347 enable: true,
1348 },
1349 },
1350 })
1351 ```
1352
1353 </CodeTab>
1354 </CodeTabs>
1355
1356 In this example, you enable caching of the query's results. The next time the same query is executed, the results are returned from the cache instead of querying the database.
1357
1358 <Note title="Tip">
1359
1360 Refer to the [Caching Module documentation](!resources!/infrastructure-modules/caching/concepts#caching-best-practices) for best practices on caching.
1361
1362 </Note>
1363
1364 ### Cache Properties
1365
1366 `cache` is an object that accepts the following properties:
1367
1368 <TypeList
1369 types={[
1370 {
1371 type: "`boolean` \| `((args: any[]) => boolean \| undefined)`",
1372 name: "enable",
1373 description: "Whether to enable caching of query results. If a function is passed, it receives as a parameter the `query.graph` parameters, and returns a boolean indicating whether caching is enabled.",
1374 defaultValue: "false"
1375 },
1376 {
1377 type: "`string` \| `((args: any[], cachingModule: ICachingModuleService) => string \| Promise<string>)`",
1378 name: "key",
1379 description: "The key to cache the query results with. If no key is provided, the Caching Module will generate the key from the `query.graph` parameters.\n\nIf a function is passed, it receives the following properties:\n\n1. The parameters passed to `query.graph`.\n\n2. The [Caching Module's service](!resources!/references/caching-service), which you can use to perform caching operations.\n\nThe function must return a string indicating the cache key.",
1380 },
1381 {
1382 type: "`string[]` \| `((args: any[]) => string[] \| undefined)`",
1383 name: "tags",
1384 description: "The tags to associate with the cached results. Tags are useful to group related items. If no tag is provided, the Caching Module will generate relevant tags for the entity and its retrieved relations. If tags are provided, they replace the automatically computed tags unless `computeAutomaticTags` is also set.\n\nIf a function is passed, it receives as a parameter the `query.index` parameters, and returns an array of strings indicating the cache tags."
1385 },
1386 {
1387 type: "`boolean`",
1388 name: "computeAutomaticTags",
1389 description: "Whether the automatically computed tags should be applied alongside the ones given in `tags`, rather than `tags` replacing them. Pass custom tags for what the automatic computation cannot see, such as link table rows, relations selected without their `id`, or entities that affect the result without appearing in it, and enable this option to avoid restating every entity the result already exposes.\n\nHas no effect when `tags` is omitted, since tags are computed automatically in that case.",
1390 defaultValue: "`false`"
1391 },
1392 {
1393 type: "`number` \| `((args: any[]) => number \| undefined)`",
1394 name: "ttl",
1395 description: "The time-to-live (TTL) for the cached results, in seconds. If no TTL is provided, the Caching Module Provider will receive the [configured TTL of the Caching Module](!resources!/infrastructure-modules/caching#caching-module-options), or it will use its own default value.\n\nIf a function is passed, it receives as a parameter the `query.graph` parameters, and returns a number indicating the TTL.",
1396 },
1397 {
1398 type: "`boolean` \| `((args: any[]) => boolean \| undefined)`",
1399 name: "autoInvalidate",
1400 description: "Whether to automatically invalidate the cached data when it expires.\n\nIf a function is passed, it receives as a parameter the `query.graph` parameters, and returns a boolean indicating whether to automatically invalidate the cache.",
1401 defaultValue: "`true`"
1402 },
1403 {
1404 type: "`string[]` \| `((args: any[]) => string[] \| undefined)`",
1405 name: "providers",
1406 description: "The IDs of the providers to use for caching. If not provided, the [default Caching Module Provider](!resources!/infrastructure-modules/caching/providers#default-caching-module-provider) is used. If multiple providers are passed, the cache is stored and retrieved in those providers in order.\n\nIf a function is passed, it receives as a parameter the `query.graph` parameters, and return an array of strings indicating the providers to use."
1407 }
1408 ]}
1409 sectionTitle="Cache Properties"
1410 />
1411
1412 ### Set Cache Key
1413
1414 By default, the Caching Module generates a cache key for a query based on the arguments passed to `query.graph`. The cache key is a unique key that the cached result is stored with.
1415
1416 Alternatively, you can set a custom cache key for a query. This is useful if you want to manage invalidating the cache manually.
1417
1418 To set the cache key of a query, pass the `cache.key` option:
1419
1420 <CodeTabs group="query">
1421 <CodeTab label="query.graph" value="query.graph">
1422
1423 ```ts highlights={[["7"]]}
1424 const { data: products } = await query.graph({
1425 entity: "product",
1426 fields: ["id", "title"],
1427 }, {
1428 cache: {
1429 enable: true,
1430 key: "products-123456",
1431 // to disable auto invalidation:
1432 // autoInvalidate: false,
1433 },
1434 })
1435 ```
1436
1437 </CodeTab>
1438 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1439
1440 ```ts highlights={[["7"]]}
1441 const { data: products } = useQueryGraphStep({
1442 entity: "product",
1443 fields: ["id", "title"],
1444 options: {
1445 cache: {
1446 enable: true,
1447 key: "products-123456",
1448 // to disable auto invalidation:
1449 // autoInvalidate: false,
1450 },
1451 },
1452 })
1453 ```
1454
1455 </CodeTab>
1456 </CodeTabs>
1457
1458 In the example above, you cache the query results with the `products-123456` key.
1459
1460 <Note>
1461
1462 You should generate cache keys with the Caching Module service's [computeKey method](!resources!/references/caching-service#computeKey) to ensure that the key is unique and follows best practices.
1463
1464 </Note>
1465
1466 You can also pass a function as the value of `cache.key`:
1467
1468 <Note>
1469
1470 Passing a function to `cache.key` is only supported in `query.graph`, not in `useQueryGraphStep`. This is due to variable-related restrictions in workflows, as explained in the [Data Manipulation in Workflows guide](../workflows/variable-manipulation/page.mdx). You can alternatively create a step that uses Query directly, and use it in the workflow.
1471
1472 </Note>
1473
1474 ```ts highlights={[["7"], ["8"], ["9"], ["10"], ["11"]]}
1475 const { data: products } = await query.graph({
1476 entity: "product",
1477 fields: ["id", "title"],
1478 }, {
1479 cache: {
1480 enable: true,
1481 key: async (args, cachingModuleService) => {
1482 return await cachingModuleService.computeKey({
1483 ...args,
1484 prefix: "products",
1485 })
1486 },
1487 },
1488 })
1489 ```
1490
1491 In the example above, you pass a function to `key`. It accepts two parameters:
1492
1493 1. The arguments of `query.graph` passed as an array.
1494 2. The [Caching Module's service](!resources!/references/caching-service).
1495
1496 You generate the key using the [computeKey method of the Caching Module's service](!resources!/references/caching-service#computeKey). The query results will be cached with that key.
1497
1498 ### Set Cache Tags
1499
1500 By default, the Caching Module generates relevant tags for a query based on the entity and its retrieved relations. Cache tags are useful to group related items together, allowing you to [retrieve](!resources!/references/caching-service#get) or [invalidate](!resources!/references/caching-service#clear) items by common tags.
1501
1502 Alternatively, you can set the cache tags of a query manually. This is useful if you want to manage invalidating the cache manually, or you want to group related cached items with custom tags.
1503
1504 To set the cache tags of a query, pass the `cache.tags` option:
1505
1506 <CodeTabs group="query">
1507 <CodeTab label="query.graph" value="query.graph">
1508
1509 ```ts highlights={[["7"]]}
1510 const { data: products } = await query.graph({
1511 entity: "product",
1512 fields: ["id", "title"],
1513 }, {
1514 cache: {
1515 enable: true,
1516 tags: ["Product:list:*"],
1517 },
1518 })
1519 ```
1520
1521 </CodeTab>
1522 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1523
1524 ```ts highlights={[["7"]]}
1525 const { data: products } = useQueryGraphStep({
1526 entity: "product",
1527 fields: ["id", "title"],
1528 options: {
1529 cache: {
1530 enable: true,
1531 tags: ["Product:list:*"],
1532 // to disable auto invalidation:
1533 // autoInvalidate: false,
1534 },
1535 },
1536 })
1537 ```
1538
1539 </CodeTab>
1540 </CodeTabs>
1541
1542 In the example above, you cache the query results with the `Product:list:*` tag.
1543
1544 <Note>
1545
1546 When you set `cache.tags`, those tags replace the automatically computed ones. To keep the automatic tags and add your own on top, also set `computeAutomaticTags: true`. This is useful when you need to cover entities that automatic computation cannot see, such as link table rows, relations fetched without their `id`, or entities that affect the response without appearing in it.
1547
1548 The cache tag must follow the [Caching Tags Convention](!resources!/infrastructure-modules/caching/concepts#caching-tags-convention) to be automatically invalidated.
1549
1550 </Note>
1551
1552 For example, to add extra tags without losing automatic ones:
1553
1554 ```ts highlights={[["7"], ["8"]]}
1555 const { data: products } = useQueryGraphStep({
1556 entity: "product",
1557 fields: ["id", "title", "variants.id"],
1558 options: {
1559 cache: {
1560 tags: ["LinkProductVariantInventoryItem:list:*"],
1561 computeAutomaticTags: true,
1562 },
1563 },
1564 })
1565 ```
1566
1567 You can also pass a function as the value of `cache.tags`:
1568
1569 <Note>
1570
1571 Passing a function to `cache.tags` is only supported in `query.graph`, not in `useQueryGraphStep`. This is due to variable-related restrictions in workflows, as explained in the [Data Manipulation in Workflows guide](../workflows/variable-manipulation/page.mdx). You can alternatively create a step that uses Query directly, and use it in the workflow.
1572
1573 </Note>
1574
1575 ```ts highlights={[["7"], ["8"], ["9"], ["10"], ["11"], ["12"], ["13"]]}
1576 const { data: products } = await query.graph({
1577 entity: "product",
1578 fields: ["id", "title"],
1579 }, {
1580 cache: {
1581 enable: true,
1582 tags: (args) => {
1583 const collectionId = args[0].filter?.collection_id
1584 return [
1585 ...args,
1586 collectionId ? `ProductCollection:${collectionId}` : undefined,
1587 ]
1588 },
1589 },
1590 })
1591 ```
1592
1593 In the example above, you use a function to determine the cache tags. The function accepts the arguments passed to `query.graph` as an array.
1594
1595 Then, you add the `ProductCollection:id` tag if `collection_id` is passed in the query filters.
1596
1597 ### Set TTL
1598
1599 By default, the Caching Module will pass the [configured time-to-live (TTL)](!resources!/infrastructure-modules/caching#caching-module-options) to the Caching Module Provider when caching data. The Caching Module Provider may also have its own default TTL. The cache isn't invalidated until the configured TTL passes.
1600
1601 Alternatively, you can set a custom TTL for a query. This is useful if you want the cached data to be invalidated sooner or later than the default TTL.
1602
1603 To set the TTL of the cached query results to a custom value, use the `cache.ttl` option:
1604
1605 <CodeTabs group="query">
1606 <CodeTab label="query.graph" value="query.graph">
1607
1608 ```ts highlights={[["7"]]}
1609 const { data: products } = await query.graph({
1610 entity: "product",
1611 fields: ["id", "title"],
1612 }, {
1613 cache: {
1614 enable: true,
1615 ttl: 100, // 100 seconds
1616 },
1617 })
1618 ```
1619
1620 </CodeTab>
1621 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1622
1623 ```ts highlights={[["7"]]}
1624 const { data: products } = useQueryGraphStep({
1625 entity: "product",
1626 fields: ["id", "title"],
1627 options: {
1628 cache: {
1629 enable: true,
1630 ttl: 100, // 100 seconds
1631 },
1632 },
1633 })
1634 ```
1635
1636 </CodeTab>
1637 </CodeTabs>
1638
1639 In the example above, you set the TTL of the cached query result to `100` seconds. It will be invalidated after that time.
1640
1641 You can also pass a function as the value of `cache.ttl`:
1642
1643 <Note>
1644
1645 Passing a function to `cache.ttl` is only supported in `query.graph`, not in `useQueryGraphStep`. This is due to variable-related restrictions in workflows, as explained in the [Data Manipulation in Workflows guide](../workflows/variable-manipulation/page.mdx). You can alternatively create a step that uses Query directly, and use it in the workflow.
1646
1647 </Note>
1648
1649 ```ts highlights={[["10"], ["11"], ["12"]]}
1650 const { data: products } = await query.graph({
1651 entity: "product",
1652 fields: ["id", "title"],
1653 filters: {
1654 id: "prod_123",
1655 },
1656 }, {
1657 cache: {
1658 enable: true,
1659 ttl: (args) => {
1660 return args[0].filters.id === "test" ? 10 : 100
1661 },
1662 },
1663 })
1664 ```
1665
1666 In the example above, you use a function to determine the TTL. The function accepts the arguments passed to `query.graph` as an array.
1667
1668 Then, you set the TTL based on the ID of the product passed in the filters.
1669
1670 ### Set Auto Invalidation
1671
1672 By default, the Caching Module automatically invalidates cached query results when the data changes.
1673
1674 Alternatively, you can disable auto invalidation of cached query results. This is useful if you want to manage invalidating the cache manually.
1675
1676 To configure invalidation behavior, use the `cache.autoInvalidate` option:
1677
1678 <CodeTabs group="query">
1679 <CodeTab label="query.graph" value="query.graph">
1680
1681 ```ts highlights={[["7"]]}
1682 const { data: products } = await query.graph({
1683 entity: "product",
1684 fields: ["id", "title"],
1685 }, {
1686 cache: {
1687 enable: true,
1688 autoInvalidate: false,
1689 },
1690 })
1691 ```
1692
1693 </CodeTab>
1694 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1695
1696 ```ts highlights={[["7"]]}
1697 const { data: products } = useQueryGraphStep({
1698 entity: "product",
1699 fields: ["id", "title"],
1700 options: {
1701 cache: {
1702 enable: true,
1703 autoInvalidate: false,
1704 },
1705 },
1706 })
1707 ```
1708
1709 </CodeTab>
1710 </CodeTabs>
1711
1712 In this example, you disable auto invalidation of the query result. You must [invalidate](!resources!/references/caching-service#clear) the cached data manually.
1713
1714 You can also pass a function as the value of `cache.autoInvalidate`:
1715
1716 <Note>
1717
1718 Passing a function to `cache.autoInvalidate` is only supported in `query.graph`, not in `useQueryGraphStep`. This is due to variable-related restrictions in workflows, as explained in the [Data Manipulation in Workflows guide](../workflows/variable-manipulation/page.mdx). You can alternatively create a step that uses Query directly, and use it in the workflow.
1719
1720 </Note>
1721
1722 ```ts highlights={[["7"], ["8"], ["9"]]}
1723 const { data: products } = await query.graph({
1724 entity: "product",
1725 fields: ["id", "title"],
1726 }, {
1727 cache: {
1728 enable: true,
1729 autoInvalidate: (args) => {
1730 return !args[0].fields.includes("custom_field")
1731 },
1732 },
1733 })
1734 ```
1735
1736 In the example above, you use a function to determine whether to invalidate the cached query result automatically. The function accepts the arguments passed to `query.graph` as an array.
1737
1738 Then, you enable auto-invalidation only if the `fields` passed to `query.graph` don't include `custom_fields`. If this disables auto-invalidation, you must [invalidate](!resources!/references/caching-service#clear) the cached data manually.
1739
1740 <Note title="Tip">
1741
1742 Learn more about automatic invalidation in the [Caching Module documentation](!resources!/infrastructure-modules/caching/concepts#automatic-cache-invalidation).
1743
1744 </Note>
1745
1746 ### Set Caching Provider
1747
1748 By default, the Caching Module uses the [default Caching Module Provider](!resources!/infrastructure-modules/caching/providers#default-caching-module-provider) to cache a query.
1749
1750 Alternatively, you can set the caching provider to use for a query. This is useful if you have multiple caching providers configured, and you want to use a specific one for a query, or you want to specify a fallback provider.
1751
1752 To configure the caching providers, use the `cache.providers` option:
1753
1754 <CodeTabs group="query">
1755 <CodeTab label="query.graph" value="query.graph">
1756
1757 ```ts highlights={[["7"]]}
1758 const { data: products } = await query.graph({
1759 entity: "product",
1760 fields: ["id", "title"],
1761 }, {
1762 cache: {
1763 enable: true,
1764 providers: ["caching-redis", "caching-memcached"],
1765 },
1766 })
1767 ```
1768
1769 </CodeTab>
1770 <CodeTab label="useQueryGraphStep" value="useQueryGraphStep">
1771
1772 ```ts highlights={[["7"]]}
1773 const { data: products } = useQueryGraphStep({
1774 entity: "product",
1775 fields: ["id", "title"],
1776 options: {
1777 cache: {
1778 enable: true,
1779 providers: ["caching-redis", "caching-memcached"],
1780 },
1781 },
1782 })
1783 ```
1784
1785 </CodeTab>
1786 </CodeTabs>
1787
1788 In the example above, you specify the providers with ID `caching-redis` and `caching-memcached` to cache the query results. These IDs must match the IDs of the providers in `medusa-config.ts`.
1789
1790 When you pass multiple providers, the cache is stored and retrieved in those providers in order.
1791
1792 You can also pass a function as the value of `cache.providers`:
1793
1794 <Note>
1795
1796 Passing a function to `cache.providers` is only supported in `query.graph`, not in `useQueryGraphStep`. This is due to variable-related restrictions in workflows, as explained in the [Data Manipulation in Workflows guide](../workflows/variable-manipulation/page.mdx). You can alternatively create a step that uses Query directly, and use it in the workflow.
1797
1798 </Note>
1799
1800 ```ts highlights={[["10"], ["11"], ["12"]]}
1801 const { data: products } = await query.graph({
1802 entity: "product",
1803 fields: ["id", "title"],
1804 filters: {
1805 id: "prod_123",
1806 },
1807 }, {
1808 cache: {
1809 enable: true,
1810 providers: (args) => {
1811 return args[0].filters.id === "test" ? ["caching-redis"] : ["caching-memcached"]
1812 },
1813 },
1814 })
1815 ```
1816
1817 In the example above, you use a function to determine the caching providers. The function accepts the arguments passed to `query.graph` as an array.
1818
1819 Then, you set the providers based on the ID of the product passed in the filters.
1820
1821 ---
1822
1823 ## Request Query Configurations
1824
1825 For API routes that retrieve a single or list of resources, Medusa provides a `validateAndTransformQuery` middleware that:
1826
1827 - Validates accepted query parameters, as explained in [this documentation](../api-routes/validation/page.mdx).
1828 - Parses configurations that are received as query parameters to be passed to Query.
1829
1830 Using this middleware allows you to have default configurations for retrieved fields and relations or pagination, while allowing clients to customize them per request.
1831
1832 ### Step 1: Add Middleware
1833
1834 The first step is to use the `validateAndTransformQuery` middleware on the `GET` route. You add the middleware in `src/api/middlewares.ts`:
1835
1836 ```ts title="src/api/middlewares.ts"
1837 import {
1838 validateAndTransformQuery,
1839 defineMiddlewares,
1840 } from "@medusajs/framework/http"
1841 import { createFindParams } from "@medusajs/medusa/api/utils/validators"
1842
1843 export const GetCustomSchema = createFindParams()
1844
1845 export default defineMiddlewares({
1846 routes: [
1847 {
1848 matcher: "/customs",
1849 method: "GET",
1850 middlewares: [
1851 validateAndTransformQuery(
1852 GetCustomSchema,
1853 {
1854 defaults: [
1855 "id",
1856 "title",
1857 "products.id",
1858 "products.title",
1859 ],
1860 isList: true,
1861 }
1862 ),
1863 ],
1864 },
1865 ],
1866 })
1867 ```
1868
1869 The `validateAndTransformQuery` accepts two parameters:
1870
1871 1. A Zod validation schema for the query parameters, which you can learn more about in the [API Route Validation documentation](../api-routes/validation/page.mdx). Medusa has a `createFindParams` utility that generates a Zod schema that accepts four query parameters:
1872 1. `fields`: The fields and relations to retrieve in the returned resources.
1873 2. `offset`: The number of items to skip before retrieving the returned items.
1874 3. `limit`: The maximum number of items to return.
1875 4. `order`: The fields to order the returned items by in ascending or descending order.
1876 2. A Query configuration object. It accepts the following properties:
1877 1. `defaults`: An array of default fields and relations to retrieve in each resource.
1878 2. `isList`: A boolean indicating whether a list of items is returned in the response.
1879 3. `allowed`: An array of fields and relations allowed to be passed in the `fields` query parameter.
1880 4. `defaultLimit`: A number indicating the default limit to use if no limit is provided. By default, it's `50`.
1881 5. `disallowed`: An array of strings or regular expressions. A string entry matches any field path segment of the same name. A regular expression is tested against each segment and also against the full dotted path, which lets you block a relation at a specific position (for example, `/\.orders(?:\.|$)/` blocks `orders` everywhere except at the root). Any matched field is removed before the query executes, making this a hard security boundary. Learn more in the [Disallowed Fields in API Routes](../api-routes/disallowed-fields/page.mdx) chapter.
1882 6. `storeRelationsLimit`: A number that overrides the application-wide `http.storeRelationsLimit` configuration for this specific route. It limits how many nested relations a caller can expand in a single request. Only applies to routes under the `/store` prefix. Available since [v2.20.0](https://github.com/medusajs/medusa/releases/tag/v2.20.0).
1883
1884 <Note title="Tip">
1885
1886 List specific properties in `defaults` rather than `*` or `{relation}.*`. Every client request that doesn't pass a `fields` query parameter uses these defaults, so an expensive default applies to all of them. Refer to the [Select Specific Fields](#select-specific-fields) section for details.
1887
1888 </Note>
1889
1890 ### Step 2: Use Configurations in API Route
1891
1892 After applying this middleware, your API route now accepts the `fields`, `offset`, `limit`, and `order` query parameters mentioned above.
1893
1894 The middleware transforms these parameters to configurations that you can pass to Query in your API route handler. These configurations are stored in the `queryConfig` parameter of the `MedusaRequest` object.
1895
1896 <Note>
1897
1898 As of [Medusa v2.2.0](https://github.com/medusajs/medusa/releases/tag/v2.2.0), `remoteQueryConfig` has been deprecated in favor of `queryConfig`. Their usage is still the same, only the property name has changed.
1899
1900 </Note>
1901
1902 For example, create the file `src/api/customs/route.ts` with the following content:
1903
1904 export const queryConfigHighlights = [
1905 ["17", "req.queryConfig", "Pass the parsed request Query configurations to the Query graph execution."]
1906 ]
1907
1908 ```ts title="src/api/customs/route.ts"
1909 import {
1910 MedusaRequest,
1911 MedusaResponse,
1912 } from "@medusajs/framework/http"
1913 import {
1914 ContainerRegistrationKeys,
1915 } from "@medusajs/framework/utils"
1916
1917 export const GET = async (
1918 req: MedusaRequest,
1919 res: MedusaResponse
1920 ) => {
1921 const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
1922
1923 const { data: posts } = await query.graph({
1924 entity: "post",
1925 ...req.queryConfig,
1926 })
1927
1928 res.json({ posts: posts })
1929 }
1930 ```
1931
1932 This adds a `GET` API route at `/customs`, which is the API route you added the middleware for.
1933
1934 In the API route, you pass `req.queryConfig` to `query.graph`. `queryConfig` has properties like `fields` and `pagination` to configure the query based on the default values you specified in the middleware, and the query parameters passed in the request.
1935
1936 ### Test it Out
1937
1938 To test it out, start your Medusa application and send a `GET` request to the `/customs` API route. A list of records is retrieved with the specified fields in the middleware.
1939
1940 ```json title="Returned Data"
1941 {
1942 "posts": [
1943 {
1944 "id": "123",
1945 "title": "test"
1946 }
1947 ]
1948 }
1949 ```
1950
1951 Try passing one of the Query configuration parameters, like `fields` or `limit`, and you'll see its impact on the returned result.
1952
1953 <Note>
1954
1955 Learn more about [specifying fields and relations](!api!/store/select-fields-and-relations) and [pagination](!api!/store/pagination) in the API reference.
1956
1957 </Note>