index.mdx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. ---
  2. title: 'Plugins'
  3. sidebar_position: 6
  4. ---
  5. The heart of Vendure is its plugin system. Plugins not only allow you to instantly add new functionality to your
  6. Vendure server via third-part npm packages, they are also the means by which you build out the custom business
  7. logic of your application.
  8. Plugins in Vendure allow one to:
  9. - Modify the VendureConfig object, such as defining custom fields on existing entities.
  10. - Extend the GraphQL APIs, including modifying existing types and adding completely new queries and mutations.
  11. - Define new database entities and interact directly with the database.
  12. - Interact with external systems that you need to integrate with.
  13. - Respond to events such as new orders being placed.
  14. - Trigger background tasks to run on the worker process.
  15. … and more!
  16. In a typical Vendure application, custom logic and functionality is implemented as a set of plugins
  17. which are usually independent of one another. For example, there could be a plugin for each of the following:
  18. wishlists, product reviews, loyalty points, gift cards, etc.
  19. This allows for a clean separation of concerns and makes it easy to add or remove functionality as needed.
  20. ## Core Plugins
  21. Vendure provides a set of core plugins covering common functionality such as assets handling,
  22. email sending, and search. For documentation on these, see the [Core Plugins reference](/reference/core-plugins/).
  23. ## Plugin basics
  24. Here's a bare-minimum example of a plugin:
  25. ```ts title="src/plugins/avatar-plugin/avatar.plugin.ts"
  26. import { LanguageCode, PluginCommonModule, VendurePlugin } from '@vendure/core';
  27. @VendurePlugin({
  28. imports: [PluginCommonModule],
  29. configuration: config => {
  30. config.customFields.Customer.push({
  31. type: 'string',
  32. name: 'avatarUrl',
  33. label: [{ languageCode: LanguageCode.en, value: 'Avatar URL' }],
  34. list: true,
  35. });
  36. return config;
  37. },
  38. })
  39. export class AvatarPlugin {}
  40. ```
  41. This plugin does one thing only: it adds a new custom field to the `Customer` entity.
  42. The plugin is then imported into the `VendureConfig`:
  43. ```ts title="src/vendure-config.ts"
  44. import { VendureConfig } from '@vendure/core';
  45. import { AvatarPlugin } from './plugins/avatar-plugin/avatar.plugin';
  46. export const config: VendureConfig = {
  47. // ...
  48. // highlight-next-line
  49. plugins: [AvatarPlugin],
  50. };
  51. ```
  52. The key feature is the `@VendurePlugin()` decorator, which marks the class as a Vendure plugin and accepts a configuration
  53. object on the type [`VendurePluginMetadata`](/reference/typescript-api/plugin/vendure-plugin-metadata/).
  54. A VendurePlugin is actually an enhanced version of a [NestJS Module](https://docs.nestjs.com/modules), and supports
  55. all the metadata properties that NestJS modules support:
  56. - `imports`: Allows importing other NestJS modules in order to make use of their exported providers.
  57. - `providers`: The providers (services) that will be instantiated by the Nest injector and that may
  58. be shared across this plugin.
  59. - `controllers`: Controllers allow the plugin to define REST-style endpoints.
  60. - `exports`: The providers which will be exported from this plugin and made available to other plugins.
  61. Additionally, the `VendurePlugin` decorator adds the following Vendure-specific properties:
  62. - `configuration`: A function which can modify the `VendureConfig` object before the server bootstraps.
  63. - `shopApiExtensions`: Allows the plugin to extend the GraphQL Shop API with new queries, mutations, resolvers & scalars.
  64. - `adminApiExtensions`: Allows the plugin to extend the GraphQL Admin API with new queries, mutations, resolvers & scalars.
  65. - `entities`: Allows the plugin to define new database entities.
  66. - `compatibility`: Allows the plugin to declare which versions of Vendure it is compatible with.
  67. :::info
  68. Since a Vendure plugin is a superset of a NestJS module, this means that many NestJS modules are actually
  69. valid Vendure plugins!
  70. :::
  71. ## Plugin lifecycle
  72. Since a VendurePlugin is built on top of the NestJS module system, any plugin (as well as any providers it defines)
  73. can make use of any of the [NestJS lifecycle hooks](https://docs.nestjs.com/fundamentals/lifecycle-events):
  74. - onModuleInit
  75. - onApplicationBootstrap
  76. - onModuleDestroy
  77. - beforeApplicationShutdown
  78. - onApplicationShutdown
  79. :::caution
  80. Note that lifecycle hooks are run in both the server and worker contexts.
  81. If you have code that should only run either in the server context or worker context,
  82. you can inject the [ProcessContext provider](/reference/typescript-api/common/process-context/).
  83. :::
  84. ### Configure
  85. Another hook that is not strictly a lifecycle hook, but which can be useful to know is the [`configure` method](https://docs.nestjs.com/middleware#applying-middleware) which is
  86. used by NestJS to apply middleware. This method is called _only_ for the server and _not_ for the worker, since middleware relates
  87. to the network stack, and the worker has no network part.
  88. ```ts
  89. import { MiddlewareConsumer, NestModule } from '@nestjs/common';
  90. import { EventBus, PluginCommonModule, VendurePlugin } from '@vendure/core';
  91. import { MyMiddleware } from './api/my-middleware';
  92. @VendurePlugin({
  93. imports: [PluginCommonModule]
  94. })
  95. export class MyPlugin implements NestModule {
  96. configure(consumer: MiddlewareConsumer) {
  97. consumer
  98. .apply(MyMiddleware)
  99. .forRoutes('my-custom-route');
  100. }
  101. }
  102. ```
  103. ## Create a Plugin via CLI
  104. :::cli
  105. Run the `npx vendure add` command, and select "Create a new Vendure plugin".
  106. This will guide you through the creation of a new plugin and automate all aspects of the process.
  107. This is the recommended way of creating a new plugin.
  108. :::
  109. ## Writing a plugin from scratch
  110. Although the [Vendure CLI](/developer-guide/cli/) is the recommended way to create a new plugin, it can be useful to understand the process of creating
  111. a plugin manually.
  112. Vendure **plugins** are used to extend the core functionality of the server. Plugins can be pre-made functionality that you can install via npm, or they can be custom plugins that you write yourself.
  113. For any unit of functionality that you need to add to your project, you'll be creating a Vendure plugin. By convention, plugins are stored in the `plugins` directory of your project. However, this is not a requirement, and you are free to arrange your plugin files in any way you like.
  114. ```txt
  115. ├──src
  116. ├── index.ts
  117. ├── vendure-config.ts
  118. ├── plugins
  119. ├── reviews-plugin
  120. ├── cms-plugin
  121. ├── wishlist-plugin
  122. ├── stock-sync-plugin
  123. ```
  124. :::info
  125. For a complete working example of a Vendure plugin, see the [real-world-vendure Reviews plugin](https://github.com/vendurehq/real-world-vendure/tree/master/src/plugins/reviews)
  126. You can also use the [Vendure CLI](/developer-guide/cli) to quickly scaffold a new plugin.
  127. :::
  128. In this guide, we will implement a simple but fully-functional **wishlist plugin** step-by-step. The goal of this plugin is to allow signed-in customers to add products to a wishlist, and to view and manage their wishlist.
  129. ### Step 1: Create the plugin file
  130. We'll start by creating a new directory to house our plugin, add create the main plugin file:
  131. ```txt
  132. ├──src
  133. ├── index.ts
  134. ├── vendure-config.ts
  135. ├── plugins
  136. // highlight-next-line
  137. ├── wishlist-plugin
  138. // highlight-next-line
  139. ├── wishlist.plugin.ts
  140. ```
  141. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  142. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  143. @VendurePlugin({
  144. imports: [PluginCommonModule],
  145. })
  146. export class WishlistPlugin {}
  147. ```
  148. The `PluginCommonModule` will be required in all plugins that you create. It contains the common services that are exposed by Vendure Core, allowing you to inject them into your plugin's services and resolvers.
  149. ### Step 2: Define an entity
  150. Next we will define a new database entity to store the wishlist items. Vendure uses [TypeORM](https://typeorm.io/) to manage the database schema, and an Entity corresponds to a database table.
  151. First let's create the file to house the entity:
  152. ```txt
  153. ├── wishlist-plugin
  154. ├── wishlist.plugin.ts
  155. ├── entities
  156. // highlight-next-line
  157. ├── wishlist-item.entity.ts
  158. ```
  159. By convention, we'll store the entity definitions in the `entities` directory of the plugin. Again, this is not a requirement, but it is a good way to keep your plugin organized.
  160. ```ts title="src/plugins/wishlist-plugin/entities/wishlist-item.entity.ts"
  161. import { DeepPartial, ID, ProductVariant, VendureEntity, EntityId } from '@vendure/core';
  162. import { Entity, ManyToOne } from 'typeorm';
  163. @Entity()
  164. export class WishlistItem extends VendureEntity {
  165. constructor(input?: DeepPartial<WishlistItem>) {
  166. super(input);
  167. }
  168. @ManyToOne(type => ProductVariant)
  169. productVariant: ProductVariant;
  170. @EntityId()
  171. productVariantId: ID;
  172. }
  173. ```
  174. Let's break down what's happening here:
  175. - The `WishlistItem` entity extends the [`VendureEntity` class](/reference/typescript-api/entities/vendure-entity/). This is a base class which provides the `id`, `createdAt` and `updatedAt` fields, and all custom entities should extend it.
  176. - The `@Entity()` decorator marks this class as a TypeORM entity.
  177. - The `@ManyToOne()` decorator defines a many-to-one relationship with the `ProductVariant` entity. This means that each `WishlistItem` will be associated with a single `ProductVariant`.
  178. - The `productVariantId` column is not strictly necessary, but it allows us to always have access to the ID of the related `ProductVariant` without having to load the entire `ProductVariant` entity from the database.
  179. - The `constructor()` is used to create a new instance of the entity. This is not strictly necessary, but it is a good practice to define a constructor which takes a `DeepPartial` of the entity as an argument. This allows us to create new instances of the entity using the `new` keyword, passing in a plain object with the desired properties.
  180. Next we need to register this entity with our plugin:
  181. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  182. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  183. import { WishlistItem } from './entities/wishlist-item.entity';
  184. @VendurePlugin({
  185. imports: [PluginCommonModule],
  186. entities: [WishlistItem],
  187. })
  188. export class WishlistPlugin {}
  189. ```
  190. ### Step 3: Add a custom field to the Customer entity
  191. We'll now define a new custom field on the Customer entity which will store a list of WishlistItems. This will allow us to easily query for all wishlist items associated with a particular customer.
  192. Custom fields are defined in the VendureConfig object, and in a plugin we use the `configuration` function to modify the config object:
  193. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  194. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  195. import { WishlistItem } from './entities/wishlist-item.entity';
  196. @VendurePlugin({
  197. imports: [PluginCommonModule],
  198. entities: [WishlistItem],
  199. configuration: config => {
  200. config.customFields.Customer.push({
  201. name: 'wishlistItems',
  202. type: 'relation',
  203. list: true,
  204. entity: WishlistItem,
  205. internal: true,
  206. });
  207. return config;
  208. },
  209. })
  210. export class WishlistPlugin {}
  211. ```
  212. In this snippet we are pushing a new custom field definition onto the `Customer` entity's `customFields` array, and defining this new field as a list (array) of `WishlistItem` entities. Internally, this will tell TypeORM to update the database schema to store this new field. We set `internal: true` to indicate that this field should not be directly exposed to the GraphQL API as `Customer.customFields.wishlistItems`, but instead should be accessed via a custom resolver we will define later.
  213. In order to make use of this custom field in a type-safe way, we can tell TypeScript about this field in a new file:
  214. ```txt
  215. ├── wishlist-plugin
  216. ├── wishlist.plugin.ts
  217. // highlight-next-line
  218. ├── types.ts
  219. ```
  220. ```ts title="src/plugins/wishlist-plugin/types.ts"
  221. import { WishlistItem } from './entities/wishlist-item.entity';
  222. declare module '@vendure/core/dist/entity/custom-entity-fields' {
  223. interface CustomCustomerFields {
  224. wishlistItems: WishlistItem[];
  225. }
  226. }
  227. ```
  228. We can then import this types file in our plugin's main file:
  229. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  230. // highlight-next-line
  231. import './types';
  232. ```
  233. :::note
  234. Custom fields are not solely restricted to Vendure's native entities though, it's also possible to add support for custom fields to your own custom entities. This way other plugins would be able to extend our example `WishlistItem`. See: [Supporting custom fields](/developer-guide/database-entity/#supporting-custom-fields)
  235. :::
  236. ### Step 4: Create a service
  237. A "service" is a class which houses the bulk of the business logic of any plugin. A plugin can define multiple services if needed, but each service should be responsible for a single unit of functionality, such as dealing with a particular entity, or performing a particular task.
  238. Let's create a service to handle the wishlist functionality:
  239. ```txt
  240. ├── wishlist-plugin
  241. ├── wishlist.plugin.ts
  242. ├── services
  243. // highlight-next-line
  244. ├── wishlist.service.ts
  245. ```
  246. ```ts title="src/plugins/wishlist-plugin/services/wishlist.service.ts"
  247. import { Injectable } from '@nestjs/common';
  248. import {
  249. Customer,
  250. ForbiddenError,
  251. ID,
  252. InternalServerError,
  253. ProductVariantService,
  254. RequestContext,
  255. TransactionalConnection,
  256. UserInputError,
  257. } from '@vendure/core';
  258. import { WishlistItem } from '../entities/wishlist-item.entity';
  259. @Injectable()
  260. export class WishlistService {
  261. constructor(
  262. private connection: TransactionalConnection,
  263. private productVariantService: ProductVariantService,
  264. ) {}
  265. async getWishlistItems(ctx: RequestContext): Promise<WishlistItem[]> {
  266. try {
  267. const customer = await this.getCustomerWithWishlistItems(ctx);
  268. return customer.customFields.wishlistItems;
  269. } catch (err: any) {
  270. return [];
  271. }
  272. }
  273. /**
  274. * Adds a new item to the active Customer's wishlist.
  275. */
  276. async addItem(ctx: RequestContext, variantId: ID): Promise<WishlistItem[]> {
  277. const customer = await this.getCustomerWithWishlistItems(ctx);
  278. const variant = await this.productVariantService.findOne(ctx, variantId);
  279. if (!variant) {
  280. throw new UserInputError(`No ProductVariant with the id ${variantId} could be found`);
  281. }
  282. const existingItem = customer.customFields.wishlistItems.find(i => i.productVariantId === variantId);
  283. if (existingItem) {
  284. // Item already exists in wishlist, do not
  285. // add it again
  286. return customer.customFields.wishlistItems;
  287. }
  288. const wishlistItem = await this.connection
  289. .getRepository(ctx, WishlistItem)
  290. .save(new WishlistItem({ productVariantId: variantId }));
  291. customer.customFields.wishlistItems.push(wishlistItem);
  292. await this.connection.getRepository(ctx, Customer).save(customer, { reload: false });
  293. return this.getWishlistItems(ctx);
  294. }
  295. /**
  296. * Removes an item from the active Customer's wishlist.
  297. */
  298. async removeItem(ctx: RequestContext, itemId: ID): Promise<WishlistItem[]> {
  299. const customer = await this.getCustomerWithWishlistItems(ctx);
  300. const itemToRemove = customer.customFields.wishlistItems.find(i => i.id === itemId);
  301. if (itemToRemove) {
  302. await this.connection.getRepository(ctx, WishlistItem).remove(itemToRemove);
  303. customer.customFields.wishlistItems = customer.customFields.wishlistItems.filter(
  304. i => i.id !== itemId,
  305. );
  306. }
  307. await this.connection.getRepository(ctx, Customer).save(customer);
  308. return this.getWishlistItems(ctx);
  309. }
  310. /**
  311. * Gets the active Customer from the context and loads the wishlist items.
  312. */
  313. private async getCustomerWithWishlistItems(ctx: RequestContext): Promise<Customer> {
  314. if (!ctx.activeUserId) {
  315. throw new ForbiddenError();
  316. }
  317. const customer = await this.connection.getRepository(ctx, Customer).findOne({
  318. where: { user: { id: ctx.activeUserId } },
  319. relations: {
  320. customFields: {
  321. wishlistItems: {
  322. productVariant: true,
  323. },
  324. },
  325. },
  326. });
  327. if (!customer) {
  328. throw new InternalServerError(`Customer was not found`);
  329. }
  330. return customer;
  331. }
  332. }
  333. ```
  334. Let's break down what's happening here:
  335. - The `WishlistService` class is decorated with the `@Injectable()` decorator. This is a standard NestJS decorator which tells the NestJS dependency injection (DI) system that this class can be injected into other classes. All your services should be decorated with this decorator.
  336. - The arguments passed to the constructor will be injected by the NestJS DI system. The `connection` argument is a [TransactionalConnection](/reference/typescript-api/data-access/transactional-connection/) instance, which is used to access and manipulate data in the database. The [`ProductVariantService`](/reference/typescript-api/services/product-variant-service/) argument is a built-in Vendure service which contains methods relating to ProductVariants.
  337. - The [`RequestContext`](/reference/typescript-api/request/request-context/) object is usually the first argument to any service method, and contains information and context about the current request as well as any open database transactions. It should always be passed to the methods of the `TransactionalConnection`.
  338. The service is then registered with the plugin metadata as a provider:
  339. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  340. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  341. import { WishlistService } from './services/wishlist.service';
  342. @VendurePlugin({
  343. imports: [PluginCommonModule],
  344. // highlight-next-line
  345. providers: [WishlistService],
  346. entities: [WishlistItem],
  347. configuration: config => {
  348. // ...
  349. },
  350. })
  351. export class WishlistPlugin {}
  352. ```
  353. ### Step 5: Extend the GraphQL API
  354. This plugin will need to extend the Shop API, adding new mutations and queries to enable the customer to view and manage their wishlist.
  355. First we will create a new file to hold the GraphQL schema extensions:
  356. ```txt
  357. ├── wishlist-plugin
  358. ├── wishlist.plugin.ts
  359. ├── api
  360. // highlight-next-line
  361. ├── api-extensions.ts
  362. ```
  363. ```ts title="src/plugins/wishlist-plugin/api/api-extensions.ts"
  364. import gql from 'graphql-tag';
  365. export const shopApiExtensions = gql`
  366. type WishlistItem implements Node {
  367. id: ID!
  368. createdAt: DateTime!
  369. updatedAt: DateTime!
  370. productVariant: ProductVariant!
  371. productVariantId: ID!
  372. }
  373. extend type Query {
  374. activeCustomerWishlist: [WishlistItem!]!
  375. }
  376. extend type Mutation {
  377. addToWishlist(productVariantId: ID!): [WishlistItem!]!
  378. removeFromWishlist(itemId: ID!): [WishlistItem!]!
  379. }
  380. `;
  381. ```
  382. :::note
  383. The `graphql-tag` package is a dependency of the Vendure core package. Depending on the package manager you are using, you may need to install it separately with `yarn add graphql-tag` or `npm install graphql-tag`.
  384. :::
  385. The `api-extensions.ts` file is where we define the extensions we will be making to the Shop API GraphQL schema. We are defining a new `WishlistItem` type; a new query: `activeCustomerWishlist`; and two new mutations: `addToWishlist` and `removeFromWishlist`. This definition is written in [schema definition language](https://graphql.org/learn/schema/) (SDL), a convenient syntax for defining GraphQL schemas.
  386. Next we need to pass these extensions to our plugin's metadata:
  387. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  388. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  389. import { shopApiExtensions } from './api/api-extensions';
  390. @VendurePlugin({
  391. imports: [PluginCommonModule],
  392. shopApiExtensions: {
  393. schema: shopApiExtensions,
  394. resolvers: [],
  395. },
  396. })
  397. export class WishlistPlugin {}
  398. ```
  399. ### Step 6: Create a resolver
  400. Now that we have defined the GraphQL schema extensions, we need to create a resolver to handle the new queries and mutations. A resolver in GraphQL is a function which actually implements the query or mutation defined in the schema. This is done by creating a new file in the `api` directory:
  401. ```txt
  402. ├── wishlist-plugin
  403. ├── wishlist.plugin.ts
  404. ├── api
  405. ├── api-extensions.ts
  406. // highlight-next-line
  407. ├── wishlist.resolver.ts
  408. ```
  409. ```ts title="src/plugins/wishlist-plugin/api/wishlist.resolver.ts"
  410. import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
  411. import { Allow, Ctx, Permission, RequestContext, Transaction } from '@vendure/core';
  412. import { WishlistService } from '../services/wishlist.service';
  413. @Resolver()
  414. export class WishlistShopResolver {
  415. constructor(private wishlistService: WishlistService) {}
  416. @Query()
  417. @Allow(Permission.Owner)
  418. async activeCustomerWishlist(@Ctx() ctx: RequestContext) {
  419. return this.wishlistService.getWishlistItems(ctx);
  420. }
  421. @Mutation()
  422. @Transaction()
  423. @Allow(Permission.Owner)
  424. async addToWishlist(
  425. @Ctx() ctx: RequestContext,
  426. @Args() { productVariantId }: { productVariantId: string },
  427. ) {
  428. return this.wishlistService.addItem(ctx, productVariantId);
  429. }
  430. @Mutation()
  431. @Transaction()
  432. @Allow(Permission.Owner)
  433. async removeFromWishlist(@Ctx() ctx: RequestContext, @Args() { itemId }: { itemId: string }) {
  434. return this.wishlistService.removeItem(ctx, itemId);
  435. }
  436. }
  437. ```
  438. Resolvers are usually "thin" functions that delegate the actual work to a service. Vendure, like NestJS itself, makes heavy use of decorators at the API layer to define various aspects of the resolver. Let's break down what's happening here:
  439. - The `@Resolver()` decorator tells the NestJS DI system that this class is a resolver. Since a Resolver is part of the NestJS DI system, we can also inject dependencies into its constructor. In this case we are injecting the `WishlistService` which we created in the previous step.
  440. - The `@Mutation()` decorator tells Vendure that this is a mutation resolver. Similarly, `@Query()` decorator defines a query resolver. The name of the method is the name of the query or mutation in the schema.
  441. - The `@Transaction()` decorator tells Vendure that this resolver method should be wrapped in a database transaction. This is important because we are performing multiple database operations in this method, and we want them to be atomic.
  442. - The `@Allow()` decorator tells Vendure that this mutation is only allowed for users with the `Owner` permission. The `Owner` permission is a special permission which indicates that the active user should be the owner of this operation.
  443. - The `@Ctx()` decorator tells Vendure that this method requires access to the `RequestContext` object. Every resolver should have this as the first argument, as it is required throughout the Vendure request lifecycle.
  444. This resolver is then registered with the plugin metadata:
  445. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  446. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  447. import { shopApiExtensions } from './api/api-extensions';
  448. import { WishlistShopResolver } from './api/wishlist.resolver';
  449. @VendurePlugin({
  450. imports: [PluginCommonModule],
  451. shopApiExtensions: {
  452. schema: shopApiExtensions,
  453. // highlight-next-line
  454. resolvers: [WishlistShopResolver],
  455. },
  456. configuration: config => {
  457. // ...
  458. },
  459. })
  460. export class WishlistPlugin {}
  461. ```
  462. :::info
  463. More information about resolvers can be found in the [NestJS docs](https://docs.nestjs.com/graphql/resolvers).
  464. :::
  465. ### Step 7: Specify compatibility
  466. Since Vendure v2.0.0, it is possible for a plugin to specify which versions of Vendure core it is compatible with. This is especially important if the plugin is intended to be made publicly available via npm or another package registry.
  467. The compatibility is specified via the `compatibility` property in the plugin metadata:
  468. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  469. @VendurePlugin({
  470. // ...
  471. // highlight-next-line
  472. compatibility: '^2.0.0',
  473. })
  474. export class WishlistPlugin {}
  475. ```
  476. The value of this property is a [semver range](https://docs.npmjs.com/about-semantic-versioning) which specifies the range of compatible versions. In this case, we are saying that this plugin is compatible with any version of Vendure core which is `>= 2.0.0 < 3.0.0`.
  477. ### Step 8: Add the plugin to the VendureConfig
  478. The final step is to add the plugin to the `VendureConfig` object. This is done in the `vendure-config.ts` file:
  479. ```ts title="src/vendure-config.ts"
  480. import { VendureConfig } from '@vendure/core';
  481. import { WishlistPlugin } from './plugins/wishlist-plugin/wishlist.plugin';
  482. export const config: VendureConfig = {
  483. // ...
  484. plugins: [
  485. // ...
  486. // highlight-next-line
  487. WishlistPlugin,
  488. ],
  489. };
  490. ```
  491. ### Test the Plugin
  492. Now that the plugin is installed, we can test it out. Since we have defined a custom field, we'll need to generate and run a migration to add the new column to the database.
  493. 1. **Generate the Migration File**
  494. Run the following command to generate a migration file for the `wishlist-plugin`:
  495. ```bash
  496. npx vendure migrate wishlist-plugin
  497. ```
  498. When prompted, select the "Generate a new migration" option. This will create a new migration file in the `src/migrations` folder.
  499. 2. **Run the Migration**
  500. After generating the migration file, apply the changes to the database by running the same command again:
  501. ```bash
  502. npx vendure migrate wishlist-plugin
  503. ```
  504. Then start the server:
  505. ```bash
  506. npm run dev
  507. ```
  508. Once the server is running, we should be able to log in as an existing Customer, and then add a product to the wishlist:
  509. <Tabs>
  510. <TabItem value="Login mutation" label="Login mutation" default>
  511. ```graphql
  512. mutation Login {
  513. login(username: "alec.breitenberg@gmail.com", password: "test") {
  514. ... on CurrentUser {
  515. id
  516. identifier
  517. }
  518. ... on ErrorResult {
  519. errorCode
  520. message
  521. }
  522. }
  523. }
  524. ```
  525. </TabItem>
  526. <TabItem value="Response" label="Response">
  527. ```json
  528. {
  529. "data": {
  530. "login": {
  531. "id": "9",
  532. "identifier": "alec.breitenberg@gmail.com"
  533. }
  534. }
  535. }
  536. ```
  537. </TabItem>
  538. </Tabs>
  539. <Tabs>
  540. <TabItem value="AddToWishlist mutation" label="AddToWishlist mutation" default>
  541. ```graphql
  542. mutation AddToWishlist {
  543. addToWishlist(productVariantId: "7") {
  544. id
  545. productVariant {
  546. id
  547. name
  548. }
  549. }
  550. }
  551. ```
  552. </TabItem>
  553. <TabItem value="Response" label="Response">
  554. ```json
  555. {
  556. "data": {
  557. "addToWishlist": [
  558. {
  559. "id": "4",
  560. "productVariant": {
  561. "id": "7",
  562. "name": "Wireless Optical Mouse"
  563. }
  564. }
  565. ]
  566. }
  567. }
  568. ```
  569. </TabItem>
  570. </Tabs>
  571. We can then query the wishlist items:
  572. <Tabs>
  573. <TabItem value="GetWishlist query" label="GetWishlist query" default>
  574. ```graphql
  575. query GetWishlist {
  576. activeCustomerWishlist {
  577. id
  578. productVariant {
  579. id
  580. name
  581. }
  582. }
  583. }
  584. ```
  585. </TabItem>
  586. <TabItem value="Response" label="Response">
  587. ```json
  588. {
  589. "data": {
  590. "activeCustomerWishlist": [
  591. {
  592. "id": "4",
  593. "productVariant": {
  594. "id": "7",
  595. "name": "Wireless Optical Mouse"
  596. }
  597. }
  598. ]
  599. }
  600. }
  601. ```
  602. </TabItem>
  603. </Tabs>
  604. And finally, we can test removing an item from the wishlist:
  605. <Tabs>
  606. <TabItem value="RemoveFromWishlist mutation" label="RemoveFromWishlist mutation" default>
  607. ```graphql
  608. mutation RemoveFromWishlist {
  609. removeFromWishlist(itemId: "4") {
  610. id
  611. productVariant {
  612. id
  613. name
  614. }
  615. }
  616. }
  617. ```
  618. </TabItem>
  619. <TabItem value="Response" label="Response">
  620. ```json
  621. {
  622. "data": {
  623. "removeFromWishlist": []
  624. }
  625. }
  626. ```
  627. </TabItem>
  628. </Tabs>
  629. ## Publishing plugins
  630. If you have created a plugin that you would like to share with the community, you can publish it to npm, and even
  631. have it listed on the [Vendure Hub](https://vendure.io/hub).
  632. For a full guide to publishing plugins, see the [Publishing a Plugin how-to guide](/how-to/publish-plugin/).