index.mdx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. ---
  2. title: 'Plugins'
  3. sidebar_position: 6
  4. ---
  5. import Tabs from '@theme/Tabs';
  6. import TabItem from '@theme/TabItem';
  7. The heart of Vendure is its plugin system. Plugins not only allow you to instantly add new functionality to your
  8. Vendure server via third-part npm packages, they are also the means by which you build out the custom business
  9. logic of your application.
  10. Plugins in Vendure allow one to:
  11. - Modify the VendureConfig object, such as defining custom fields on existing entities.
  12. - Extend the GraphQL APIs, including modifying existing types and adding completely new queries and mutations.
  13. - Define new database entities and interact directly with the database.
  14. - Interact with external systems that you need to integrate with.
  15. - Respond to events such as new orders being placed.
  16. - Trigger background tasks to run on the worker process.
  17. … and more!
  18. In a typical Vendure application, custom logic and functionality is implemented as a set of plugins
  19. which are usually independent of one another. For example, there could be a plugin for each of the following:
  20. wishlists, product reviews, loyalty points, gift cards, etc.
  21. This allows for a clean separation of concerns and makes it easy to add or remove functionality as needed.
  22. ## Core Plugins
  23. Vendure provides a set of core plugins covering common functionality such as assets handling,
  24. email sending, and search. For documentation on these, see the [Core Plugins reference](/reference/core-plugins/).
  25. ## Plugin basics
  26. Here's a bare-minimum example of a plugin:
  27. ```ts title="src/plugins/avatar-plugin/avatar.plugin.ts"
  28. import { LanguageCode, PluginCommonModule, VendurePlugin } from '@vendure/core';
  29. @VendurePlugin({
  30. imports: [PluginCommonModule],
  31. configuration: config => {
  32. config.customFields.Customer.push({
  33. type: 'string',
  34. name: 'avatarUrl',
  35. label: [{ languageCode: LanguageCode.en, value: 'Avatar URL' }],
  36. list: true,
  37. });
  38. return config;
  39. },
  40. })
  41. export class AvatarPlugin {}
  42. ```
  43. This plugin does one thing only: it adds a new custom field to the `Customer` entity.
  44. The plugin is then imported into the `VendureConfig`:
  45. ```ts title="src/vendure-config.ts"
  46. import { VendureConfig } from '@vendure/core';
  47. import { AvatarPlugin } from './plugins/avatar-plugin/avatar.plugin';
  48. export const config: VendureConfig = {
  49. // ...
  50. // highlight-next-line
  51. plugins: [AvatarPlugin],
  52. };
  53. ```
  54. The key feature is the `@VendurePlugin()` decorator, which marks the class as a Vendure plugin and accepts a configuration
  55. object on the type [`VendurePluginMetadata`](/reference/typescript-api/plugin/vendure-plugin-metadata/).
  56. A VendurePlugin is actually an enhanced version of a [NestJS Module](https://docs.nestjs.com/modules), and supports
  57. all the metadata properties that NestJS modules support:
  58. - `imports`: Allows importing other NestJS modules in order to make use of their exported providers.
  59. - `providers`: The providers (services) that will be instantiated by the Nest injector and that may
  60. be shared across this plugin.
  61. - `controllers`: Controllers allow the plugin to define REST-style endpoints.
  62. - `exports`: The providers which will be exported from this plugin and made available to other plugins.
  63. Additionally, the `VendurePlugin` decorator adds the following Vendure-specific properties:
  64. - `configuration`: A function which can modify the `VendureConfig` object before the server bootstraps.
  65. - `shopApiExtensions`: Allows the plugin to extend the GraphQL Shop API with new queries, mutations, resolvers & scalars.
  66. - `adminApiExtensions`: Allows the plugin to extend the GraphQL Admin API with new queries, mutations, resolvers & scalars.
  67. - `entities`: Allows the plugin to define new database entities.
  68. - `compatibility`: Allows the plugin to declare which versions of Vendure it is compatible with.
  69. :::info
  70. Since a Vendure plugin is a superset of a NestJS module, this means that many NestJS modules are actually
  71. valid Vendure plugins!
  72. :::
  73. ## Plugin lifecycle
  74. Since a VendurePlugin is built on top of the NestJS module system, any plugin (as well as any providers it defines)
  75. can make use of any of the [NestJS lifecycle hooks](https://docs.nestjs.com/fundamentals/lifecycle-events):
  76. - onModuleInit
  77. - onApplicationBootstrap
  78. - onModuleDestroy
  79. - beforeApplicationShutdown
  80. - onApplicationShutdown
  81. :::caution
  82. Note that lifecycle hooks are run in both the server and worker contexts.
  83. If you have code that should only run either in the server context or worker context,
  84. you can inject the [ProcessContext provider](/reference/typescript-api/common/process-context/).
  85. :::
  86. ### Configure
  87. 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
  88. used by NestJS to apply middleware. This method is called _only_ for the server and _not_ for the worker, since middleware relates
  89. to the network stack, and the worker has no network part.
  90. ```ts
  91. import { MiddlewareConsumer, NestModule } from '@nestjs/common';
  92. import { EventBus, PluginCommonModule, VendurePlugin } from '@vendure/core';
  93. import { MyMiddleware } from './api/my-middleware';
  94. @VendurePlugin({
  95. imports: [PluginCommonModule]
  96. })
  97. export class MyPlugin implements NestModule {
  98. configure(consumer: MiddlewareConsumer) {
  99. consumer
  100. .apply(MyMiddleware)
  101. .forRoutes('my-custom-route');
  102. }
  103. }
  104. ```
  105. ## Create a Plugin via CLI
  106. :::cli
  107. Run the `npx vendure add` command, and select "Create a new Vendure plugin".
  108. This will guide you through the creation of a new plugin and automate all aspects of the process.
  109. This is the recommended way of creating a new plugin.
  110. :::
  111. ## Writing a plugin from scratch
  112. Although the [Vendure CLI](/guides/developer-guide/cli/) is the recommended way to create a new plugin, it can be useful to understand the process of creating
  113. a plugin manually.
  114. In 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.
  115. 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.
  116. ```txt
  117. ├──src
  118. ├── index.ts
  119. ├── vendure-config.ts
  120. ├── plugins
  121. ├── reviews-plugin
  122. ├── cms-plugin
  123. ├── wishlist-plugin
  124. ├── stock-sync-plugin
  125. ```
  126. :::info
  127. For a complete working example of a Vendure plugin, see the [real-world-vendure Reviews plugin](https://github.com/vendure-ecommerce/real-world-vendure/tree/master/src/plugins/reviews)
  128. You can also use the [Vendure CLI](/guides/developer-guide/cli) to quickly scaffold a new plugin.
  129. If you intend to write a shared plugin to be distributed as an npm package, see the [vendure plugin-template repo](https://github.com/vendure-ecommerce/plugin-template)
  130. :::
  131. 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.
  132. ### Step 1: Create the plugin file
  133. We'll start by creating a new directory to house our plugin, add create the main plugin file:
  134. ```txt
  135. ├──src
  136. ├── index.ts
  137. ├── vendure-config.ts
  138. ├── plugins
  139. // highlight-next-line
  140. ├── wishlist-plugin
  141. // highlight-next-line
  142. ├── wishlist.plugin.ts
  143. ```
  144. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  145. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  146. @VendurePlugin({
  147. imports: [PluginCommonModule],
  148. })
  149. export class WishlistPlugin {}
  150. ```
  151. 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.
  152. ### Step 2: Define an entity
  153. 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.
  154. First let's create the file to house the entity:
  155. ```txt
  156. ├── wishlist-plugin
  157. ├── wishlist.plugin.ts
  158. ├── entities
  159. // highlight-next-line
  160. ├── wishlist-item.entity.ts
  161. ```
  162. 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.
  163. ```ts title="src/plugins/wishlist-plugin/entities/wishlist-item.entity.ts"
  164. import { DeepPartial, ID, ProductVariant, VendureEntity, EntityId } from '@vendure/core';
  165. import { Column, Entity, ManyToOne } from 'typeorm';
  166. @Entity()
  167. export class WishlistItem extends VendureEntity {
  168. constructor(input?: DeepPartial<WishlistItem>) {
  169. super(input);
  170. }
  171. @ManyToOne(type => ProductVariant)
  172. productVariant: ProductVariant;
  173. @EntityId()
  174. productVariantId: ID;
  175. }
  176. ```
  177. Let's break down what's happening here:
  178. - 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.
  179. - The `@Entity()` decorator marks this class as a TypeORM entity.
  180. - 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`.
  181. - 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.
  182. - 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.
  183. Next we need to register this entity with our plugin:
  184. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  185. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  186. import { WishlistItem } from './entities/wishlist-item.entity';
  187. @VendurePlugin({
  188. imports: [PluginCommonModule],
  189. entities: [WishlistItem],
  190. })
  191. export class WishlistPlugin {}
  192. ```
  193. ### Step 3: Add a custom field to the Customer entity
  194. 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.
  195. Custom fields are defined in the VendureConfig object, and in a plugin we use the `configuration` function to modify the config object:
  196. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  197. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  198. import { WishlistItem } from './entities/wishlist-item.entity';
  199. @VendurePlugin({
  200. imports: [PluginCommonModule],
  201. entities: [WishlistItem],
  202. configuration: config => {
  203. config.customFields.Customer.push({
  204. name: 'wishlistItems',
  205. type: 'relation',
  206. list: true,
  207. entity: WishlistItem,
  208. internal: true,
  209. });
  210. return config;
  211. },
  212. })
  213. export class WishlistPlugin {}
  214. ```
  215. 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.
  216. 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:
  217. ```txt
  218. ├── wishlist-plugin
  219. ├── wishlist.plugin.ts
  220. // highlight-next-line
  221. ├── types.ts
  222. ```
  223. ```ts title="src/plugins/wishlist-plugin/types.ts"
  224. import { WishlistItem } from './entities/wishlist-item.entity';
  225. declare module '@vendure/core/dist/entity/custom-entity-fields' {
  226. interface CustomCustomerFields {
  227. wishlistItems: WishlistItem[];
  228. }
  229. }
  230. ```
  231. We can then import this types file in our plugin's main file:
  232. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  233. // highlight-next-line
  234. import './types';
  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 = 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 { WishlistItem } from '../entities/wishlist-item.entity';
  413. import { WishlistService } from '../services/wishlist.service';
  414. @Resolver()
  415. export class WishlistShopResolver {
  416. constructor(private wishlistService: WishlistService) {}
  417. @Query()
  418. @Allow(Permission.Owner)
  419. activeCustomerWishlist(@Ctx() ctx: RequestContext) {
  420. return this.wishlistService.getWishlistItems(ctx);
  421. }
  422. @Mutation()
  423. @Transaction()
  424. @Allow(Permission.Owner)
  425. async addToWishlist(
  426. @Ctx() ctx: RequestContext,
  427. @Args() { productVariantId }: { productVariantId: string },
  428. ) {
  429. return this.wishlistService.addItem(ctx, productVariantId);
  430. }
  431. @Mutation()
  432. @Transaction()
  433. @Allow(Permission.Owner)
  434. async removeFromWishlist(@Ctx() ctx: RequestContext, @Args() { itemId }: { itemId: string }) {
  435. return this.wishlistService.removeItem(ctx, itemId);
  436. }
  437. }
  438. ```
  439. 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:
  440. - 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.
  441. - 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.
  442. - 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.
  443. - 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.
  444. - 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.
  445. This resolver is then registered with the plugin metadata:
  446. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  447. import { PluginCommonModule, VendurePlugin } from '@vendure/core';
  448. import { shopApiExtensions } from './api/api-extensions';
  449. import { WishlistShopResolver } from './api/wishlist.resolver';
  450. @VendurePlugin({
  451. imports: [PluginCommonModule],
  452. shopApiExtensions: {
  453. schema: shopApiExtensions,
  454. // highlight-next-line
  455. resolvers: [WishlistShopResolver],
  456. },
  457. configuration: config => {
  458. // ...
  459. },
  460. })
  461. export class WishlistPlugin {}
  462. ```
  463. :::info
  464. More information about resolvers can be found in the [NestJS docs](https://docs.nestjs.com/graphql/resolvers).
  465. :::
  466. ### Step 7: Specify compatibility
  467. 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.
  468. The compatibility is specified via the `compatibility` property in the plugin metadata:
  469. ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts"
  470. @VendurePlugin({
  471. // ...
  472. // highlight-next-line
  473. compatibility: '^2.0.0',
  474. })
  475. export class WishlistPlugin {}
  476. ```
  477. 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`.
  478. ### Step 8: Add the plugin to the VendureConfig
  479. The final step is to add the plugin to the `VendureConfig` object. This is done in the `vendure-config.ts` file:
  480. ```ts title="src/vendure-config.ts"
  481. import { VendureConfig } from '@vendure/core';
  482. import { WishlistPlugin } from './plugins/wishlist-plugin/wishlist.plugin';
  483. export const config: VendureConfig = {
  484. // ...
  485. plugins: [
  486. // ...
  487. // highlight-next-line
  488. WishlistPlugin,
  489. ],
  490. };
  491. ```
  492. ### Test the plugin
  493. 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:
  494. ```bash
  495. npm run migration:generate wishlist-plugin
  496. ```
  497. Then start the server:
  498. ```bash
  499. npm run dev
  500. ```
  501. Once the server is running, we should be able to log in as an existing Customer, and then add a product to the wishlist:
  502. <Tabs>
  503. <TabItem value="Login mutation" label="Login mutation" default>
  504. ```graphql
  505. mutation Login {
  506. login(username: "alec.breitenberg@gmail.com", password: "test") {
  507. ... on CurrentUser {
  508. id
  509. identifier
  510. }
  511. ... on ErrorResult {
  512. errorCode
  513. message
  514. }
  515. }
  516. }
  517. ```
  518. </TabItem>
  519. <TabItem value="Response" label="Response">
  520. ```json
  521. {
  522. "data": {
  523. "login": {
  524. "id": "9",
  525. "identifier": "alec.breitenberg@gmail.com"
  526. }
  527. }
  528. }
  529. ```
  530. </TabItem>
  531. </Tabs>
  532. <Tabs>
  533. <TabItem value="AddToWishlist mutation" label="AddToWishlist mutation" default>
  534. ```graphql
  535. mutation AddToWishlist {
  536. addToWishlist(productVariantId: "7") {
  537. id
  538. productVariant {
  539. id
  540. name
  541. }
  542. }
  543. }
  544. ```
  545. </TabItem>
  546. <TabItem value="Response" label="Response">
  547. ```json
  548. {
  549. "data": {
  550. "addToWishlist": [
  551. {
  552. "id": "4",
  553. "productVariant": {
  554. "id": "7",
  555. "name": "Wireless Optical Mouse"
  556. }
  557. }
  558. ]
  559. }
  560. }
  561. ```
  562. </TabItem>
  563. </Tabs>
  564. We can then query the wishlist items:
  565. <Tabs>
  566. <TabItem value="GetWishlist mutation" label="GetWishlist mutation" default>
  567. ```graphql
  568. query GetWishlist {
  569. activeCustomerWishlist {
  570. id
  571. productVariant {
  572. id
  573. name
  574. }
  575. }
  576. }
  577. ```
  578. </TabItem>
  579. <TabItem value="Response" label="Response">
  580. ```json
  581. {
  582. "data": {
  583. "activeCustomerWishlist": [
  584. {
  585. "id": "4",
  586. "productVariant": {
  587. "id": "7",
  588. "name": "Wireless Optical Mouse"
  589. }
  590. }
  591. ]
  592. }
  593. }
  594. ```
  595. </TabItem>
  596. </Tabs>
  597. And finally, we can test removing an item from the wishlist:
  598. <Tabs>
  599. <TabItem value="RemoveFromWishlist mutation" label="RemoveFromWishlist mutation" default>
  600. ```graphql
  601. mutation RemoveFromWishlist {
  602. removeFromWishlist(itemId: "4") {
  603. id
  604. productVariant {
  605. name
  606. }
  607. }
  608. }
  609. ```
  610. </TabItem>
  611. <TabItem value="Response" label="Response">
  612. ```json
  613. {
  614. "data": {
  615. "removeFromWishlist": []
  616. }
  617. }
  618. ```
  619. </TabItem>
  620. </Tabs>