Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(medusa): Alternative Subscriber API and new ScheduledJobs API #5624

Merged
merged 21 commits into from
Nov 16, 2023

Conversation

kasperkristensen
Copy link
Contributor

@kasperkristensen kasperkristensen commented Nov 13, 2023

What

  • Introduces a new API for loading Subscribers
  • Introduces a new API for loading Scheduled Jobs

Subscriber API

This PR introduces a new API for loading subscribers in Medusa. The API uses the same syntax as the new API Routes, and is meant to simplify the process of setting up Subscribers in projects.

Subscribers are still loaded through the folder /src/subscribers, and an example of the new syntax could look like this:

// src/subscribers/product-update-handler.ts
import type { SubscriberConfig, SubscriberArgs, ProductService } from "@medusajs/medusa"

export default async function productUpdateHandler({ data, eventName, container, pluginOptions }: SubscriberArgs) {
  const productService: ProductService = container.resolve("productService")

  const { id } = data

  const product = await productService.retrieve(id)

  // do something with the product...
}

export const config: SubscriberConfig = {
  event: ProductService.Events.UPDATE,
  context: {
    subscriberId: "product-update-handler"
  }
}

Here it is important to notice that the file has one default export (the subscriber handler), and one named const export (the config).

The handler takes an argument of SubscriberArgs that can be destructures to:

  • data which is the data that is passed when the subscribed event is emitted
  • eventName which allows the user to tell which event is currently being handled which is useful if a handler is subscribed to multiple events
  • The Medusa container which allows developers to resolve services, repositories, etc.
  • pluginOptions which allows the developer to access the plugin options when adding subscribers to a plugin.

The config (of type SubscriberConfig) has two fields:

  • (Required) event that the subscriber should subscribe to, this can be either a string or an string[].
  • (Optional) context which is an optional object of type { subscriberId?: string } & Record<string, unknown>. Which can be used to pass any context the user wants to the eventBusService. If a context.subscriberId is not provided the loader will attempt to infer it from the handler name, and if the handler is an anonymous function then from the file name.

When using event-bus-local

  • The subscriberId is overwritten to a uuid when using event-bus-local, so setting a context.subscriberId of the inferIdentifier won't have any effect in that case.
  • The eventName passed to the handler will be undefined when using event-bus-local as it does not pass it properly.

Scheduled Jobs API

The new Scheduled Jobs API is also aimed at making it easier for users to setup scheduled jobs (cron jobs) in Medusa. Currently, the developer needs to create a loader, and within that loader they need to resolve the jobSchedulerService and create their job. With this new PR Scheduled Jobs can be created directly in the new /src/jobs folder.

The syntax is as follows:

// src/jobs/once-a-minute.ts
import type { ProductService, ScheduledJobConfig, ScheduledJobArgs }  from "@medusajs/medusa"

export default async function handler({ container, data, pluginOptions }: ScheduledJobArgs) {
  const productService: ProductService = container.resolve("productService")
  
  const count = await productService.count()

  console.log(`You have ${count} products. This is a test: ${data.test ? "True" : "False"}`)
}

export const config: ScheduledJobConfig = {
  name: "every-minute",
  schedule: "* * * * *",
  data: {
    test: true,
  }
}

Again we need a default export of type function which is the job handler, and a named export for the config.

The handler takes one argument of type ScheduledJobArgs, that can be destructured to the following:

  • container, the Medusa container.
  • data, an optional object that can be passed in the config. (This field does not make a lot of sense with this syntax, but I have kept it to keep this syntax aligned with the old approach)
  • pluginOptions, the options of the plugin that the job was scheduled from.

The config of type ScheduledJobConfig has the following fields:

  • (Required) name, the name that is assigned to the job.
  • (Required) schedule, the cron schedule that determines when the job should run.
  • (Optional) data, an optional object that will be passed on to the handler.

Both

  • Both new APIs recursively discover jobs/subscribers to load. This allows developers to co-locate their code, as an example if a developer has 3 subscribers related to products, they can place them in a folder src/subscribers/products to organize related subscribers.

Resolves CORE-1547, CORE-1548

Copy link

changeset-bot bot commented Nov 13, 2023

🦋 Changeset detected

Latest commit: b80ccbd

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@medusajs/medusa Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link

vercel bot commented Nov 13, 2023

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Ignored Deployments
Name Status Preview Comments Updated (UTC)
api-reference ⬜️ Ignored (Inspect) Visit Preview Nov 16, 2023 0:26am
docs-ui ⬜️ Ignored (Inspect) Visit Preview Nov 16, 2023 0:26am
medusa-docs ⬜️ Ignored (Inspect) Visit Preview Nov 16, 2023 0:26am

@kasperkristensen kasperkristensen marked this pull request as ready for review November 14, 2023 10:14
@kasperkristensen kasperkristensen requested a review from a team as a code owner November 14, 2023 10:14
@olivermrbl
Copy link
Contributor

/snapshot-this

Copy link
Contributor

🚀 A snapshot release has been made for this PR

Test the snapshots by updating your package.json with the newly published versions:

yarn add @medusajs/admin-ui@2.1.8-snapshot-20231115070542
yarn add @medusajs/medusa@1.17.5-snapshot-20231115070542
yarn add medusa-source-shopify@1.2.10-snapshot-20231115070542
yarn add @medusajs/medusa-oas-cli@0.2.25-snapshot-20231115070542
yarn add @medusajs/utils@1.11.0-snapshot-20231115070542
yarn add @medusajs/workflows@0.3.0-snapshot-20231115070542

Latest commit: 5280071

Copy link
Contributor

@olivermrbl olivermrbl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incredibly clean PR @kasperkristensen. Great work. I didn't have much to add.

I would love to see us convert our core subscribers to use the new DX in case people browse the repo (and to dogfood the feature).

We could add the required loader and convert them in a follow up PR. What do you think? Maybe ask someone else from the team to do this, so we get it tested.

@olivermrbl
Copy link
Contributor

/snapshot-this

Copy link
Contributor

🚀 A snapshot release has been made for this PR

Test the snapshots by updating your package.json with the newly published versions:

yarn add @medusajs/admin-ui@2.1.8-snapshot-20231116082935
yarn add @medusajs/medusa@1.17.5-snapshot-20231116082935
yarn add medusa-source-shopify@1.2.10-snapshot-20231116082935
yarn add @medusajs/medusa-oas-cli@0.2.25-snapshot-20231116082935
yarn add @medusajs/pricing@0.1.4-snapshot-20231116082935
yarn add @medusajs/types@1.11.7-snapshot-20231116082935
yarn add @medusajs/utils@1.11.0-snapshot-20231116082935
yarn add @medusajs/workflows@0.3.0-snapshot-20231116082935

Latest commit: ecabd38

@olivermrbl
Copy link
Contributor

@kasperkristensen should we merge this badboy?

@olivermrbl olivermrbl merged commit 57573ed into develop Nov 16, 2023
12 checks passed
@olivermrbl olivermrbl deleted the feat/subscribers-jobs-api branch November 16, 2023 19:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants