1 import { Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Guide: Schedule Syncing Brands from Third-Party`,
5 }
6
7 # {metadata.title}
8
9 In the previous chapters, you've [integrated a third-party CMS](../service/page.mdx) and implemented the logic to [sync created brands](../handle-event/page.mdx) from Medusa to the CMS.
10
11 However, when you integrate a third-party system, you want the data to be in sync between the Medusa application and the system. One way to do so is by automatically syncing the data once a day.
12
13 You can create an action to be automatically executed at a specified interval using scheduled jobs. A scheduled job is an asynchronous function with a specified schedule of when the Medusa application should run it. Scheduled jobs are useful to automate repeated tasks.
14
15 <Note>
16
17 Learn more about scheduled jobs in [this chapter](../../../fundamentals/scheduled-jobs/page.mdx).
18
19 </Note>
20
21 In this chapter, you'll create a scheduled job that triggers syncing the brands from the third-party CMS to Medusa once a day. You'll implement the syncing logic in a workflow, and execute that workflow in the scheduled job.
22
23 <Prerequisites
24 items={[
25 {
26 text: "CMS Module",
27 link: "/learn/customization/integrate-systems/service"
28 }
29 ]}
30 />
31
32 ---
33
34 ## 1. Implement Syncing Workflow
35
36 You'll start by implementing the syncing logic in a workflow, then execute the workflow later in the scheduled job.
37
38 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.
39
40 <Note>
41
42 Learn more about workflows in [this chapter](../../../fundamentals/workflows/page.mdx).
43
44 </Note>
45
46 This workflow will have three steps:
47
48 1. `retrieveBrandsFromCmsStep` to retrieve the brands from the CMS.
49 2. `createBrandsStep` to create the brands retrieved in the first step that don't exist in Medusa.
50 3. `updateBrandsStep` to update the brands retrieved in the first step that exist in Medusa.
51
52 ### retrieveBrandsFromCmsStep
53
54 To create the step that retrieves the brands from the third-party CMS, create the file `src/workflows/sync-brands-from-cms.ts` with the following content:
55
56 ![Directory structure of the Medusa application after creating the file.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733494196/Medusa%20Book/cms-dir-overview-6_z1omsi.jpg)
57
58 ```ts title="src/workflows/sync-brands-from-cms.ts" collapsibleLines="1-7" expandButtonLabel="Show Imports"
59 import {
60 createStep,
61 StepResponse,
62 } from "@medusajs/framework/workflows-sdk"
63 import CmsModuleService from "../modules/cms/service"
64 import { CMS_MODULE } from "../modules/cms"
65
66 const retrieveBrandsFromCmsStep = createStep(
67 "retrieve-brands-from-cms",
68 async (_, { container }) => {
69 const cmsModuleService: CmsModuleService = container.resolve(
70 CMS_MODULE
71 )
72
73 const brands = await cmsModuleService.retrieveBrands()
74
75 return new StepResponse(brands)
76 }
77 )
78 ```
79
80 You create a `retrieveBrandsFromCmsStep` that resolves the CMS Module's service and uses its `retrieveBrands` method to retrieve the brands in the CMS. You return those brands in the step's response.
81
82 ### createBrandsStep
83
84 The brands retrieved in the first step may have brands that don't exist in Medusa. So, you'll create a step that creates those brands. Add the step to the same `src/workflows/sync-brands-from-cms.ts` file:
85
86 export const createBrandsHighlights = [
87 ["22", "createBrands", "Create the brands in Medusa"],
88 ["35", "deleteBrands", "Delete the brands from Medusa"]
89 ]
90
91 ```ts title="src/workflows/sync-brands-from-cms.ts" highlights={createBrandsHighlights} collapsibleLines="1-8" expandButtonLabel="Show Imports"
92 // other imports...
93 import BrandModuleService from "../modules/brand/service"
94 import { BRAND_MODULE } from "../modules/brand"
95
96 // ...
97
98 type CreateBrand = {
99 name: string
100 }
101
102 type CreateBrandsInput = {
103 brands: CreateBrand[]
104 }
105
106 export const createBrandsStep = createStep(
107 "create-brands-step",
108 async (input: CreateBrandsInput, { container }) => {
109 const brandModuleService: BrandModuleService = container.resolve(
110 BRAND_MODULE
111 )
112
113 const brands = await brandModuleService.createBrands(input.brands)
114
115 return new StepResponse(brands, brands)
116 },
117 async (brands, { container }) => {
118 if (!brands) {
119 return
120 }
121
122 const brandModuleService: BrandModuleService = container.resolve(
123 BRAND_MODULE
124 )
125
126 await brandModuleService.deleteBrands(brands.map((brand) => brand.id))
127 }
128 )
129 ```
130
131 The `createBrandsStep` accepts the brands to create as an input. It resolves the [Brand Module](../../custom-features/module/page.mdx)'s service and uses the generated `createBrands` method to create the brands.
132
133 The step passes the created brands to the compensation function, which deletes those brands if an error occurs during the workflow's execution.
134
135 <Note>
136
137 Learn more about compensation functions in [this chapter](../../../fundamentals/workflows/compensation-function/page.mdx).
138
139 </Note>
140
141 ### Update Brands Step
142
143 The brands retrieved in the first step may also have brands that exist in Medusa. So, you'll create a step that updates their details to match that of the CMS. Add the step to the same `src/workflows/sync-brands-from-cms.ts` file:
144
145 export const updateBrandsHighlights = [
146 ["19", "prevUpdatedBrands", "Retrieve the data of the brands before the update."],
147 ["23", "updateBrands", "Update the brands in Medusa."],
148 ["36", "updateBrands", "Revert the update by reverting the brands' details to before the update."]
149 ]
150
151 ```ts title="src/workflows/sync-brands-from-cms.ts" highlights={updateBrandsHighlights}
152 // ...
153
154 type UpdateBrand = {
155 id: string
156 name: string
157 }
158
159 type UpdateBrandsInput = {
160 brands: UpdateBrand[]
161 }
162
163 export const updateBrandsStep = createStep(
164 "update-brands-step",
165 async ({ brands }: UpdateBrandsInput, { container }) => {
166 const brandModuleService: BrandModuleService = container.resolve(
167 BRAND_MODULE
168 )
169
170 const prevUpdatedBrands = await brandModuleService.listBrands({
171 id: brands.map((brand) => brand.id),
172 })
173
174 const updatedBrands = await brandModuleService.updateBrands(brands)
175
176 return new StepResponse(updatedBrands, prevUpdatedBrands)
177 },
178 async (prevUpdatedBrands, { container }) => {
179 if (!prevUpdatedBrands) {
180 return
181 }
182
183 const brandModuleService: BrandModuleService = container.resolve(
184 BRAND_MODULE
185 )
186
187 await brandModuleService.updateBrands(prevUpdatedBrands)
188 }
189 )
190 ```
191
192 The `updateBrandsStep` receives the brands to update in Medusa. In the step, you retrieve the brand's details in Medusa before the update to pass them to the compensation function. You then update the brands using the Brand Module's `updateBrands` generated method.
193
194 In the compensation function, which receives the brand's old data, you revert the update using the same `updateBrands` method.
195
196 ### Create Workflow
197
198 Finally, you'll create the workflow that uses the above steps to sync the brands from the CMS to Medusa. Add to the same `src/workflows/sync-brands-from-cms.ts` file the following:
199
200 ```ts title="src/workflows/sync-brands-from-cms.ts"
201 // other imports...
202 import {
203 // ...
204 createWorkflow,
205 transform,
206 WorkflowResponse,
207 } from "@medusajs/framework/workflows-sdk"
208
209 // ...
210
211 export const syncBrandsFromCmsWorkflow = createWorkflow(
212 "sync-brands-from-system",
213 () => {
214 const brands = retrieveBrandsFromCmsStep()
215
216 // TODO create and update brands
217 }
218 )
219 ```
220
221 In the workflow, you only use the `retrieveBrandsFromCmsStep` for now, which retrieves the brands from the third-party CMS.
222
223 Next, you need to identify which brands must be created or updated. Since workflows are constructed internally and are only evaluated during execution, you can't access values to perform data manipulation directly. Instead, use [transform](../../../fundamentals/workflows/variable-manipulation/page.mdx) from the Workflows SDK that gives you access to the real-time values of the data, allowing you to create new variables using those values.
224
225 <Note>
226
227 Learn more about data manipulation using `transform` in [this chapter](../../../fundamentals/workflows/variable-manipulation/page.mdx).
228
229 </Note>
230
231 So, replace the `TODO` with the following:
232
233 ```ts title="src/workflows/sync-brands-from-cms.ts"
234 const { toCreate, toUpdate } = transform(
235 {
236 brands,
237 },
238 (data) => {
239 const toCreate: CreateBrand[] = []
240 const toUpdate: UpdateBrand[] = []
241
242 data.brands.forEach((brand) => {
243 if (brand.external_id) {
244 toUpdate.push({
245 id: brand.external_id as string,
246 name: brand.name as string,
247 })
248 } else {
249 toCreate.push({
250 name: brand.name as string,
251 })
252 }
253 })
254
255 return { toCreate, toUpdate }
256 }
257 )
258
259 // TODO create and update the brands
260 ```
261
262 `transform` accepts two parameters:
263
264 1. The data to be passed to the function in the second parameter.
265 2. A function to execute only when the workflow is executed. Its return value can be consumed by the rest of the workflow.
266
267 In `transform`'s function, you loop over the brands array to check which should be created or updated. This logic assumes that a brand in the CMS has an `external_id` property whose value is the brand's ID in Medusa.
268
269 You now have the list of brands to create and update. So, replace the new `TODO` with the following:
270
271 ```ts title="src/workflows/sync-brands-from-cms.ts"
272 const created = createBrandsStep({ brands: toCreate })
273 const updated = updateBrandsStep({ brands: toUpdate })
274
275 return new WorkflowResponse({
276 created,
277 updated,
278 })
279 ```
280
281 You first run the `createBrandsStep` to create the brands that don't exist in Medusa, then the `updateBrandsStep` to update the brands that exist in Medusa. You pass the arrays returned by `transform` as the inputs for the steps.
282
283 Finally, you return an object of the created and updated brands. You'll execute this workflow in the scheduled job next.
284
285 ---
286
287 ## 2. Schedule Syncing Task
288
289 You now have the workflow to sync the brands from the CMS to Medusa. Next, you'll create a scheduled job that runs this workflow once a day to ensure the data between Medusa and the CMS are always in sync.
290
291 A scheduled job is created in a TypeScript or JavaScript file under the `src/jobs` directory. So, create the file `src/jobs/sync-brands-from-cms.ts` with the following content:
292
293 ![Directory structure of the Medusa application after adding the scheduled job](https://res.cloudinary.com/dza7lstvk/image/upload/v1733494592/Medusa%20Book/cms-dir-overview-7_dkjb9s.jpg)
294
295 ```ts title="src/jobs/sync-brands-from-cms.ts"
296 import { MedusaContainer } from "@medusajs/framework/types"
297 import { syncBrandsFromCmsWorkflow } from "../workflows/sync-brands-from-cms"
298 import {
299 ContainerRegistrationKeys,
300 } from "@medusajs/framework/utils"
301
302 export default async function (container: MedusaContainer) {
303 const logger = container.resolve(
304 ContainerRegistrationKeys.LOGGER
305 )
306
307 const { result } = await syncBrandsFromCmsWorkflow(container).run()
308
309 logger.info(
310 `Synced brands from third-party system: ${
311 result.created.length
312 } brands created and ${result.updated.length} brands updated.`)
313 }
314
315 export const config = {
316 name: "sync-brands-from-system",
317 schedule: "0 0 * * *", // change to * * * * * for debugging
318 }
319 ```
320
321 A scheduled job file must export:
322
323 - An asynchronous function that will be executed at the specified schedule. This function must be the file's default export.
324 - An object of scheduled jobs configuration. It has two properties:
325 - `name`: A unique name for the scheduled job.
326 - `schedule`: A string that holds a [cron expression](https://crontab.guru/) indicating the schedule to run the job.
327
328 The scheduled job function accepts as a parameter the [Medusa container](../../../fundamentals/medusa-container/page.mdx) used to resolve Framework and commerce tools. You then execute the `syncBrandsFromCmsWorkflow` and use its result to log how many brands were created or updated.
329
330 Based on the cron expression specified in `config.schedule`, Medusa will run the scheduled job every day at midnight. You can also change it to `* * * * *` to run it every minute for easier debugging.
331
332 ---
333
334 ## Test it Out
335
336 To test out the scheduled job, start the Medusa application:
337
338 ```bash npm2yarn
339 npm run dev
340 ```
341
342 If you set the schedule to `* * * * *` for debugging, the scheduled job will run in a minute. You'll see in the logs how many brands were created or updated.
343
344 ---
345
346 ## Summary
347
348 By following the previous chapters, you utilized the Medusa Framework and orchestration tools to perform and automate tasks that span across systems.
349
350 With Medusa, you can integrate any service from your commerce ecosystem with ease. You don't have to set up separate applications to manage your different customizations, or worry about data inconsistency across systems. Your efforts only go into implementing the business logic that ties your systems together.