Raw
1 import { Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Guide: Sync Brands from Medusa to Third-Party`,
5 }
6
7 # {metadata.title}
8
9 In the [previous chapter](../service/page.mdx), you created a CMS Module that integrates a dummy third-party system. You can now perform actions using that module within your custom flows.
10
11 In another previous chapter, you [added a workflow](../../custom-features/workflow/page.mdx) that creates a brand. After integrating the CMS, you want to sync that brand to the third-party system as well.
12
13 Medusa has an event system that emits events when an operation is performed. It allows you to listen to those events and perform an asynchronous action in a function called a [subscriber](../../../fundamentals/events-and-subscribers/page.mdx). This is useful to perform actions that aren't integral to the original flow, such as syncing data to a third-party system.
14
15 <Note>
16
17 Learn more about Medusa's event system and subscribers in [this chapter](../../../fundamentals/events-and-subscribers/page.mdx).
18
19 </Note>
20
21 In this chapter, you'll modify the `createBrandWorkflow` you created before to emit a custom event that indicates a brand was created. Then, you'll listen to that event in a subscriber to sync the brand to the third-party CMS. You'll implement the sync logic within a workflow that you execute in the subscriber.
22
23 <Prerequisites
24 items={[
25 {
26 text: "createBrandWorkflow",
27 link: "/learn/customization/custom-features/workflow"
28 },
29 {
30 text: "CMS Module",
31 link: "/learn/customization/integrate-systems/service"
32 }
33 ]}
34 />
35
36 ## 1. Emit Event in createBrandWorkflow
37
38 Since syncing the brand to the third-party system isn't integral to creating a brand, you'll emit a custom event indicating that a brand was created.
39
40 Medusa provides an `emitEventStep` that allows you to emit an event in your workflows. So, in the `createBrandWorkflow` defined in `src/workflows/create-brand.ts`, use the `emitEventStep` helper step after the `createBrandStep`:
41
42 export const eventHighlights = [
43 ["13", "emitEventStep", "Emit an event."],
44 ["14", "eventName", "The event's name."],
45 ["15", "data", "The data to pass in the payload."]
46 ]
47
48 ```ts title="src/workflows/create-brand.ts" highlights={eventHighlights}
49 // other imports...
50 import {
51 emitEventStep,
52 } from "@medusajs/medusa/core-flows"
53
54 // ...
55
56 export const createBrandWorkflow = createWorkflow(
57 "create-brand",
58 (input: CreateBrandInput) => {
59 // ...
60
61 emitEventStep({
62 eventName: "brand.created",
63 data: {
64 id: brand.id,
65 },
66 })
67
68 return new WorkflowResponse(brand)
69 }
70 )
71 ```
72
73 The `emitEventStep` accepts an object parameter having two properties:
74
75 - `eventName`: The name of the event to emit. You'll use this name later to listen to the event in a subscriber.
76 - `data`: The data payload to emit with the event. This data is passed to subscribers that listen to the event. You add the brand's ID to the data payload, informing the subscribers which brand was created.
77
78 You'll learn how to handle this event in a later step.
79
80 ---
81
82 ## 2. Create Sync to Third-Party System Workflow
83
84 The subscriber that will listen to the `brand.created` event will sync the created brand to the third-party CMS. So, you'll implement the syncing logic in a workflow, then execute the workflow in the subscriber.
85
86 Workflows have a built-in durable execution engine that helps you complete tasks spanning multiple systems. Also, their rollback mechanism ensures that data is consistent across systems even when errors occur during execution.
87
88 <Note>
89
90 Learn more about workflows in [this chapter](../../../fundamentals/workflows/page.mdx).
91
92 </Note>
93
94 You'll create a `syncBrandToSystemWorkflow` that has two steps:
95
96 - `useQueryGraphStep`: a step that Medusa provides to retrieve data using [Query](../../../fundamentals/query/page.mdx). You'll use this to retrieve the brand's details using its ID.
97 - `syncBrandToCmsStep`: a step that you'll create to sync the brand to the CMS.
98
99 ### syncBrandToCmsStep
100
101 To implement the step that syncs the brand to the CMS, create the file `src/workflows/sync-brands-to-cms.ts` with the following content:
102
103 ![Directory structure of the Medusa application after adding the file](https://res.cloudinary.com/dza7lstvk/image/upload/v1733493547/Medusa%20Book/cms-dir-overview-4_u5t0ug.jpg)
104
105 export const syncStepHighlights = [
106 ["8", "InferTypeOf", "Get the `Brand` data model as a type."],
107 ["14", "cmsModuleService", "Resolve the CMS Module's service from the container."],
108 ["16", "createBrand", "Create the brand in the third-party CMS."],
109 ["18", "brand.id", "Pass the brand's ID to the compensation function."],
110 ["27", "deleteBrand", "Delete the brand in the third-party CMS if an error occurs."]
111 ]
112
113 ```ts title="src/workflows/sync-brands-to-cms.ts" highlights={syncStepHighlights} collapsibleLines="1-6" expandButtonLabel="Show Imports"
114 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
115 import { InferTypeOf } from "@medusajs/framework/types"
116 import { Brand } from "../modules/brand/models/brand"
117 import { CMS_MODULE } from "../modules/cms"
118 import CmsModuleService from "../modules/cms/service"
119
120 type SyncBrandToCmsStepInput = {
121 brand: InferTypeOf<typeof Brand>
122 }
123
124 const syncBrandToCmsStep = createStep(
125 "sync-brand-to-cms",
126 async ({ brand }: SyncBrandToCmsStepInput, { container }) => {
127 const cmsModuleService: CmsModuleService = container.resolve(CMS_MODULE)
128
129 await cmsModuleService.createBrand(brand)
130
131 return new StepResponse(null, brand.id)
132 },
133 async (id, { container }) => {
134 if (!id) {
135 return
136 }
137
138 const cmsModuleService: CmsModuleService = container.resolve(CMS_MODULE)
139
140 await cmsModuleService.deleteBrand(id)
141 }
142 )
143 ```
144
145 You create the `syncBrandToCmsStep` that accepts a brand as an input. In the step, you resolve the CMS Module's service from the [Medusa container](../../../fundamentals/medusa-container/page.mdx) and use its `createBrand` method. This method will create the brand in the third-party CMS.
146
147 You also pass the brand's ID to the step's compensation function. In this function, you delete the brand in the third-party CMS if an error occurs during the workflow's execution.
148
149 <Note>
150
151 Learn more about compensation functions in [this chapter](../../../fundamentals/workflows/compensation-function/page.mdx).
152
153 </Note>
154
155 ### Create Workflow
156
157 You can now create the workflow that uses the above step. Add the workflow to the same `src/workflows/sync-brands-to-cms.ts` file:
158
159 export const syncWorkflowHighlights = [
160 ["18", "useQueryGraphStep", "Retrieve the brand's details."],
161 ["22", "id", "Filter by the brand's ID."],
162 ["25", "throwIfKeyNotFound", "Throw an error if a brand with the specified ID doesn't exist."],
163 ["29", "syncBrandToCmsStep", "Create the brand in the third-party CMS."]
164 ]
165
166 ```ts title="src/workflows/sync-brands-to-cms.ts" highlights={syncWorkflowHighlights}
167 // other imports...
168 import {
169 // ...
170 createWorkflow,
171 WorkflowResponse,
172 } from "@medusajs/framework/workflows-sdk"
173 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
174
175 // ...
176
177 type SyncBrandToCmsWorkflowInput = {
178 id: string
179 }
180
181 export const syncBrandToCmsWorkflow = createWorkflow(
182 "sync-brand-to-cms",
183 (input: SyncBrandToCmsWorkflowInput) => {
184 const { data: brands } = useQueryGraphStep({
185 entity: "brand",
186 fields: ["*"],
187 filters: {
188 id: input.id,
189 },
190 options: {
191 throwIfKeyNotFound: true,
192 },
193 })
194
195 syncBrandToCmsStep({
196 brand: brands[0],
197 } as SyncBrandToCmsStepInput)
198
199 return new WorkflowResponse({})
200 }
201 )
202 ```
203
204 You create a `syncBrandToCmsWorkflow` that accepts the brand's ID as input. The workflow has the following steps:
205
206 - `useQueryGraphStep`: Retrieve the brand's details using Query. You pass the brand's ID as a filter, and set the `throwIfKeyNotFound` option to true so that the step throws an error if a brand with the specified ID doesn't exist.
207 - `syncBrandToCmsStep`: Create the brand in the third-party CMS.
208
209 You'll execute this workflow in the subscriber next.
210
211 <Note>
212
213 Learn more about `useQueryGraphStep` in [this reference](!resources!/references/helper-steps/useQueryGraphStep).
214
215 </Note>
216
217 ---
218
219 ## 3. Handle brand.created Event
220
221 You now have a workflow with the logic to sync a brand to the CMS. You need to execute this workflow whenever the `brand.created` event is emitted. So, you'll create a subscriber that listens to and handle the event.
222
223 Subscribers are created in a TypeScript or JavaScript file under the `src/subscribers` directory. So, create the file `src/subscribers/brand-created.ts` with the following content:
224
225 ![Directory structure of the Medusa application after adding the subscriber](https://res.cloudinary.com/dza7lstvk/image/upload/v1733493774/Medusa%20Book/cms-dir-overview-5_iqqwvg.jpg)
226
227 export const subscriberHighlights = [
228 ["7", "brandCreatedHandler", "The function to execute when the event is emitted."],
229 ["8", "data", "The event's data payload."],
230 ["9", "container", "The Medusa container used to resolve resources."],
231 ["10", "id: string", "The expected data payload's type."],
232 ["11", "syncBrandToCmsWorkflow", "Execute the workflow to sync the brand to the CMS."],
233 ["16", "config", "Export the subscriber's configurations."],
234 ["17", "event", "The event that the subscriber is listening to."]
235 ]
236
237 ```ts title="src/subscribers/brand-created.ts" highlights={subscriberHighlights}
238 import type {
239 SubscriberConfig,
240 SubscriberArgs,
241 } from "@medusajs/framework"
242 import { syncBrandToCmsWorkflow } from "../workflows/sync-brands-to-cms"
243
244 export default async function brandCreatedHandler({
245 event: { data },
246 container,
247 }: SubscriberArgs<{ id: string }>) {
248 await syncBrandToCmsWorkflow(container).run({
249 input: data,
250 })
251 }
252
253 export const config: SubscriberConfig = {
254 event: "brand.created",
255 }
256 ```
257
258 A subscriber file must export:
259
260 - The asynchronous function that's executed when the event is emitted. This must be the file's default export.
261 - An object that holds the subscriber's configurations. It has an `event` property that indicates the name of the event that the subscriber is listening to.
262
263 The subscriber function accepts an object parameter that has two properties:
264
265 - `event`: An object of event details. Its `data` property holds the event's data payload, which is the brand's ID.
266 - `container`: The Medusa container used to resolve Framework and commerce tools.
267
268 In the function, you execute the `syncBrandToCmsWorkflow`, passing it the data payload as an input. So, every time a brand is created, Medusa will execute this function, which in turn executes the workflow to sync the brand to the CMS.
269
270 <Note>
271
272 Learn more about subscribers in [this chapter](../../../fundamentals/events-and-subscribers/page.mdx).
273
274 </Note>
275
276 ---
277
278 ## Test it Out
279
280 To test the subscriber and workflow out, you'll use the [Create Brand API route](../../custom-features/api-route/page.mdx) you created in a previous chapter.
281
282 First, start the Medusa application:
283
284 ```bash npm2yarn
285 npm run dev
286 ```
287
288 Since the `/admin/brands` API route has a `/admin` prefix, it's only accessible by authenticated admin users. So, to retrieve an authenticated token of your admin user, send a `POST` request to the `/auth/user/emailpass` API Route:
289
290 ```bash
291 curl -X POST 'http://localhost:9000/auth/user/emailpass' \
292 -H 'Content-Type: application/json' \
293 --data-raw '{
294 "email": "admin@medusa-test.com",
295 "password": "supersecret"
296 }'
297 ```
298
299 Make sure to replace the email and password with your admin user's credentials.
300
301 <Note title="Tip">
302
303 Don't have an admin user? Refer to [this guide](../../../installation/page.mdx#create-medusa-admin-user).
304
305 </Note>
306
307 Then, send a `POST` request to `/admin/brands`, passing the token received from the previous request in the `Authorization` header:
308
309 ```bash
310 curl -X POST 'http://localhost:9000/admin/brands' \
311 -H 'Content-Type: application/json' \
312 -H 'Authorization: Bearer {token}' \
313 --data '{
314 "name": "Acme"
315 }'
316 ```
317
318 This request returns the created brand. If you check the logs, you'll find the `brand.created` event was emitted, and that the request to the third-party system was simulated:
319
320 ```plain
321 info: Processing brand.created which has 1 subscribers
322 http: POST /admin/brands ← - (200) - 16.418 ms
323 info: Sending a POST request to /brands.
324 info: Request Data: {
325 "id": "01JEDWENYD361P664WRQPMC3J8",
326 "name": "Acme",
327 "created_at": "2024-12-06T11:42:32.909Z",
328 "updated_at": "2024-12-06T11:42:32.909Z",
329 "deleted_at": null
330 }
331 info: API Key: "123"
332 ```
333
334 ---
335
336 ## Next Chapter: Sync Brand from Third-Party CMS to Medusa
337
338 You can also automate syncing data from a third-party system to Medusa at a regular interval. In the next chapter, you'll learn how to sync brands from the third-party CMS to Medusa once a day.