|
1
|
--- |
|
2
|
sidebar_label: "Extend Product" |
|
3
|
tags: |
|
4
|
- product |
|
5
|
- tutorial |
|
6
|
- extend module |
|
7
|
- server |
|
8
|
--- |
|
9
|
|
|
10
|
import { Prerequisites } from "docs-ui" |
|
11
|
|
|
12
|
export const metadata = { |
|
13
|
title: `Extend Product Data Model`, |
|
14
|
} |
|
15
|
|
|
16
|
# {metadata.title} |
|
17
|
|
|
18
|
In this documentation, you'll learn how to extend a data model of the Product Module to add a custom property. |
|
19
|
|
|
20
|
You'll create a `Custom` data model in a module. This data model will have a `custom_name` property, which is the property you want to add to the [Product data model](/references/product/models/Product) defined in the Product Module. |
|
21
|
|
|
22
|
You'll then learn how to: |
|
23
|
|
|
24
|
- Link the `Custom` data model to the `Product` data model. |
|
25
|
- Set the `custom_name` property when a product is created or updated using Medusa's API routes. |
|
26
|
- Retrieve the `custom_name` property with the product's details, in custom or existing API routes. |
|
27
|
|
|
28
|
<Note title="Tip"> |
|
29
|
|
|
30
|
Similar steps can be applied to the `ProductVariant` or `ProductOption` data models. |
|
31
|
|
|
32
|
</Note> |
|
33
|
|
|
34
|
## Step 1: Define Custom Data Model |
|
35
|
|
|
36
|
Consider you have a Hello Module defined in the `/src/modules/hello` directory. |
|
37
|
|
|
38
|
<Note title="Tip"> |
|
39
|
|
|
40
|
If you don't have a module, follow [this guide](!docs!/learn/fundamentals/modules) to create one. |
|
41
|
|
|
42
|
</Note> |
|
43
|
|
|
44
|
To add the `custom_name` property to the `Product` data model, you'll create in the Hello Module a data model that has the `custom_name` property. |
|
45
|
|
|
46
|
Create the file `src/modules/hello/models/custom.ts` with the following content: |
|
47
|
|
|
48
|
```ts title="src/modules/hello/models/custom.ts" |
|
49
|
import { model } from "@medusajs/framework/utils" |
|
50
|
|
|
51
|
export const Custom = model.define("custom", { |
|
52
|
id: model.id().primaryKey(), |
|
53
|
custom_name: model.text(), |
|
54
|
}) |
|
55
|
``` |
|
56
|
|
|
57
|
This creates a `Custom` data model that has the `id` and `custom_name` properties. |
|
58
|
|
|
59
|
<Note title="Tip"> |
|
60
|
|
|
61
|
Learn more about data models in [this guide](!docs!/learn/fundamentals/modules#1-create-data-model). |
|
62
|
|
|
63
|
</Note> |
|
64
|
|
|
65
|
--- |
|
66
|
|
|
67
|
## Step 2: Define Link to Product Data Model |
|
68
|
|
|
69
|
Next, you'll define a module link between the `Custom` and `Product` data model. A module link allows you to form a relation between two data models of separate modules while maintaining module isolation. |
|
70
|
|
|
71
|
<Note title="Tip"> |
|
72
|
|
|
73
|
Learn more about module links in [this guide](!docs!/learn/fundamentals/module-links). |
|
74
|
|
|
75
|
</Note> |
|
76
|
|
|
77
|
Create the file `src/links/product-custom.ts` with the following content: |
|
78
|
|
|
79
|
```ts title="src/links/product-custom.ts" |
|
80
|
import { defineLink } from "@medusajs/framework/utils" |
|
81
|
import HelloModule from "../modules/hello" |
|
82
|
import ProductModule from "@medusajs/medusa/product" |
|
83
|
|
|
84
|
export default defineLink( |
|
85
|
ProductModule.linkable.product, |
|
86
|
HelloModule.linkable.custom |
|
87
|
) |
|
88
|
``` |
|
89
|
|
|
90
|
This defines a link between the `Product` and `Custom` data models. Using this link, you'll later query data across the modules, and link records of each data model. |
|
91
|
|
|
92
|
--- |
|
93
|
|
|
94
|
## Step 3: Generate and Run Migrations |
|
95
|
|
|
96
|
<Prerequisites |
|
97
|
items={[ |
|
98
|
{ |
|
99
|
text: "Module must be registered in medusa-config.js", |
|
100
|
link: "!docs!/learn/fundamentals/modules#4-add-module-to-configurations" |
|
101
|
} |
|
102
|
]} |
|
103
|
/> |
|
104
|
|
|
105
|
To reflect the `Custom` data model in the database, generate a migration that defines the table to be created for it. |
|
106
|
|
|
107
|
Run the following command in your Medusa project's root: |
|
108
|
|
|
109
|
```bash npx2yarn |
|
110
|
npx medusa db:generate helloModuleService |
|
111
|
``` |
|
112
|
|
|
113
|
Where `helloModuleService` is your module's name. |
|
114
|
|
|
115
|
Then, run the `db:migrate` command to run the migrations and create a table in the database for the link between the `Product` and `Custom` data models: |
|
116
|
|
|
117
|
```bash npx2yarn |
|
118
|
npx medusa db:migrate |
|
119
|
``` |
|
120
|
|
|
121
|
A table for the link is now created in the database. You can now retrieve and manage the link between records of the data models. |
|
122
|
|
|
123
|
--- |
|
124
|
|
|
125
|
## Step 4: Consume productsCreated Workflow Hook |
|
126
|
|
|
127
|
When a product is created, you also want to create a `Custom` record and set the `custom_name` property, then create a link between the `Product` and `Custom` records. |
|
128
|
|
|
129
|
To do that, you'll consume the [productsCreated](/references/medusa-workflows/createProductsWorkflow#productscreated) hook of the [createProductsWorkflow](/references/medusa-workflows/createProductsWorkflow). This workflow is executed in the [Create Product Admin API route](!api!/admin/products/create-product) |
|
130
|
|
|
131
|
<Note title="Tip"> |
|
132
|
|
|
133
|
Learn more about workflow hooks in [this guide](!docs!/learn/fundamentals/workflows/workflow-hooks). |
|
134
|
|
|
135
|
</Note> |
|
136
|
|
|
137
|
The API route accepts in its request body an `additional_data` parameter. You can pass in it custom data, which is passed to the workflow hook handler. |
|
138
|
|
|
139
|
### Add custom_name to Additional Data Validation |
|
140
|
|
|
141
|
To pass the `custom_name` in the `additional_data` parameter, you must add a validation rule that tells the Medusa application about this custom property. |
|
142
|
|
|
143
|
Create the file `src/api/middlewares.ts` with the following content: |
|
144
|
|
|
145
|
<Note> |
|
146
|
|
|
147
|
As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`. |
|
148
|
|
|
149
|
</Note> |
|
150
|
|
|
151
|
```ts title="src/api/middlewares.ts" |
|
152
|
import { defineMiddlewares } from "@medusajs/framework/http" |
|
153
|
import { z } from "@medusajs/framework/zod" |
|
154
|
|
|
155
|
export default defineMiddlewares({ |
|
156
|
routes: [ |
|
157
|
{ |
|
158
|
method: "POST", |
|
159
|
matcher: "/admin/products", |
|
160
|
additionalDataValidator: { |
|
161
|
custom_name: z.string().optional(), |
|
162
|
}, |
|
163
|
}, |
|
164
|
], |
|
165
|
}) |
|
166
|
``` |
|
167
|
|
|
168
|
The `additional_data` parameter validation is customized using `defineMiddlewares`. In the routes middleware configuration object, the `additionalDataValidator` property accepts [Zod](https://zod.dev/) validation rules. |
|
169
|
|
|
170
|
In the snippet above, you add a validation rule indicating that `custom_name` is a string that can be passed in the `additional_data` object. |
|
171
|
|
|
172
|
<Note title="Tip"> |
|
173
|
|
|
174
|
Learn more about additional data validation in [this guide](!docs!/learn/fundamentals/api-routes/additional-data). |
|
175
|
|
|
176
|
</Note> |
|
177
|
|
|
178
|
### Create Workflow to Create Custom Record |
|
179
|
|
|
180
|
You'll now create a workflow that will be used in the hook handler. |
|
181
|
|
|
182
|
This workflow will create a `Custom` record, then link it to the product. |
|
183
|
|
|
184
|
Start by creating the step that creates the `Custom` record. Create the file `src/workflows/create-custom-from-product/steps/create-custom.ts` with the following content: |
|
185
|
|
|
186
|
```ts title="src/workflows/create-custom-from-product/steps/create-custom.ts" |
|
187
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
188
|
import HelloModuleService from "../../../modules/hello/service" |
|
189
|
import { HELLO_MODULE } from "../../../modules/hello" |
|
190
|
|
|
191
|
type CreateCustomStepInput = { |
|
192
|
custom_name?: string |
|
193
|
} |
|
194
|
|
|
195
|
export const createCustomStep = createStep( |
|
196
|
"create-custom", |
|
197
|
async (data: CreateCustomStepInput, { container }) => { |
|
198
|
if (!data.custom_name) { |
|
199
|
return |
|
200
|
} |
|
201
|
|
|
202
|
const helloModuleService: HelloModuleService = container.resolve( |
|
203
|
HELLO_MODULE |
|
204
|
) |
|
205
|
|
|
206
|
const custom = await helloModuleService.createCustoms(data) |
|
207
|
|
|
208
|
return new StepResponse(custom, custom) |
|
209
|
}, |
|
210
|
async (custom, { container }) => { |
|
211
|
const helloModuleService: HelloModuleService = container.resolve( |
|
212
|
HELLO_MODULE |
|
213
|
) |
|
214
|
|
|
215
|
await helloModuleService.deleteCustoms(custom.id) |
|
216
|
} |
|
217
|
) |
|
218
|
``` |
|
219
|
|
|
220
|
In the step, you resolve the Hello Module's main service and create a `Custom` record. |
|
221
|
|
|
222
|
In the compensation function that undoes the step's actions in case of an error, you delete the created record. |
|
223
|
|
|
224
|
<Note title="Tip"> |
|
225
|
|
|
226
|
Learn more about compensation functions in [this guide](!docs!/learn/fundamentals/workflows/compensation-function). |
|
227
|
|
|
228
|
</Note> |
|
229
|
|
|
230
|
Then, create the workflow at `src/workflows/create-custom-from-product/index.ts` with the following content: |
|
231
|
|
|
232
|
```ts title="src/workflows/create-custom-from-product/index.ts" collapsibleLines="1-7" expandButtonLabel="Show Imports" |
|
233
|
import { createWorkflow, transform, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk" |
|
234
|
import { ProductDTO } from "@medusajs/framework/types" |
|
235
|
import { createRemoteLinkStep } from "@medusajs/medusa/core-flows" |
|
236
|
import { Modules } from "@medusajs/framework/utils" |
|
237
|
import { HELLO_MODULE } from "../../modules/hello" |
|
238
|
import { createCustomStep } from "./steps/create-custom" |
|
239
|
|
|
240
|
export type CreateCustomFromProductWorkflowInput = { |
|
241
|
product: ProductDTO |
|
242
|
additional_data?: { |
|
243
|
custom_name?: string |
|
244
|
} |
|
245
|
} |
|
246
|
|
|
247
|
export const createCustomFromProductWorkflow = createWorkflow( |
|
248
|
"create-custom-from-product", |
|
249
|
(input: CreateCustomFromProductWorkflowInput) => { |
|
250
|
const customName = transform( |
|
251
|
{ |
|
252
|
input, |
|
253
|
}, |
|
254
|
(data) => data.input.additional_data.custom_name || "" |
|
255
|
) |
|
256
|
|
|
257
|
const custom = createCustomStep({ |
|
258
|
custom_name: customName, |
|
259
|
}) |
|
260
|
|
|
261
|
when(({ custom }), ({ custom }) => custom !== undefined) |
|
262
|
.then(() => { |
|
263
|
createRemoteLinkStep([{ |
|
264
|
[Modules.PRODUCT]: { |
|
265
|
product_id: input.product.id, |
|
266
|
}, |
|
267
|
[HELLO_MODULE]: { |
|
268
|
custom_id: custom.id, |
|
269
|
}, |
|
270
|
}]) |
|
271
|
}) |
|
272
|
|
|
273
|
return new WorkflowResponse({ |
|
274
|
custom, |
|
275
|
}) |
|
276
|
} |
|
277
|
) |
|
278
|
``` |
|
279
|
|
|
280
|
The workflow accepts as an input the created product and the `additional_data` parameter passed in the request. This is the same input that the `productsCreated` hook accepts. |
|
281
|
|
|
282
|
In the workflow, you: |
|
283
|
|
|
284
|
1. Use `transform` to get the value of `custom_name` based on whether it's set in `additional_data`. Learn more about why you can't use conditional operators in a workflow without using `transform` in [this guide](!docs!/learn/fundamentals/workflows/conditions#why-if-conditions-arent-allowed-in-workflows). |
|
285
|
2. Create the `Custom` record using the `createCustomStep`. |
|
286
|
3. Use `when-then` to link the product to the `Custom` record if it was created. Learn more about why you can't use if-then conditions in a workflow without using `when-then` in [this guide](!docs!/learn/fundamentals/workflows/conditions#why-if-conditions-arent-allowed-in-workflows). |
|
287
|
|
|
288
|
You'll next execute the workflow in the hook handler. |
|
289
|
|
|
290
|
### Consume Workflow Hook |
|
291
|
|
|
292
|
You can now consume the `productsCreated` hook, which is executed in the `createProductsWorkflow` after the product is created. |
|
293
|
|
|
294
|
To consume the hook, create the file `src/workflows/hooks/product-created.ts` with the following content: |
|
295
|
|
|
296
|
```ts title="src/workflows/hooks/product-created.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports" |
|
297
|
import { createProductsWorkflow } from "@medusajs/medusa/core-flows" |
|
298
|
import { |
|
299
|
createCustomFromProductWorkflow, |
|
300
|
CreateCustomFromProductWorkflowInput, |
|
301
|
} from "../create-custom-from-product" |
|
302
|
|
|
303
|
createProductsWorkflow.hooks.productsCreated( |
|
304
|
async ({ products, additional_data }, { container }) => { |
|
305
|
const workflow = createCustomFromProductWorkflow(container) |
|
306
|
|
|
307
|
for (const product of products) { |
|
308
|
await workflow.run({ |
|
309
|
input: { |
|
310
|
product, |
|
311
|
additional_data, |
|
312
|
} as CreateCustomFromProductWorkflowInput, |
|
313
|
}) |
|
314
|
} |
|
315
|
} |
|
316
|
) |
|
317
|
``` |
|
318
|
|
|
319
|
The hook handler executes the `createCustomFromProductWorkflow`, passing it its input. |
|
320
|
|
|
321
|
### Test it Out |
|
322
|
|
|
323
|
To test it out, send a `POST` request to `/admin/products` to create a product, passing `custom_name` in `additional_data`: |
|
324
|
|
|
325
|
```bash |
|
326
|
curl -X POST 'localhost:9000/admin/products' \ |
|
327
|
-H 'Content-Type: application/json' \ |
|
328
|
-H 'Authorization: Bearer {token}' \ |
|
329
|
--data '{ |
|
330
|
"title": "Shoes", |
|
331
|
"options": [ |
|
332
|
{ |
|
333
|
"title": "Default option", |
|
334
|
"values": ["Default option value"] |
|
335
|
} |
|
336
|
], |
|
337
|
"shipping_profile_id": "{shipping_profile_id}", |
|
338
|
"additional_data": { |
|
339
|
"custom_name": "test" |
|
340
|
} |
|
341
|
}' |
|
342
|
``` |
|
343
|
|
|
344
|
Make sure to replace `{token}` with an admin user's JWT token. Learn how to retrieve it in the [API reference](!api!/admin#1-bearer-authorization-with-jwt-tokens). |
|
345
|
|
|
346
|
Also, make sure to replace `{shipping_profile_id}` with an existing shipping profile's ID. You can retrieve one either from the Medusa Admin dashboard or using the [List Shipping Profiles API Route](!api!/admin/shipping-profiles/list-shipping-profiles). |
|
347
|
|
|
348
|
The request will return the product's details. You'll learn how to retrieve the `custom_name` property with the product's details in the next section. |
|
349
|
|
|
350
|
--- |
|
351
|
|
|
352
|
## Step 5: Retrieve custom_name with Product Details |
|
353
|
|
|
354
|
When you extend an existing data model through links, you also want to retrieve the custom properties with the data model. |
|
355
|
|
|
356
|
### Retrieve in API Routes |
|
357
|
|
|
358
|
To retrieve the `custom_name` property when you're retrieving the product through API routes, such as the [Get Product API Route](!api!/admin/products/get-a-product), pass in the `fields` query parameter `+custom.*`, which retrieves the linked `Custom` record's details. |
|
359
|
|
|
360
|
<Note title="Tip"> |
|
361
|
|
|
362
|
The `+` prefix in `+custom.*` indicates that the relation should be retrieved with the default product fields. Learn more about selecting fields and relations in the [API reference](!api!/admin/select-fields-and-relations). |
|
363
|
|
|
364
|
</Note> |
|
365
|
|
|
366
|
For example: |
|
367
|
|
|
368
|
```bash |
|
369
|
curl 'localhost:9000/admin/products/{product_id}?fields=+custom.*' \ |
|
370
|
-H 'Authorization: Bearer {token}' |
|
371
|
``` |
|
372
|
|
|
373
|
Make sure to replace `{product_id}` with the product's ID, and `{token}` with an admin user's JWT token. |
|
374
|
|
|
375
|
Among the returned `product` object, you'll find a `custom` property which holds the details of the linked `Custom` record: |
|
376
|
|
|
377
|
```json |
|
378
|
{ |
|
379
|
"product": { |
|
380
|
// ... |
|
381
|
"custom": { |
|
382
|
"id": "01J9NP7ANXDZ0EAYF0956ZE1ZA", |
|
383
|
"custom_name": "test", |
|
384
|
"created_at": "2024-10-08T09:09:06.877Z", |
|
385
|
"updated_at": "2024-10-08T09:09:06.877Z", |
|
386
|
"deleted_at": null |
|
387
|
} |
|
388
|
} |
|
389
|
} |
|
390
|
``` |
|
391
|
|
|
392
|
### Retrieve in Store API Routes |
|
393
|
|
|
394
|
The Store API routes only return the fields in their allowed fields, and `custom` isn't one of them, so Medusa removes it from the response without an error. To retrieve it through a route like the [List Products API Route](!api!/store/products/list-products), add it to the route's allowed fields in `src/api/middlewares.ts`: |
|
395
|
|
|
396
|
```ts title="src/api/middlewares.ts" |
|
397
|
import { allowFields } from "@medusajs/framework/http" |
|
398
|
|
|
399
|
export default defineMiddlewares({ |
|
400
|
routes: [ |
|
401
|
// ... |
|
402
|
{ |
|
403
|
matcher: "/store/products", |
|
404
|
middlewares: [allowFields("custom")], |
|
405
|
}, |
|
406
|
], |
|
407
|
}) |
|
408
|
``` |
|
409
|
|
|
410
|
<Note> |
|
411
|
|
|
412
|
`allowFields` is available since Medusa [v2.21.0](https://github.com/medusajs/medusa/releases/tag/v2.21.0). In earlier versions, write the middleware yourself, as explained in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields#how-to-override-allowed-fields-of-medusas-api-routes) documentation. |
|
413
|
|
|
414
|
</Note> |
|
415
|
|
|
416
|
You can then pass `+custom.*` in the `fields` query parameter of the Store Product API routes. |
|
417
|
|
|
418
|
<Note title="Important"> |
|
419
|
|
|
420
|
The middleware must be global, so don't set a `method` property in the route object. Medusa runs a middleware scoped to a method after it validates the `fields` query parameter, so it has no effect. |
|
421
|
|
|
422
|
</Note> |
|
423
|
|
|
424
|
Learn more in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields) documentation. |
|
425
|
|
|
426
|
### Retrieve using Query |
|
427
|
|
|
428
|
You can also retrieve the `Custom` record linked to a product in your code using [Query](!docs!/learn/fundamentals/query). |
|
429
|
|
|
430
|
For example: |
|
431
|
|
|
432
|
```ts |
|
433
|
const { data: [product] } = await query.graph({ |
|
434
|
entity: "product", |
|
435
|
fields: ["*", "custom.*"], |
|
436
|
filters: { |
|
437
|
id: product_id, |
|
438
|
}, |
|
439
|
}) |
|
440
|
``` |
|
441
|
|
|
442
|
Learn more about how to use Query in [this guide](!docs!/learn/fundamentals/query). |
|
443
|
|
|
444
|
--- |
|
445
|
|
|
446
|
## Step 6: Consume productsUpdated Workflow Hook |
|
447
|
|
|
448
|
Similar to the `productsCreated` hook, you'll consume the [productsUpdated](/references/medusa-workflows/updateProductsWorkflow#productsUpdated) hook of the [updateProductsWorkflow](/references/medusa-workflows/updateProductsWorkflow) to update `custom_name` when the product is updated. |
|
449
|
|
|
450
|
The `updateProductsWorkflow` is executed by the [Update Product API route](!api!/admin/products/update-a-product), which accepts the `additional_data` parameter to pass custom data to the hook. |
|
451
|
|
|
452
|
### Add custom_name to Additional Data Validation |
|
453
|
|
|
454
|
To allow passing `custom_name` in the `additional_data` parameter of the update product route, add in `src/api/middlewares.ts` a new route middleware configuration object: |
|
455
|
|
|
456
|
<Note> |
|
457
|
|
|
458
|
As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`. |
|
459
|
|
|
460
|
</Note> |
|
461
|
|
|
462
|
```ts title="src/api/middlewares.ts" |
|
463
|
import { defineMiddlewares } from "@medusajs/framework/http" |
|
464
|
import { z } from "@medusajs/framework/zod" |
|
465
|
|
|
466
|
export default defineMiddlewares({ |
|
467
|
routes: [ |
|
468
|
// ... |
|
469
|
{ |
|
470
|
method: "POST", |
|
471
|
matcher: "/admin/products/:id", |
|
472
|
additionalDataValidator: { |
|
473
|
custom_name: z.string().nullish(), |
|
474
|
}, |
|
475
|
}, |
|
476
|
], |
|
477
|
}) |
|
478
|
``` |
|
479
|
|
|
480
|
The validation schema is the similar to that of the Create Product API route, except you can pass a `null` value for `custom_name` to remove or unset the `custom_name`'s value. |
|
481
|
|
|
482
|
### Create Workflow to Update Custom Record |
|
483
|
|
|
484
|
Next, you'll create a workflow that creates, updates, or deletes `Custom` records based on the provided `additional_data` parameter: |
|
485
|
|
|
486
|
1. If `additional_data.custom_name` is set and it's `null`, the `Custom` record linked to the product is deleted. |
|
487
|
2. If `additional_data.custom_name` is set and the product doesn't have a linked `Custom` record, a new record is created and linked to the product. |
|
488
|
3. If `additional_data.custom_name` is set and the product has a linked `Custom` record, the `custom_name` property of the `Custom` record is updated. |
|
489
|
|
|
490
|
Start by creating the step that updates a `Custom` record. Create the file `src/workflows/update-custom-from-product/steps/update-custom.ts` with the following content: |
|
491
|
|
|
492
|
```ts title="src/workflows/update-custom-from-product/steps/update-custom.ts" |
|
493
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
494
|
import { HELLO_MODULE } from "../../../modules/hello" |
|
495
|
import HelloModuleService from "../../../modules/hello/service" |
|
496
|
|
|
497
|
type UpdateCustomStepInput = { |
|
498
|
id: string |
|
499
|
custom_name: string |
|
500
|
} |
|
501
|
|
|
502
|
export const updateCustomStep = createStep( |
|
503
|
"update-custom", |
|
504
|
async ({ id, custom_name }: UpdateCustomStepInput, { container }) => { |
|
505
|
const helloModuleService: HelloModuleService = container.resolve( |
|
506
|
HELLO_MODULE |
|
507
|
) |
|
508
|
|
|
509
|
const prevData = await helloModuleService.retrieveCustom(id) |
|
510
|
|
|
511
|
const custom = await helloModuleService.updateCustoms({ |
|
512
|
id, |
|
513
|
custom_name, |
|
514
|
}) |
|
515
|
|
|
516
|
return new StepResponse(custom, prevData) |
|
517
|
}, |
|
518
|
async (prevData, { container }) => { |
|
519
|
const helloModuleService: HelloModuleService = container.resolve( |
|
520
|
HELLO_MODULE |
|
521
|
) |
|
522
|
|
|
523
|
await helloModuleService.updateCustoms(prevData) |
|
524
|
} |
|
525
|
) |
|
526
|
``` |
|
527
|
|
|
528
|
In this step, you update a `Custom` record. In the compensation function, you revert the update. |
|
529
|
|
|
530
|
Next, you'll create the step that deletes a `Custom` record. Create the file `src/workflows/update-custom-from-product/steps/delete-custom.ts` with the following content: |
|
531
|
|
|
532
|
```ts title="src/workflows/update-custom-from-product/steps/delete-custom.ts" collapsibleLines="1-6" expandButtonLabel="Show Imports" |
|
533
|
import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk" |
|
534
|
import { Custom } from "../../../modules/hello/models/custom" |
|
535
|
import { InferTypeOf } from "@medusajs/framework/types" |
|
536
|
import HelloModuleService from "../../../modules/hello/service" |
|
537
|
import { HELLO_MODULE } from "../../../modules/hello" |
|
538
|
|
|
539
|
type DeleteCustomStepInput = { |
|
540
|
custom: InferTypeOf<typeof Custom> |
|
541
|
} |
|
542
|
|
|
543
|
export const deleteCustomStep = createStep( |
|
544
|
"delete-custom", |
|
545
|
async ({ custom }: DeleteCustomStepInput, { container }) => { |
|
546
|
const helloModuleService: HelloModuleService = container.resolve( |
|
547
|
HELLO_MODULE |
|
548
|
) |
|
549
|
|
|
550
|
await helloModuleService.deleteCustoms(custom.id) |
|
551
|
|
|
552
|
return new StepResponse(custom, custom) |
|
553
|
}, |
|
554
|
async (custom, { container }) => { |
|
555
|
const helloModuleService: HelloModuleService = container.resolve( |
|
556
|
HELLO_MODULE |
|
557
|
) |
|
558
|
|
|
559
|
await helloModuleService.createCustoms(custom) |
|
560
|
} |
|
561
|
) |
|
562
|
``` |
|
563
|
|
|
564
|
In this step, you delete a `Custom` record. In the compensation function, you create it again. |
|
565
|
|
|
566
|
Finally, you'll create the workflow. Create the file `src/workflows/update-custom-from-product/index.ts` with the following content: |
|
567
|
|
|
568
|
```ts title="src/workflows/update-custom-from-product/index.ts" collapsibleLines="1-9" expandButtonLabel="Show Imports" |
|
569
|
import { ProductDTO } from "@medusajs/framework/types" |
|
570
|
import { createWorkflow, when, WorkflowResponse } from "@medusajs/framework/workflows-sdk" |
|
571
|
import { createRemoteLinkStep, dismissRemoteLinkStep, useQueryGraphStep } from "@medusajs/medusa/core-flows" |
|
572
|
import { createCustomStep } from "../create-custom-from-cart/steps/create-custom" |
|
573
|
import { Modules } from "@medusajs/framework/utils" |
|
574
|
import { HELLO_MODULE } from "../../modules/hello" |
|
575
|
import { deleteCustomStep } from "./steps/delete-custom" |
|
576
|
import { updateCustomStep } from "./steps/update-custom" |
|
577
|
|
|
578
|
export type UpdateCustomFromProductStepInput = { |
|
579
|
product: ProductDTO |
|
580
|
additional_data?: { |
|
581
|
custom_name?: string | null |
|
582
|
} |
|
583
|
} |
|
584
|
|
|
585
|
export const updateCustomFromProductWorkflow = createWorkflow( |
|
586
|
"update-custom-from-product", |
|
587
|
(input: UpdateCustomFromProductStepInput) => { |
|
588
|
const { data: products } = useQueryGraphStep({ |
|
589
|
entity: "product", |
|
590
|
fields: ["custom.*"], |
|
591
|
filters: { |
|
592
|
id: input.product.id, |
|
593
|
}, |
|
594
|
}) |
|
595
|
|
|
596
|
// TODO create, update, or delete Custom record |
|
597
|
} |
|
598
|
) |
|
599
|
``` |
|
600
|
|
|
601
|
The workflow accepts the same input as the `productsUpdated` workflow hook handler would. |
|
602
|
|
|
603
|
In the workflow, you retrieve the product's linked `Custom` record using Query. |
|
604
|
|
|
605
|
Next, replace the `TODO` with the following: |
|
606
|
|
|
607
|
```ts title="src/workflows/update-custom-from-product/index.ts" |
|
608
|
const created = when( |
|
609
|
"create-product-custom-link", |
|
610
|
{ |
|
611
|
input, |
|
612
|
products, |
|
613
|
}, (data) => |
|
614
|
!data.products[0].custom && |
|
615
|
data.input.additional_data?.custom_name?.length > 0 |
|
616
|
) |
|
617
|
.then(() => { |
|
618
|
const custom = createCustomStep({ |
|
619
|
custom_name: input.additional_data.custom_name, |
|
620
|
}) |
|
621
|
|
|
622
|
createRemoteLinkStep([{ |
|
623
|
[Modules.PRODUCT]: { |
|
624
|
product_id: input.product.id, |
|
625
|
}, |
|
626
|
[HELLO_MODULE]: { |
|
627
|
custom_id: custom.id, |
|
628
|
}, |
|
629
|
}]) |
|
630
|
|
|
631
|
return custom |
|
632
|
}) |
|
633
|
|
|
634
|
// TODO update, or delete Custom record |
|
635
|
``` |
|
636
|
|
|
637
|
Using `when-then`, you check if the product doesn't have a linked `Custom` record and the `custom_name` property is set. If so, you create a `Custom` record and link it to the product. |
|
638
|
|
|
639
|
To create the `Custom` record, you use the `createCustomStep` you created in an earlier section. |
|
640
|
|
|
641
|
Next, replace the new `TODO` with the following: |
|
642
|
|
|
643
|
```ts title="src/workflows/update-custom-from-product/index.ts" |
|
644
|
const deleted = when( |
|
645
|
"delete-product-custom-link", |
|
646
|
{ |
|
647
|
input, |
|
648
|
products, |
|
649
|
}, (data) => |
|
650
|
data.products[0].custom && ( |
|
651
|
data.input.additional_data?.custom_name === null || |
|
652
|
data.input.additional_data?.custom_name.length === 0 |
|
653
|
) |
|
654
|
) |
|
655
|
.then(() => { |
|
656
|
deleteCustomStep({ |
|
657
|
custom: products[0].custom, |
|
658
|
}) |
|
659
|
|
|
660
|
dismissRemoteLinkStep({ |
|
661
|
[HELLO_MODULE]: { |
|
662
|
custom_id: products[0].custom.id, |
|
663
|
}, |
|
664
|
}) |
|
665
|
|
|
666
|
return products[0].custom.id |
|
667
|
}) |
|
668
|
|
|
669
|
// TODO delete Custom record |
|
670
|
``` |
|
671
|
|
|
672
|
Using `when-then`, you check if the product has a linked `Custom` record and `custom_name` is `null` or an empty string. If so, you delete the linked `Custom` record and dismiss its links. |
|
673
|
|
|
674
|
Finally, replace the new `TODO` with the following: |
|
675
|
|
|
676
|
```ts title="src/workflows/update-custom-from-product/index.ts" |
|
677
|
const updated = when({ |
|
678
|
input, |
|
679
|
products, |
|
680
|
}, (data) => data.products[0].custom && data.input.additional_data?.custom_name?.length > 0) |
|
681
|
.then(() => { |
|
682
|
return updateCustomStep({ |
|
683
|
id: products[0].custom.id, |
|
684
|
custom_name: input.additional_data.custom_name, |
|
685
|
}) |
|
686
|
}) |
|
687
|
|
|
688
|
return new WorkflowResponse({ |
|
689
|
created, |
|
690
|
updated, |
|
691
|
deleted, |
|
692
|
}) |
|
693
|
``` |
|
694
|
|
|
695
|
Using `when-then`, you check if the product has a linked `Custom` record and `custom_name` is passed in the `additional_data`. If so, you update the linked `Custom` record. |
|
696
|
|
|
697
|
You return in the workflow response the created, updated, and deleted `Custom` record. |
|
698
|
|
|
699
|
### Consume productsUpdated Workflow Hook |
|
700
|
|
|
701
|
You can now consume the `productsUpdated` and execute the workflow you created. |
|
702
|
|
|
703
|
Create the file `src/workflows/hooks/product-updated.ts` with the following content: |
|
704
|
|
|
705
|
```ts title="src/workflows/hooks/product-updated.ts" |
|
706
|
import { updateProductsWorkflow } from "@medusajs/medusa/core-flows" |
|
707
|
import { |
|
708
|
UpdateCustomFromProductStepInput, |
|
709
|
updateCustomFromProductWorkflow, |
|
710
|
} from "../update-custom-from-product" |
|
711
|
|
|
712
|
updateProductsWorkflow.hooks.productsUpdated( |
|
713
|
async ({ products, additional_data }, { container }) => { |
|
714
|
const workflow = updateCustomFromProductWorkflow(container) |
|
715
|
|
|
716
|
for (const product of products) { |
|
717
|
await workflow.run({ |
|
718
|
input: { |
|
719
|
product, |
|
720
|
additional_data, |
|
721
|
} as UpdateCustomFromProductStepInput, |
|
722
|
}) |
|
723
|
} |
|
724
|
} |
|
725
|
) |
|
726
|
``` |
|
727
|
|
|
728
|
In the workflow hook handler, you execute the workflow, passing it the hook's input. |
|
729
|
|
|
730
|
### Test it Out |
|
731
|
|
|
732
|
To test it out, send a `POST` request to `/admin/products/:id` to update a product, passing `custom_name` in `additional_data`: |
|
733
|
|
|
734
|
```bash |
|
735
|
curl -X POST 'localhost:9000/admin/products/{product_id}?fields=+custom.*' \ |
|
736
|
-H 'Content-Type: application/json' \ |
|
737
|
-H 'Authorization: Bearer {token}' \ |
|
738
|
--data '{ |
|
739
|
"additional_data": { |
|
740
|
"custom_name": "test 2" |
|
741
|
} |
|
742
|
}' |
|
743
|
``` |
|
744
|
|
|
745
|
Make sure to replace `{product_id}` with the product's ID, and `{token}` with the JWT token of an admin user. |
|
746
|
|
|
747
|
The request will return the product's details with the updated `custom` linked record. |