|
1
|
{"slug":"/references/analytics/provider","title":"How to Create an Analytics Module Provider","frontmatter":{"slug":"/references/analytics/provider","keywords":["analytics","provider","integration"]},"toc":[{"title":"Implementation Example","id":"implementation-example","level":2},{"title":"Create Module Provider Directory","id":"create-module-provider-directory","level":2},{"title":"2. Create the Analytics Module Provider's Service","id":"2-create-the-analytics-module-provider-s-service","level":2},{"title":"constructor","id":"constructor","level":3},{"title":"Example","id":"example","level":4},{"title":"identifier","id":"identifier","level":3},{"title":"Example","id":"example-1","level":4},{"title":"identify","id":"identify","level":3},{"title":"Example","id":"example-2","level":4},{"title":"Parameters","id":"identify-parameters","level":4},{"title":"Returns","id":"identify-returns","level":4},{"title":"shutdown","id":"shutdown","level":3},{"title":"Example","id":"example-3","level":4},{"title":"Returns","id":"shutdown-returns","level":4},{"title":"track","id":"track","level":3},{"title":"Example","id":"example-4","level":4},{"title":"Parameters","id":"track-parameters","level":4},{"title":"Returns","id":"track-returns","level":4},{"title":"3. Create Module Provider Definition File","id":"3-create-module-provider-definition-file","level":2},{"title":"4. Use Module Provider","id":"4-use-module-provider","level":2},{"title":"5. Test it Out","id":"5-test-it-out","level":2},{"title":"Additional Resources","id":"additional-resources","level":2}],"blocks":[{"kind":"markdown","html":"In this document, you’ll learn how to create an Analytics Module Provider and the methods you must implement in its main service."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"Implementation Example","id":"implementation-example"},{"kind":"markdown","html":"As you implement your Analytics Module Provider, it can be useful to refer to an existing provider and how it's implemeted.\n\nIf you need to refer to an existing implementation as an example, check the [PostHog Analytics Module Provider in the Medusa repository](https://github.com/medusajs/medusa/tree/develop/packages/modules/providers/analytics-posthog).\n\n---"},{"kind":"heading","level":2,"text":"Create Module Provider Directory","id":"create-module-provider-directory"},{"kind":"markdown","html":"Start by creating a new directory for your module provider.\n\nIf you're creating the module provider in a Medusa application, create it under the `src/modules` directory. For example, `src/modules/my-analytics`.\n\nIf you're creating the module provider in a plugin, create it under the `src/providers` directory. For example, `src/providers/my-analytics`."},{"kind":"note","variant":"note","html":"The rest of this guide always uses the `src/modules/my-analytics` directory as an example."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"2. Create the Analytics Module Provider's Service","id":"2-create-the-analytics-module-provider-s-service"},{"kind":"markdown","html":"Create the file `src/modules/my-analytics/service.ts` that holds the implementation of the module provider's main service. It must extend the `AbstractAnalyticsProviderService` class imported from `@medusajs/framework/utils`:\n\n```ts title=\"src/modules/my-analytics/service.ts\"\nimport { AbstractAnalyticsProviderService } from \"@medusajs/framework/utils\"\n\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n // TODO implement methods\n}\n\nexport default MyAnalyticsProviderService\n```"},{"kind":"heading","level":3,"text":"constructor","id":"constructor"},{"kind":"markdown","html":"The constructor allows you to access resources from the module's container using the first parameter,\nand the module's options using the second parameter.\n\nIf you're creating a client or establishing a connection with a third-party service, do it in the constructor."},{"kind":"heading","level":4,"text":"Example","id":"example"},{"kind":"markdown","html":"```ts\nimport { Logger } from \"@medusajs/framework/types\"\nimport { AbstractAnalyticsProviderService } from \"@medusajs/framework/utils\"\n\ntype InjectedDependencies = {\n logger: Logger\n}\n\ntype Options = {\n apiKey: string\n}\n\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n protected logger_: Logger\n protected options_: Options\n static identifier = \"my-analytics\"\n // assuming you're initializing a client\n protected client\n\n constructor (\n { logger }: InjectedDependencies,\n options: Options\n ) {\n super()\n\n this.logger_ = logger\n this.options_ = options\n\n // assuming you're initializing a client\n this.client = new Client(options)\n }\n}\n\nexport default MyAnalyticsProviderService\n```"},{"kind":"heading","level":3,"text":"identifier","id":"identifier"},{"kind":"markdown","html":"Each analytics provider has a unique ID used to identify it. The provider's ID\nwill be stored as `aly_{identifier}_{id}`, where `{id}` is the provider's `id`\nproperty in the `medusa-config.ts`."},{"kind":"heading","level":4,"text":"Example","id":"example-1"},{"kind":"markdown","html":"```ts\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n static identifier = \"my-analytics\"\n // ...\n}\n```"},{"kind":"heading","level":3,"text":"identify","id":"identify"},{"kind":"markdown","html":"This method identifies an actor or group in the third-party analytics provider. The Analytics Module\nwill use this method in its `identify` method if your provider is configured in `medusa-config.ts`."},{"kind":"heading","level":4,"text":"Example","id":"example-2"},{"kind":"markdown","html":"```ts\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n // ...\n async identify(\n data: ProviderIdentifyAnalyticsEventDTO\n ): Promise<void> {\n // identify actor or group in the analytics provider\n // or using custom logic\n // for example:\n this.client.identify(data)\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"identify-parameters"},{"kind":"typeList","sectionTitle":"identify","types":[{"name":"data","type":"[IdentifyAnalyticsEventDTO](/references/types/types/types.IdentifyAnalyticsEventDTO)","description":"The details of the actor or group.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the actor. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":false,"defaultValue":"","example":"\"organization\"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"identify-returns"},{"kind":"typeList","sectionTitle":"identify","types":[{"name":"Promise","type":"Promise<void>","optional":false,"defaultValue":"","description":"Resolves when the actor or group is identified successfully.","expandable":false,"children":[]}]},{"kind":"heading","level":3,"text":"shutdown","id":"shutdown"},{"kind":"badges","badges":[{"variant":"neutral","label":"optional"}]},{"kind":"markdown","html":"This method is used to shutdown the analytics provider, and flush all data before shutting down.\n\nThis method is called by the Analytics Module when the Medusa application is shutting down."},{"kind":"heading","level":4,"text":"Example","id":"example-3"},{"kind":"markdown","html":"```ts\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n // ...\n async shutdown(): Promise<void> {\n // perform any cleanup or shutdown logic\n // in the analytics provider or using custom logic\n // for example:\n await this.client.shutdown()\n }\n}\n```"},{"kind":"heading","level":4,"text":"Returns","id":"shutdown-returns"},{"kind":"typeList","sectionTitle":"shutdown","types":[{"name":"Promise","type":"Promise<void>","optional":false,"defaultValue":"","description":"Resolves when the provider is shutdown successfully.","expandable":false,"children":[]}]},{"kind":"heading","level":3,"text":"track","id":"track"},{"kind":"markdown","html":"This method tracks an event with the third-party analytics provider. The Analytics Module\nwill use this method in its `track` method if your provider is configured in `medusa-config.ts`.\n\nYou can send the event to the third-party provider based on its semantics."},{"kind":"heading","level":4,"text":"Example","id":"example-4"},{"kind":"markdown","html":"```ts\nclass MyAnalyticsProviderService extends AbstractAnalyticsProviderService {\n // ...\n async track(\n data: ProviderTrackAnalyticsEventDTO\n ): Promise<void> {\n // track event to third-party provider\n // or using custom logic\n // for example:\n this.client.track(data)\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"track-parameters"},{"kind":"typeList","sectionTitle":"track","types":[{"name":"data","type":"[TrackAnalyticsEventDTO](/references/types/interfaces/types.TrackAnalyticsEventDTO)","description":"The event's details.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"event","type":"`string`","description":"The event name","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"actor_id","type":"`string`","description":"The actor of the event, if there is any","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"group","type":"`object`","description":"The group that the event is for, such as an organization or team.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"type","type":"`string`","description":"The name of the group.","optional":true,"defaultValue":"","example":"\"organization\"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The group's ID.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"properties","type":"`Record<string, any>`","description":"The properties of the event. The format and content is dynamic and depends on the integrated provider.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"track-returns"},{"kind":"typeList","sectionTitle":"track","types":[{"name":"Promise","type":"Promise<void>","optional":false,"defaultValue":"","description":"Resolves when the event is tracked successfully.","expandable":false,"children":[]}]},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"3. Create Module Provider Definition File","id":"3-create-module-provider-definition-file"},{"kind":"markdown","html":"Create the file `src/modules/my-analytics/index.ts` with the following content:\n\n```ts title=\"src/modules/my-analytics/index.ts\"\nimport MyAnalyticsProviderService from \"./service\"\nimport { \n ModuleProvider, \n Modules\n} from \"@medusajs/framework/utils\"\n\nexport default ModuleProvider(Modules.ANALYTICS, {\n services: [MyAnalyticsProviderService],\n})\n```\n\nThis exports the module provider's definition, indicating that the `MyAnalyticsProviderService` is the module provider's service.\n\n---"},{"kind":"heading","level":2,"text":"4. Use Module Provider","id":"4-use-module-provider"},{"kind":"markdown","html":"To use your Analytics Module Provider, add it to the `providers` array of the Analytics Module in `medusa-config.ts`:"},{"kind":"note","variant":"note","html":"The Analytics Module accepts one provider only."},{"kind":"markdown","html":"```ts title=\"medusa-config.ts\"\nmodule.exports = defineConfig({\n // ...\n modules: [\n {\n resolve: \"@medusajs/medusa/analytics\",\n options: {\n providers: [\n {\n // if module provider is in a plugin, use `plugin-name/providers/my-analytics`\n resolve: \"./src/modules/my-analytics\",\n id: \"my-analytics\",\n options: {\n // provider options...\n },\n },\n ],\n },\n },\n ]\n})\n```\n\n\n---"},{"kind":"heading","level":2,"text":"5. Test it Out","id":"5-test-it-out"},{"kind":"markdown","html":"To test the module out, you'll track in your third-party provider when an order is placed.\n\nYou'll first create a [workflow](!docs!/learn/fundamentals/workflows) that tracks the order completion event. Then, you can execute the workflow in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the `order.placed` event.\n\nFor example, create a workflow at `src/workflows/track-order-placed.ts` with the following content:\n\n```ts title=\"src/workflows/track-order-created.ts\"\nimport { createWorkflow } from \"@medusajs/framework/workflows-sdk\"\nimport { createStep } from \"@medusajs/framework/workflows-sdk\"\nimport { Modules } from \"@medusajs/framework/utils\"\nimport { OrderDTO } from \"@medusajs/framework/types\"\n\ntype StepInput = {\n order: OrderDTO\n}\n\nconst trackOrderCreatedStep = createStep(\n \"track-order-created-step\",\n async ({ order }: StepInput, { container }) => {\n const analyticsModuleService = container.resolve(Modules.ANALYTICS)\n\n await analyticsModuleService.track({\n event: \"order_created\",\n userId: order.customer_id,\n properties: {\n order_id: order.id,\n total: order.total,\n items: order.items.map((item) => ({\n variant_id: item.variant_id,\n product_id: item.product_id,\n quantity: item.quantity,\n })),\n customer_id: order.customer_id,\n },\n })\n }\n)\n\ntype WorkflowInput = {\n order_id: string\n}\n\nexport const trackOrderCreatedWorkflow = createWorkflow(\n \"track-order-created-workflow\",\n ({ order_id }: WorkflowInput) => {\n const { data: orders } = useQueryGraphStep({\n entity: \"order\",\n fields: [\n \"*\",\n \"customer.*\",\n \"items.*\"\n ],\n filters: {\n id: order_id,\n },\n })\n trackOrderCreatedStep({\n order: orders[0],\n })\n }\n)\n```\n\nThis workflow retrieves the order details using the `useQueryGraphStep` and then tracks the order creation event using the `trackOrderCreatedStep`.\n\nIn the step, you resolve the service of the Analytics Module from the [Medusa container](!docs!/learn/fundamentals/medusa-container) and use its `track` method to track the event. This method will use the underlying provider configured (which is your provider, in this case) to track the event.\n\nNext, create a subscriber at `src/subscribers/order-placed.ts` with the following content:\n\n```ts title=\"src/subscribers/order-placed.ts\"\nimport type {\n SubscriberArgs,\n SubscriberConfig,\n} from \"@medusajs/framework\"\nimport { trackOrderCreatedWorkflow } from \"../workflows/track-order-created\"\n\nexport default async function orderPlacedHandler({\n event: { data },\n container,\n}: SubscriberArgs<{ id: string }>) {\n await trackOrderCreatedWorkflow(container).run({\n input: {\n order_id: data.id,\n },\n })\n}\n\nexport const config: SubscriberConfig = {\n event: \"order.placed\",\n}\n```\n\nThis subscriber listens to the `order.placed` event and executes the `trackOrderCreatedWorkflow` workflow, passing the order ID as input.\n\nYou'll now track the order creation event whenever an order is placed in your Medusa application. You can test this out by placing an order and checking in your third-party provider if the event was tracked successfully.\n\n\n---"},{"kind":"heading","level":2,"text":"Additional Resources","id":"additional-resources"},{"kind":"markdown","html":"- [How to Use the Analytics Module](/references/analytics/service)"}]} |