content
stringlengths
29
370k
--- title: "DefaultTaxZoneStrategy" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## DefaultTaxZoneStrategy <GenerationInfo sourceFile="packages/core/src/config/tax/default-tax-zone-strategy.ts" sourceLine="12" packageName="@vendure/core" /> A default method of determining Zone for tax calculations. ```ts title="Signature" class DefaultTaxZoneStrategy implements TaxZoneStrategy { determineTaxZone(ctx: RequestContext, zones: Zone[], channel: Channel, order?: Order) => Zone; } ``` * Implements: <code><a href='/reference/typescript-api/tax/tax-zone-strategy#taxzonestrategy'>TaxZoneStrategy</a></code> <div className="members-wrapper"> ### determineTaxZone <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, zones: <a href='/reference/typescript-api/entities/zone#zone'>Zone</a>[], channel: <a href='/reference/typescript-api/entities/channel#channel'>Channel</a>, order?: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/entities/zone#zone'>Zone</a>`} /> </div>
--- title: "Tax" isDefaultIndex: true generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; import DocCardList from '@theme/DocCardList'; <DocCardList />
--- title: "TaxLineCalculationStrategy" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## TaxLineCalculationStrategy <GenerationInfo sourceFile="packages/core/src/config/tax/tax-line-calculation-strategy.ts" sourceLine="29" packageName="@vendure/core" /> This strategy defines how the TaxLines on OrderItems are calculated. By default, the <a href='/reference/typescript-api/tax/default-tax-line-calculation-strategy#defaulttaxlinecalculationstrategy'>DefaultTaxLineCalculationStrategy</a> is used, which directly applies a single TaxLine based on the applicable <a href='/reference/typescript-api/entities/tax-rate#taxrate'>TaxRate</a>. However, custom strategies may use any suitable method for calculating TaxLines. For example, a third-party tax API or a lookup of a custom tax table may be used. :::info This is configured via the `taxOptions.taxLineCalculationStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface TaxLineCalculationStrategy extends InjectableStrategy { calculate(args: CalculateTaxLinesArgs): TaxLine[] | Promise<TaxLine[]>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### calculate <MemberInfo kind="method" type={`(args: <a href='/reference/typescript-api/tax/tax-line-calculation-strategy#calculatetaxlinesargs'>CalculateTaxLinesArgs</a>) => TaxLine[] | Promise&#60;TaxLine[]&#62;`} /> This method is called when calculating the Order prices. Since it will be called whenever an Order is modified in some way (adding/removing items, applying promotions, setting ShippingMethod etc), care should be taken so that calling the function does not adversely impact overall performance. For example, by using caching and only calling external APIs when absolutely necessary. </div> ## CalculateTaxLinesArgs <GenerationInfo sourceFile="packages/core/src/config/tax/tax-line-calculation-strategy.ts" sourceLine="47" packageName="@vendure/core" /> ```ts title="Signature" interface CalculateTaxLinesArgs { ctx: RequestContext; order: Order; orderLine: OrderLine; applicableTaxRate: TaxRate; } ``` <div className="members-wrapper"> ### ctx <MemberInfo kind="property" type={`<a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>`} /> ### order <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/order#order'>Order</a>`} /> ### orderLine <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/order-line#orderline'>OrderLine</a>`} /> ### applicableTaxRate <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/tax-rate#taxrate'>TaxRate</a>`} /> </div>
--- title: "TaxOptions" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## TaxOptions <GenerationInfo sourceFile="packages/core/src/config/vendure-config.ts" sourceLine="857" packageName="@vendure/core" /> ```ts title="Signature" interface TaxOptions { taxZoneStrategy?: TaxZoneStrategy; taxLineCalculationStrategy?: TaxLineCalculationStrategy; } ``` <div className="members-wrapper"> ### taxZoneStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/tax/tax-zone-strategy#taxzonestrategy'>TaxZoneStrategy</a>`} default="<a href='/reference/typescript-api/tax/default-tax-zone-strategy#defaulttaxzonestrategy'>DefaultTaxZoneStrategy</a>" /> Defines the strategy used to determine the applicable Zone used in tax calculations. ### taxLineCalculationStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/tax/tax-line-calculation-strategy#taxlinecalculationstrategy'>TaxLineCalculationStrategy</a>`} default="<a href='/reference/typescript-api/tax/default-tax-line-calculation-strategy#defaulttaxlinecalculationstrategy'>DefaultTaxLineCalculationStrategy</a>" /> Defines the strategy used to calculate the TaxLines added to OrderItems. </div>
--- title: "TaxZoneStrategy" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## TaxZoneStrategy <GenerationInfo sourceFile="packages/core/src/config/tax/tax-zone-strategy.ts" sourceLine="28" packageName="@vendure/core" /> Defines how the active <a href='/reference/typescript-api/entities/zone#zone'>Zone</a> is determined for the purposes of calculating taxes. This strategy is used in 2 scenarios: 1. To determine the applicable Zone when calculating the taxRate to apply when displaying ProductVariants. In this case the `order` argument will be undefined, as the request is not related to a specific Order. 2. To determine the applicable Zone when calculating the taxRate on the contents of a specific Order. In this case the `order` argument _will_ be defined, and can be used in the logic. For example, the shipping address can be taken into account. Note that this method is called very often in a typical user session, so any work it performs should be designed with as little performance impact as possible. :::info This is configured via the `taxOptions.taxZoneStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface TaxZoneStrategy extends InjectableStrategy { determineTaxZone( ctx: RequestContext, zones: Zone[], channel: Channel, order?: Order, ): Zone | Promise<Zone> | undefined; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### determineTaxZone <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, zones: <a href='/reference/typescript-api/entities/zone#zone'>Zone</a>[], channel: <a href='/reference/typescript-api/entities/channel#channel'>Channel</a>, order?: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/entities/zone#zone'>Zone</a> | Promise&#60;<a href='/reference/typescript-api/entities/zone#zone'>Zone</a>&#62; | undefined`} /> </div>
--- title: "Testing" weight: 10 date: 2023-07-14T16:57:50.802Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # testing
--- title: "CreateErrorResultGuard" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## createErrorResultGuard <GenerationInfo sourceFile="packages/testing/src/error-result-guard.ts" sourceLine="18" packageName="@vendure/testing" /> Convenience method for creating an <a href='/reference/typescript-api/testing/error-result-guard#errorresultguard'>ErrorResultGuard</a>. Takes a predicate function which tests whether the input is considered successful (true) or an error result (false). Note that the resulting variable must _still_ be type annotated in order for the TypeScript type inference to work as expected: *Example* ```ts const orderResultGuard: ErrorResultGuard<AddItemToOrderResult> = createErrorResultGuard(order => !!order.lines); ``` ```ts title="Signature" function createErrorResultGuard<T>(testFn: (input: T) => boolean): ErrorResultGuard<T> ``` Parameters ### testFn <MemberInfo kind="parameter" type={`(input: T) =&#62; boolean`} />
--- title: "CreateTestEnvironment" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## createTestEnvironment <GenerationInfo sourceFile="packages/testing/src/create-test-environment.ts" sourceLine="60" packageName="@vendure/testing" /> Configures a <a href='/reference/typescript-api/testing/test-server#testserver'>TestServer</a> and a <a href='/reference/typescript-api/testing/simple-graph-qlclient#simplegraphqlclient'>SimpleGraphQLClient</a> for each of the GraphQL APIs for use in end-to-end tests. Returns a <a href='/reference/typescript-api/testing/test-environment#testenvironment'>TestEnvironment</a> object. *Example* ```ts import { createTestEnvironment, testConfig } from '@vendure/testing'; describe('some feature to test', () => { const { server, adminClient, shopClient } = createTestEnvironment(testConfig); beforeAll(async () => { await server.init({ // ... server options }); await adminClient.asSuperAdmin(); }); afterAll(async () => { await server.destroy(); }); // ... end-to-end tests here }); ``` ```ts title="Signature" function createTestEnvironment(config: Required<VendureConfig>): TestEnvironment ``` Parameters ### config <MemberInfo kind="parameter" type={`Required&#60;<a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a>&#62;`} />
--- title: "ErrorResultGuard" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## ErrorResultGuard <GenerationInfo sourceFile="packages/testing/src/error-result-guard.ts" sourceLine="50" packageName="@vendure/testing" /> A utility class which is used to assert the success of an operation which returns a union type of `SuccessType | ErrorResponse [ | ErrorResponse ]`. The methods of this class are used to: 1. assert that the result is a success or error case 2. narrow the type so that TypeScript can correctly infer the properties of the result. *Example* ```ts const orderResultGuard: ErrorResultGuard<AddItemToOrderResult> = createErrorResultGuard(order => !!order.lines); it('errors when quantity is negative', async () => { const { addItemToOrder } = await shopClient.query<AddItemToOrder.Query, AddItemToOrder.Mutation>(ADD_ITEM_TO_ORDER, { productVariantId: 42, quantity: -1, }); // The test will fail orderResultGuard.assertErrorResult(addItemToOrder); // the type of `addItemToOrder` has now been // narrowed to only include the ErrorResult types. expect(addItemToOrder.errorCode).toBe(ErrorCode.NegativeQuantityError); } ``` ```ts title="Signature" class ErrorResultGuard<T> { constructor(testFn: (input: T) => boolean) isSuccess(input: T | any) => input is T; assertSuccess(input: T | R) => asserts input is T; assertErrorResult(input: T | R) => asserts input is R; } ``` <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(testFn: (input: T) =&#62; boolean) => ErrorResultGuard`} /> ### isSuccess <MemberInfo kind="method" type={`(input: T | any) => input is T`} /> A type guard which returns `true` if the input passes the `testFn` predicate. ### assertSuccess <MemberInfo kind="method" type={`(input: T | R) => asserts input is T`} /> Asserts (using the testing library's `fail()` function) that the input is successful, i.e. it passes the `testFn`. ### assertErrorResult <MemberInfo kind="method" type={`(input: T | R) => asserts input is R`} /> Asserts (using the testing library's `fail()` function) that the input is not successful, i.e. it does not pass the `testFn`. </div>
--- title: "GetSuperadminContext" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## getSuperadminContext <GenerationInfo sourceFile="packages/testing/src/utils/get-superadmin-context.ts" sourceLine="11" packageName="@vendure/testing" /> Creates a <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a> configured for the default Channel with the activeUser set as the superadmin user. Useful for populating data. ```ts title="Signature" function getSuperadminContext(app: INestApplicationContext): Promise<RequestContext> ``` Parameters ### app <MemberInfo kind="parameter" type={`INestApplicationContext`} />
--- title: "Testing" isDefaultIndex: true generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; import DocCardList from '@theme/DocCardList'; <DocCardList />
--- title: "RegisterInitializer" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## registerInitializer <GenerationInfo sourceFile="packages/testing/src/initializers/initializers.ts" sourceLine="16" packageName="@vendure/testing" /> Registers a <a href='/reference/typescript-api/testing/test-db-initializer#testdbinitializer'>TestDbInitializer</a> for the given database type. Should be called before invoking <a href='/reference/typescript-api/testing/create-test-environment#createtestenvironment'>createTestEnvironment</a>. ```ts title="Signature" function registerInitializer(type: DataSourceOptions['type'], initializer: TestDbInitializer<any>): void ``` Parameters ### type <MemberInfo kind="parameter" type={`DataSourceOptions['type']`} /> ### initializer <MemberInfo kind="parameter" type={`<a href='/reference/typescript-api/testing/test-db-initializer#testdbinitializer'>TestDbInitializer</a>&#60;any&#62;`} />
--- title: "SimpleGraphQLClient" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## SimpleGraphQLClient <GenerationInfo sourceFile="packages/testing/src/simple-graphql-client.ts" sourceLine="40" packageName="@vendure/testing" /> A minimalistic GraphQL client for populating and querying test data. ```ts title="Signature" class SimpleGraphQLClient { constructor(vendureConfig: Required<VendureConfig>, apiUrl: string = '') setAuthToken(token: string) => ; setChannelToken(token: string | null) => ; getAuthToken() => string; query(query: DocumentNode | TypedDocumentNode<T, V>, variables?: V, queryParams?: QueryParams) => Promise<T>; fetch(url: string, options: RequestInit = {}) => Promise<Response>; queryStatus(query: DocumentNode, variables?: V) => Promise<number>; asUserWithCredentials(username: string, password: string) => ; asSuperAdmin() => ; asAnonymousUser() => ; fileUploadMutation(options: { mutation: DocumentNode; filePaths: string[]; mapVariables: (filePaths: string[]) => any; }) => Promise<any>; } ``` <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(vendureConfig: Required&#60;<a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a>&#62;, apiUrl: string = '') => SimpleGraphQLClient`} /> ### setAuthToken <MemberInfo kind="method" type={`(token: string) => `} /> Sets the authToken to be used in each GraphQL request. ### setChannelToken <MemberInfo kind="method" type={`(token: string | null) => `} /> Sets the authToken to be used in each GraphQL request. ### getAuthToken <MemberInfo kind="method" type={`() => string`} /> Returns the authToken currently being used. ### query <MemberInfo kind="method" type={`(query: DocumentNode | TypedDocumentNode&#60;T, V&#62;, variables?: V, queryParams?: QueryParams) => Promise&#60;T&#62;`} /> Performs both query and mutation operations. ### fetch <MemberInfo kind="method" type={`(url: string, options: RequestInit = {}) => Promise&#60;Response&#62;`} /> Performs a raw HTTP request to the given URL, but also includes the authToken & channelToken headers if they have been set. Useful for testing non-GraphQL endpoints, e.g. for plugins which make use of REST controllers. ### queryStatus <MemberInfo kind="method" type={`(query: DocumentNode, variables?: V) => Promise&#60;number&#62;`} /> Performs a query or mutation and returns the resulting status code. ### asUserWithCredentials <MemberInfo kind="method" type={`(username: string, password: string) => `} /> Attempts to log in with the specified credentials. ### asSuperAdmin <MemberInfo kind="method" type={`() => `} /> Logs in as the SuperAdmin user. ### asAnonymousUser <MemberInfo kind="method" type={`() => `} /> Logs out so that the client is then treated as an anonymous user. ### fileUploadMutation <MemberInfo kind="method" type={`(options: { mutation: DocumentNode; filePaths: string[]; mapVariables: (filePaths: string[]) =&#62; any; }) => Promise&#60;any&#62;`} /> Perform a file upload mutation. Upload spec: https://github.com/jaydenseric/graphql-multipart-request-spec Discussion of issue: https://github.com/jaydenseric/apollo-upload-client/issues/32 </div>
--- title: "TestConfig" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## testConfig <GenerationInfo sourceFile="packages/testing/src/config/test-config.ts" sourceLine="42" packageName="@vendure/testing" /> A <a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a> object used for e2e tests. This configuration uses sqljs as the database and configures some special settings which are optimized for e2e tests: * `entityIdStrategy: new TestingEntityIdStrategy()` This ID strategy uses auto-increment IDs but encodes all IDs to be prepended with the string `'T_'`, so ID `1` becomes `'T_1'`. * `logger: new NoopLogger()` Do no output logs by default * `assetStorageStrategy: new TestingAssetStorageStrategy()` This strategy does not actually persist any binary data to disk. * `assetPreviewStrategy: new TestingAssetPreviewStrategy()` This strategy is a no-op. ## Logging By default, the testConfig does not output any log messages. This is most desirable to keep a clean CI output. However, for debugging purposes, it can make it hard to figure out why tests fail. You can enable default logging behaviour with the environment variable `LOG`: ``` LOG=true yarn e2e ```
--- title: "TestDbInitializer" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## TestDbInitializer <GenerationInfo sourceFile="packages/testing/src/initializers/test-db-initializer.ts" sourceLine="23" packageName="@vendure/testing" /> Defines how the e2e TestService sets up a particular DB to run a single test suite. The `@vendure/testing` package ships with initializers for sql.js, MySQL & Postgres. Custom initializers can be created by implementing this interface and registering it with the <a href='/reference/typescript-api/testing/register-initializer#registerinitializer'>registerInitializer</a> function: *Example* ```ts export class CockroachDbInitializer implements TestDbInitializer<CockroachConnectionOptions> { // database-specific implementation goes here } registerInitializer('cockroachdb', new CockroachDbInitializer()); ``` ```ts title="Signature" interface TestDbInitializer<T extends BaseConnectionOptions> { init(testFileName: string, connectionOptions: T): Promise<T>; populate(populateFn: () => Promise<void>): Promise<void>; destroy(): void | Promise<void>; } ``` <div className="members-wrapper"> ### init <MemberInfo kind="method" type={`(testFileName: string, connectionOptions: T) => Promise&#60;T&#62;`} /> Responsible for creating a database for the current test suite. Typically, this method will: * use the testFileName parameter to derive a database name * create the database * mutate the `connetionOptions` object to point to that new database ### populate <MemberInfo kind="method" type={`(populateFn: () =&#62; Promise&#60;void&#62;) => Promise&#60;void&#62;`} /> Execute the populateFn to populate your database. ### destroy <MemberInfo kind="method" type={`() => void | Promise&#60;void&#62;`} /> Clean up any resources used during the init() phase (i.e. close open DB connections) </div>
--- title: "TestEnvironment" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## TestEnvironment <GenerationInfo sourceFile="packages/testing/src/create-test-environment.ts" sourceLine="13" packageName="@vendure/testing" /> The return value of <a href='/reference/typescript-api/testing/create-test-environment#createtestenvironment'>createTestEnvironment</a>, containing the test server and clients for the Shop API and Admin API. ```ts title="Signature" interface TestEnvironment { server: TestServer; adminClient: SimpleGraphQLClient; shopClient: SimpleGraphQLClient; } ``` <div className="members-wrapper"> ### server <MemberInfo kind="property" type={`<a href='/reference/typescript-api/testing/test-server#testserver'>TestServer</a>`} /> A Vendure server instance against which GraphQL requests can be made. ### adminClient <MemberInfo kind="property" type={`<a href='/reference/typescript-api/testing/simple-graph-qlclient#simplegraphqlclient'>SimpleGraphQLClient</a>`} /> A GraphQL client configured for the Admin API. ### shopClient <MemberInfo kind="property" type={`<a href='/reference/typescript-api/testing/simple-graph-qlclient#simplegraphqlclient'>SimpleGraphQLClient</a>`} /> A GraphQL client configured for the Shop API. </div>
--- title: "TestServerOptions" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## TestServerOptions <GenerationInfo sourceFile="packages/testing/src/types.ts" sourceLine="14" packageName="@vendure/testing" /> Configuration options used to initialize an instance of the <a href='/reference/typescript-api/testing/test-server#testserver'>TestServer</a>. ```ts title="Signature" interface TestServerOptions { productsCsvPath?: string; initialData: InitialData; customerCount?: number; logging?: boolean; } ``` <div className="members-wrapper"> ### productsCsvPath <MemberInfo kind="property" type={`string`} /> The path to an optional CSV file containing product data to import. ### initialData <MemberInfo kind="property" type={`<a href='/reference/typescript-api/import-export/initial-data#initialdata'>InitialData</a>`} /> An object containing non-product data which is used to populate the database. ### customerCount <MemberInfo kind="property" type={`number`} default="10" /> The number of fake Customers to populate into the database. ### logging <MemberInfo kind="property" type={`boolean`} default="false" /> Set this to `true` to log some information about the database population process. </div>
--- title: "TestServer" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## TestServer <GenerationInfo sourceFile="packages/testing/src/test-server.ts" sourceLine="17" packageName="@vendure/testing" /> A real Vendure server against which the e2e tests should be run. ```ts title="Signature" class TestServer { public app: INestApplication; constructor(vendureConfig: Required<VendureConfig>) init(options: TestServerOptions) => Promise<void>; bootstrap() => ; destroy() => ; } ``` <div className="members-wrapper"> ### app <MemberInfo kind="property" type={`INestApplication`} /> ### constructor <MemberInfo kind="method" type={`(vendureConfig: Required&#60;<a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a>&#62;) => TestServer`} /> ### init <MemberInfo kind="method" type={`(options: <a href='/reference/typescript-api/testing/test-server-options#testserveroptions'>TestServerOptions</a>) => Promise&#60;void&#62;`} /> Bootstraps an instance of Vendure server and populates the database according to the options passed in. Should be called in the `beforeAll` function. The populated data is saved into an .sqlite file for each test file. On subsequent runs, this file is loaded so that the populate step can be skipped, which speeds up the tests significantly. ### bootstrap <MemberInfo kind="method" type={`() => `} /> Bootstraps a Vendure server instance. Generally the `.init()` method should be used, as that will also populate the test data. However, the `bootstrap()` method is sometimes useful in tests which need to start and stop a Vendure instance multiple times without re-populating data. ### destroy <MemberInfo kind="method" type={`() => `} /> Destroy the Vendure server instance and clean up all resources. Should be called after all tests have run, e.g. in an `afterAll` function. </div>
--- title: "TestingLogger" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## TestingLogger <GenerationInfo sourceFile="packages/testing/src/testing-logger.ts" sourceLine="55" packageName="@vendure/testing" /> The TestingLogger can be used in unit tests or e2e tests to make assertions on whether the various Logger methods have been called, and which arguments. Here's some examples of how to use it in e2e tests and unit tests. In both cases we are using the Jest testing framework, but the TestingLogger should work with other similar frameworks (e.g. replacing `jest.fn()` with `jasmine.createSpy()`). *Example* ```ts // e2e test example import { createTestEnvironment, TestingLogger } from '@vendure/testing'; const testingLogger = new TestingLogger(() => jest.fn()); const { server, adminClient, shopClient } = createTestEnvironment({ ...testConfig, logger: testingLogger, }); // e2e testing setup omitted it('should log an error', async () => { // The `errorSpy` property exposes the Jest mock function testingLogger.errorSpy.mockClear(); await doSomethingThatErrors(); expect(testingLogger.errorSpy).toHaveBeenCalled(); }); ``` *Example* ```ts // unit test example import { Test } from '@nestjs/testing'; import { Logger } from '@vendure/core'; import { TestingLogger } from '@vendure/testing'; beforeEach(async () => { const moduleRef = await Test.createTestingModule({ // Nest testing setup omitted }).compile(); Logger.useLogger(testingLogger); moduleRef.useLogger(new Logger()); } ``` ```ts title="Signature" class TestingLogger<Spy extends (...args: any[]) => any> implements VendureLogger { constructor(createSpyFn: () => Spy) debugSpy: Spy; errorSpy: Spy; infoSpy: Spy; verboseSpy: Spy; warnSpy: Spy; debug(message: string, context?: string) => void; error(message: string, context?: string, trace?: string) => void; info(message: string, context?: string) => void; verbose(message: string, context?: string) => void; warn(message: string, context?: string) => void; } ``` * Implements: <code><a href='/reference/typescript-api/logger/vendure-logger#vendurelogger'>VendureLogger</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(createSpyFn: () =&#62; Spy) => TestingLogger`} /> ### debugSpy <MemberInfo kind="property" type={`Spy`} /> ### errorSpy <MemberInfo kind="property" type={`Spy`} /> ### infoSpy <MemberInfo kind="property" type={`Spy`} /> ### verboseSpy <MemberInfo kind="property" type={`Spy`} /> ### warnSpy <MemberInfo kind="property" type={`Spy`} /> ### debug <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### error <MemberInfo kind="method" type={`(message: string, context?: string, trace?: string) => void`} /> ### info <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### verbose <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### warn <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> </div>
--- title: "Worker" weight: 10 date: 2023-07-14T16:57:49.413Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # worker
--- title: "BootstrapWorker" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## bootstrapWorker <GenerationInfo sourceFile="packages/core/src/bootstrap.ts" sourceLine="170" packageName="@vendure/core" /> Bootstraps a Vendure worker. Resolves to a <a href='/reference/typescript-api/worker/vendure-worker#vendureworker'>VendureWorker</a> object containing a reference to the underlying NestJs [standalone application](https://docs.nestjs.com/standalone-applications) as well as convenience methods for starting the job queue and health check server. Read more about the [Vendure Worker](/guides/developer-guide/worker-job-queue/). *Example* ```ts import { bootstrapWorker } from '@vendure/core'; import { config } from './vendure-config'; bootstrapWorker(config) .then(worker => worker.startJobQueue()) .then(worker => worker.startHealthCheckServer({ port: 3020 })) .catch(err => { console.log(err); process.exit(1); }); ``` ```ts title="Signature" function bootstrapWorker(userConfig: Partial<VendureConfig>, options?: BootstrapWorkerOptions): Promise<VendureWorker> ``` Parameters ### userConfig <MemberInfo kind="parameter" type={`Partial&#60;<a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a>&#62;`} /> ### options <MemberInfo kind="parameter" type={`<a href='/reference/typescript-api/worker/bootstrap-worker#bootstrapworkeroptions'>BootstrapWorkerOptions</a>`} /> ## BootstrapWorkerOptions <GenerationInfo sourceFile="packages/core/src/bootstrap.ts" sourceLine="58" packageName="@vendure/core" since="2.2.0" /> Additional options that can be used to configure the bootstrap process of the Vendure worker. ```ts title="Signature" interface BootstrapWorkerOptions { nestApplicationContextOptions: NestApplicationContextOptions; } ``` <div className="members-wrapper"> ### nestApplicationContextOptions <MemberInfo kind="property" type={`NestApplicationContextOptions`} /> These options get passed directly to the `NestFactory.createApplicationContext` method. </div>
--- title: "Worker" isDefaultIndex: true generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; import DocCardList from '@theme/DocCardList'; <DocCardList />
--- title: "VendureWorker" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## VendureWorker <GenerationInfo sourceFile="packages/core/src/worker/vendure-worker.ts" sourceLine="13" packageName="@vendure/core" /> This object is created by calling the <a href='/reference/typescript-api/worker/bootstrap-worker#bootstrapworker'>bootstrapWorker</a> function. ```ts title="Signature" class VendureWorker { public app: INestApplicationContext; constructor(app: INestApplicationContext) startJobQueue() => Promise<VendureWorker>; startHealthCheckServer(healthCheckConfig: WorkerHealthCheckConfig) => Promise<VendureWorker>; } ``` <div className="members-wrapper"> ### app <MemberInfo kind="property" type={`INestApplicationContext`} /> A reference to the `INestApplicationContext` object, which represents the NestJS [standalone application](https://docs.nestjs.com/standalone-applications) instance. ### constructor <MemberInfo kind="method" type={`(app: INestApplicationContext) => VendureWorker`} /> ### startJobQueue <MemberInfo kind="method" type={`() => Promise&#60;<a href='/reference/typescript-api/worker/vendure-worker#vendureworker'>VendureWorker</a>&#62;`} /> Starts the job queues running so that the worker can handle background jobs. ### startHealthCheckServer <MemberInfo kind="method" type={`(healthCheckConfig: <a href='/reference/typescript-api/worker/worker-health-check-config#workerhealthcheckconfig'>WorkerHealthCheckConfig</a>) => Promise&#60;<a href='/reference/typescript-api/worker/vendure-worker#vendureworker'>VendureWorker</a>&#62;`} since="1.2.0" /> Starts a simple http server which can be used as a health check on the worker instance. This endpoint can be used by container orchestration services such as Kubernetes to verify whether the worker is running. </div>
--- title: "WorkerHealthCheckConfig" isDefaultIndex: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> import MemberInfo from '@site/src/components/MemberInfo'; import GenerationInfo from '@site/src/components/GenerationInfo'; import MemberDescription from '@site/src/components/MemberDescription'; ## WorkerHealthCheckConfig <GenerationInfo sourceFile="packages/core/src/worker/worker-health.service.ts" sourceLine="14" packageName="@vendure/core" since="1.2.0" /> Specifies the configuration for the Worker's HTTP health check endpoint. ```ts title="Signature" interface WorkerHealthCheckConfig { port: number; hostname?: string; route?: string; } ``` <div className="members-wrapper"> ### port <MemberInfo kind="property" type={`number`} /> The port on which the worker will listen ### hostname <MemberInfo kind="property" type={`string`} default="'localhost'" /> The hostname ### route <MemberInfo kind="property" type={`string`} default="'/health'" /> The route at which the health check is available. </div>
--- title: "Administrator Guide" weight: 1 --- # Administrator Guide This section is for store owners and staff who are charged with running a Vendure-based store. This guide assumes that your Vendure instance is running the AdminUiPlugin. We will roughly structure this guide to conform to the default layout of the Admin UI main navigation menu.
--- title: "Collections" weight: 2 --- # Collections Collections allow you to group ProductVariants together by various criteria. A typical use of Collections is to create a hierarchical category tree which can be used in a navigation menu in your storefront. ## Populating Collections Collections are _dynamic_, which means that you define a set of rules, and Vendure will automatically populate the Collection with ProductVariants according to those rules. The rules are defined by **filters**. A Collection can define multiple filters, for example: * Include all ProductVariants with a certain FacetValue * Include all ProductVariants whose name includes the word "sale" ## Nesting Collections Collections can be nested inside one another, as many levels deep as needed. When populating a nested Collection, its own filters _plus the filters of all Collections above it_ are used to calculate the contents. ## Public vs Private Collections A Collection can be made private, meaning that it will not be available in the storefront. This can be useful when you need to organize your inventory for internal purposes.
--- title: "Facets" weight: 1 --- # Facets Facets are the primary means to attach structured data to your Products & ProductVariants. Typical uses of Facets include: * Enabling faceted search & filtering in the storefront * Organizing Products into Collections * Labelling Products for inclusion in Promotions ![./screen-facet-list.webp](./screen-facet-list.webp) A Facet has one or more FacetValues, for example: * Facet: "Brand" * Values: "Apple", "Logitech", "Sony", "LG" ... ## Assigning to Products & Variants In the Product detail page, you can assign FacetValues by clicking the _ADD FACETS_ button toward the bottom of the Product or ProductVariant views. ![./screen-facet-add.webp](./screen-facet-add.webp) ## Public vs Private Facets The visibility of a Facet can be set to either _public_ or _private_. * **Public** facets are visible via the Shop API, meaning they can be listed in the storefront and used for faceted searches. * **Private** facets are only visible to Administrators, and cannot be used in storefront faceted searches. Private facets can be useful for labelling Products for internal use. For example, you could create a "profit margin" Facet with "high" and "low" values. You wouldn't want to display these in the storefront, but you may want to use them e.g. in Promotion logic.
--- title: "Catalog" weight: 1 ---
--- title: "Products" weight: 0 --- # Products Products represent the items you want to sell to your customers. ## Products vs ProductVariants In Vendure, every Product has one or more _ProductVariants_. You can think of a Product as a "container" which houses the variants: ![./product-variants.png](./product-variants.png) In the diagram above you'll notice that it is the ProductVariants which have an SKU (_stock-keeping unit_: a unique product code) and a price. **Products** provide the overall name, description, slug, images. A product _does not_ have a price, sku, or stock level. **ProductVariants** have a price, sku, stock level, tax settings. They are the actual things that get added to orders and purchased. ## Tracking Inventory Vendure can track the stock levels of each of your ProductVariants. This is done by setting the "track inventory" option to "track" (or "inherit from global settings" if the [global setting]({{< relref "/user-guide/settings/global-settings" >}}) is set to track). ![./screen-inventory.webp](./screen-inventory.webp) When tracking inventory: * When a customer checks out, the contents of the order will be "allocated". This means that the stock has not yet been sold, but it is no longer available to purchase (no longer _saleable_). * Once a Fulfillment has been created (see the Orders section), those allocated items will be converted into sales, meaning the stock level will be lowered by the corresponding quantity. * If a customer attempts to add more of a ProductVariant than are currently _saleable_, they will encounter an error. ### Back orders Back orders can be enabled by setting a **negative value** as the "Out-of-stock threshold". This can be done via [global settings]({{< relref "/user-guide/settings/global-settings" >}}) or on a per-variant basis.
--- title: "Customers" weight: 2 --- # Customers A Customer is anybody who has: * Placed an order * Registered an account The Customers section allows you to view and search for your customers. Clicking "edit" in the list view brings up the detail view, allowing you to edit the customer details and view orders and history. ## Guest, Registered, Verified * **Guest:** Vendure allows "guest checkouts", which means people may place orders without needing to register an account with the storefront. * **Registered:** When a customer registers for an account (using their email address by default), they are assigned this status. * **Verified:** A registered customer becomes verified once they have been able to confirm ownership of their email account. Note that if alternative authentication methods are set up on your store (e.g. Facebook login), then this workflow might be slightly different. ## Customer Groups Customer Groups can be used for things like: * Grouping wholesale customers so that alternative tax calculations may be applied * Grouping members of a loyalty scheme for access to exclusive Promotions * Segmenting customers for other marketing purposes ![./screen-customer-group.webp](./screen-customer-group.webp)
--- title: "Localization" weight: 10 --- # Localization Vendure supports **customer-facing** (Shop API) localization by allowing you to define translations for the following objects: * Collections * Countries * Facets * FacetValue * Products * ProductOptions * ProductOptionGroups * ProductVariants * ShippingMethods Vendure supports **admin-facing** (Admin API and Admin UI) localization by allowing you to define translations for labels and descriptions of the following objects: * CustomFields * CollectionFilters * PaymentMethodHandlers * PromotionActions * PromotionConditions * ShippingCalculators * ShippingEligibilityCheckers ## How to enable languages To select the set of languages you wish to create translations for, set them in the [global settings]({{< relref "/user-guide/settings/global-settings" >}}). Once more than one language is enabled, you will see a language switcher appear when editing the object types listed above. ![../settings/screen-translations.webp](../settings/screen-translations.webp) ## Setting the Admin UI language Separately, you can change the language used in the Admin UI from the menu in the top right. Note that changing the UI language has no effect on the localization of your products etc. ![./screen-ui-language.webp](./screen-ui-language.webp)
--- title: "Draft Orders" --- # Draft Orders {{% alert "warning" %}} Note: Draft Orders are available from Vendure v1.8+ {{% /alert %}} Draft Orders are used when an Administrator would like to manually create an order via the Admin UI. For example, this can be useful when: - A customer phones up to place an order - A customer wants to place an order in person - You want to create an order on behalf of a customer, e.g. for a quote. - When testing Promotions To create a Draft Order, click the **"Create draft order"** button from the Order List view. From there you can: - Add ProductVariants to the Order using the search input marked "Add item to order" - Optionally activate coupon codes to trigger Promotions - Set the customer, shipping and billing addresses - Select the shipping method Once ready, click the **"Complete draft"** button to convert this Order from a Draft into a regular Order. At this stage the order can be paid for, and you can manually record the payment details. {{% alert "primary" %}} Note: Draft Orders do not appear in a Customer's order history in the storefront (Shop API) while still in the "Draft" state. {{% /alert %}}
--- title: "Orders" weight: 3 --- # Orders An Order is created whenever someone adds an item to their cart in the storefront. In Vendure, there is no distinction between a "cart" and an "order". Thus a "cart" is just an Order which has not yet passed through the checkout process. ## The Order Workflow The exact set of stages that an Order goes through can be customized in Vendure to suit your particular business needs, but we can look at the default steps to get a good idea of the typical workflow: ![./order-state-diagram-for-admin.png](./order-state-diagram-for-admin.png) When a new Order arrives, you would: 1. **Settle the payment** if not already done (this may or may not be needed depending on the way your payment provider is configured). ![./screen-settle-payment.webp](./screen-settle-payment.webp) 1. **Create a Fulfillment** by clicking the "Fulfill Order" button in the top-right of the order detail page. A Fulfillment represents the physical package which will be sent to the customer. You may split up your order into multiple Fulfillments, if that makes sense from a logistical point of view. ![./screen-fulfillment.webp](./screen-fulfillment.webp) 1. **Mark the Fulfillment as "shipped"** once the physical package leaves your warehouse. 1. **Mark the Fulfillment as "delivered"** once you have notice of the package arriving with the customer. ![./screen-fulfillment-shipped.webp](./screen-fulfillment-shipped.webp) ## Refunds You can refund one or more items from an Order by clicking this menu item, which is available once the payments are settled: ![./screen-refund-button.webp](./screen-refund-button.webp) This will bring up a dialog which allows you to select which items to refund, as well as whether to refund shipping. You can also make an arbitrary adjustment to the refund amount if needed. A Refund is then made against the payment method used in that order. Some payment methods will handle refunds automatically, and others will expect you to perform the refund manually in your payment provider's admin interface, and then record the fact manually. ## Cancellation One or more items may also be cancelled in a similar way to how refunds are handled. Performing a cancellation will return the selected items back into stock. Cancellations and refunds are often done together, but do not have to be. For example, you may refund a faulty item without requiring the customer to return it. This would be a pure refund. ## Modifying an Order An Order can be modified after checkout is completed. ![./screen-modify-button.webp](./screen-modify-button.webp) Modification allows you to: * Alter the quantities of any items in the order * Remove items from the order * Add new items to the order * Add arbitrary surcharges or discounts * Alter the shipping & billing address ![./screen-modification.webp](./screen-modification.webp) Once you have made the desired modifications, you preview the changes including the price difference. If the modifications have resulted in an increased price (as in the above example), the Order will then be set into the "Arranging additional payment" state. This allows you to process another payment from the customer to make up the price difference. On the other hand, if the new price is less than what was originally paid (e.g. if the quantity is decreased), then a Refund will be generated against the payment method used.
--- title: "Promotions" weight: 4 --- # Promotions Promotions are a means of offering discounts on an order based on various criteria. A Promotion consists of _conditions_ and _actions_. * **conditions** are the rules which determine whether the Promotion should be applied to the order. * **actions** specify exactly how this Promotion should modify the order. ## Promotion Conditions A condition defines the criteria that must be met for the Promotion to be activated. Vendure comes with some simple conditions provided which enable things like: * If the order total is at least $X * Buy at least X of a certain product * But at least X of any product with the specified [FacetValues]({{< relref "/user-guide/catalog/facets" >}}) * If the customer is a member of the specified [Customer Group]({{< relref "/user-guide/customers" >}}#customer-groups) Vendure allows completely custom conditions to be defined by your developers, implementing the specific logic needed by your business. ## Coupon codes A coupon code can be any text which will activate a Promotion. A coupon code can be used in conjunction with conditions if desired. {{< alert "primary" >}} Note: Promotions **must** have either a **coupon code** _or_ **at least 1 condition** defined. {{< /alert >}} ## Promotion Actions If all the defined conditions pass (or if the specified coupon code is used), then the actions are performed on the order. Vendure comes with some commonly-used actions which allow promotions like: * Discount the whole order by a fixed amount * Discount the whole order by a percentage * Discount selected products by a percentage * Free shipping ## Coupon code per-customer limit If a per-customer limit is specified, then the specified coupon code may only be used that many times by a single Customer. For guest checkouts, the "same customer" status is determined by the email address used when checking out.
--- title: "Administrators & Roles" --- # Administrators & Roles An **administrator** is a staff member who has access to the Admin UI, and is able to view and modify some or all of the items and settings. The exact permissions of _what_ a given administrator may view and modify is defined by which **roles** are assigned to that administrator. ## Defining a Role The role detail page allows you to create a new role or edit an existing one. A role can be thought of as a list of permissions. Permissions are usually divided into four types: * **Create** allows you to create new items, e.g. "CreateProduct" will allow one to create a new product. * **Read** allows you to view items, but not modify or delete them. * **Update** allows you to make changes to existing items, but not to create new ones. * **Delete** allows you to delete items. Vendure comes with a few pre-defined roles for commonly-needed tasks, but you are free to modify these or create your own. In general, it is advisable to create roles with the fewest amount of privileges needed for the staff member to do their jobs. For example, a marketing manager would need to be able to create, read, update and delete promotions, but probably doesn't need to be able to update or delete payment methods. ### The SuperAdmin role This is a special role which cannot be deleted or modified. This role grants _all permissions_ and is used to set up the store initially, and make certain special changes (such as creating new Channels). ## Creating Administrators For each individual that needs to log in to the Admin UI, you should create a new administrator account. Apart from filling in their details and selecting a strong password, you then need to assign at least one role. Roles "add together", meaning that when more than one role is assigned, the combined set of permissions of all assigned roles is granted to that administrator. Thus, it is possible to create a set of specific roles "Inventory Manager", "Order Manager", "Customer Services", "Marketing Manager", and _compose_ them together as needed.
--- title: "Channels" --- # Channels Channels allow you to split your store into multiple sub-stores, each of which can have its own selection of inventory, customers, orders, shipping methods etc. There are various reasons why you might want to do this: * Creating distinct stores for different countries, each with country-specific pricing, shipping and payment rules. * Implementing a multi-tenant application where many merchants have their own store, each confined to its own channel. * Implementing a marketplace where each seller has their own channel. Each channel defines some basic default settings - currency, language, tax options. There is _always_ a **default channel** - this is the "root" channel which contains _everything_, and any sub-channels can then contain a subset of the contents of the default channel.
--- title: "Countries & Zones" --- # Countries & Zones **Countries** are where you define the list of countries which are relevant to your operations. This does not only include those countries you ship to, but also those countries which may appear on a billing address. By default, Vendure includes all countries in the list, but you are free to remove or disable any that you don't need. **Zones** provide a way to group countries. Zones are used mainly for defining [tax rates]({{< relref "/user-guide/settings/taxes" >}}) and can also be used in shipping calculations.
--- title: "Global Settings" --- # Global Settings The global settings allow you to define certain configurations that affect _all_ channels. * **Available languages** defines which languages you wish to make available for translations. When more than one language has been enabled, you will see the language switcher appear when viewing translatable objects such as products, collections, facets and shipping methods. ![./screen-translations.webp](./screen-translations.webp) * **Global out-of-stock threshold** sets the stock level at which a product variant is considered to be out of stock. Using a negative value enables backorder support. This setting can be overridden by individual product variants (see the [tracking inventory]({{< relref "/user-guide/catalog/products" >}}#tracking-inventory) guide). * **Track inventory by default** sets whether stock levels should be tracked. This setting can be overridden by individual product variants (see the [tracking inventory]({{< relref "/user-guide/catalog/products" >}}#tracking-inventory) guide).
--- title: "Settings" weight: 5 ---
--- title: "Payment Methods" --- # Payment Methods Payment methods define how your storefront handles payments. Your storefront may offer multiple payment methods or just one. A Payment method consists of two parts: an **eligibility checker** and a **handler** ## Payment eligibility checker This is an optional part which can be useful in certain situations where you want to limit a payment method based on things like: * Billing address * Order contents or total price * Customer group Since these requirements are particular to your business needs, Vendure does not provide any built-in checkers, but your developers can create one to suit your requirements. ## Payment handler The payment handler contains the actual logic for processing a payment. Again, since there are many ways to handle payments, Vendure only provides a "dummy handler" by default and it is up to your developers to create integrations. Payment handlers can be created which enable payment via: * Popular payment services such as Stripe, Paypal, Braintree, Klarna etc * Pay-on-delivery * Store credit * etc
--- title: "Shipping Methods" --- # Shipping Methods Shipping methods define: * Whether an order is eligible for a particular shipping method * How much the shipping should cost for a given order * How the order will be fulfilled Let's take a closer look at each of these parts: ## Shipping eligibility checker This is how we decide whether a particular shipping method may be applied to an order. This allows you to limit a particular shipping method based on things like: * Minimum order amount * Order weight * Shipping destination * Particular contents of the order * etc. By default, Vendure comes with a checker which can impose a minimum order amount. To implement more complex checks, your developers are able to create custom checkers to suit your requirements. ## Shipping calculator The calculator is used to determine how much to charge for shipping an order. Calculators can be written to implement things like: * Determining shipping based on a 3rd-party service such as Shippo * Looking up prices from data supplied by couriers * Flat-rate shipping By default, Vendure comes with a simple flat-rate shipping calculator. Your developers can create more sophisticated integrations according to your business requirements. ## Fulfillment handler By "fulfillment" we mean how we physically get the goods into the hands of the customer. Common fulfillment methods include: * Courier services such as FedEx, DPD, DHL, etc. * Collection by customer * Delivery via email for digital goods or licenses By default, Vendure comes with a "manual fulfillment handler", which allows you to manually enter the details of whatever actual method is used. For example, if you send the order by courier, you can enter the courier name and parcel number manually when creating an order. Your developers can however create much more sophisticated fulfillment handlers, which can enable things like automated calls to courier APIs, automated label generation, and so on. ## Testing a Shipping Method At the bottom of the shipping method **detail page** you can test the current method by creating a fake order and shipping address and testing a) whether this method would be eligible, and b) how much it would cost. ![./screen-shipping-test.webp](./screen-shipping-test.webp) Additionally, on the shipping method **list page** you can test _all_ shipping methods at once.
--- title: "Taxes" --- # Taxes Taxes represent extra charges on top of the base price of a product. There are various forms of taxes that might be applicable, depending on local laws and the laws of the regions that your business serves. Common forms of applicable taxes are: * Value added tax (VAT) * Goods and services tax (GST) * Sales taxes (as in the USA) ## Tax Category In Vendure every product variant is assigned a **tax category**. In many countries, different rates of tax apply depending on the type of product being sold. For example, in the UK there are three rates of VAT: * Standard rate (20%) * Reduced rate (5%) * Zero rate (0%) Most types of products would fall into the "standard rate" category, but for instance books are classified as "zero rate". ## Tax Rate Tax rates set the rate of tax for a given **tax category** destined for a particular **zone**. They are used by default in Vendure when calculating all taxes. ## Tax Compliance Please note that tax compliance is a complex topic that varies significantly between countries. Vendure does not (and cannot) offer a complete out-of-the-box tax solution which is guaranteed to be compliant with your use-case. What we strive to do is to provide a very flexible set of tools that your developers can use to tailor tax calculations exactly to your needs. These are covered in the [Developer's guide to taxes]({{< relref "/guides/developer-guide/taxes" >}}).
# Scraper This directory contains the config to run the Typesense Docsearch scraper. First you need to copy the `.env.example` file and fill in the values for your Typesense instance. ```bash ### Local usage To populate a locally-running Typesense instance, change the `config.json` file to point to the locally-running docs site: ```json { "start_urls": [ "http://host.docker.internal:3000/" ], "sitemap_urls": [ "http://host.docker.internal:3000/sitemap.xml" ], "allowed_domains": [ "host.docker.internal" ] } ``` Then run: ```bash docker run -it --env-file=.env -e "CONFIG=$(cat config.json | jq -r tostring)" typesense/docsearch-scraper:0.7.0 ```
# Vendure AdminUiPlugin `npm install @vendure/admin-ui-plugin` For documentation, see [docs.vendure.io/reference/core-plugins/admin-ui-plugin/](https://docs.vendure.io/reference/core-plugins/admin-ui-plugin/)
# Vendure Admin UI This is the administration interface for Vendure. It is an Angular application built with the Angular CLI. The UI is powered by the [Clarity Design System](https://clarity.design). ## Structure ### Library The Admin UI is structured as an Angular library conforming to the [ng-packagr format](https://github.com/ng-packagr/ng-packagr). This library is what is published to npm as `@vendure/admin-ui`. The library consists of a set of modules which are accessible from consuming applications as sub-packages: * `@vendure/admin-ui/core` * `@vendure/admin-ui/catalog` * `@vendure/admin-ui/orders` etc. These library packages are located at [./src/lib](./src/lib) When built with `npm run build`, the output will be located in the `./package` sub directory. This is also the root of the published npm package. ### Application In addition to the library, there is also a full application located at [./src/app](./src/app). This application is used both during development of the Admin UI, and also as the "default" Admin UI without any UI extensions, as provided as the default by the [admin-ui-plugin](../admin-ui-plugin). ## Localization Localization of UI strings is handled by [ngx-translate](http://www.ngx-translate.com/). The translation strings should use the [ICU MessageFormat](http://userguide.icu-project.org/formatparse/messages). Translation keys are automatically extracted by running: ``` npm run extract-translations ``` This scan the source files for any translation keys, and add them to each of the translation files located in [`./src/lib/static/i18n-messages/`](./src/lib/static/i18n-messages/). A report is generated for each language detailing what percentage of the translation tokens are translated into that language: ```text Extracting translation tokens for "src\lib\static\i18n-messages\de.json" de: 592 of 650 tokens translated (91%) ``` This report data is also saved to the [i18n-coverage.json](./i18n-coverage.json) file. To add support for a new language, create a new empty json file (`{}`) in the `i18n-messages` directory named `<languageCode>.json`, where `languageCode` is one of the supported codes as given in the [LanguageCode enum type](../core/src/api/schema/common/language-code.graphql), then run `npm run extract-translations` To verify localization changes add `<languageCode>.json` to `./src/lib/static/vendure-ui-config.json` in the array `availableLanguages`. This will make the localization available in Admin UI development mode using `npm run start`
# Vendure AssetServerPlugin The `AssetServerPlugin` serves assets (images and other files) from the local file system. It can also perform on-the-fly image transformations and caches the results for subsequent calls. `npm install @vendure/asset-server-plugin` For documentation, see [docs.vendure.io/reference/core-plugins/asset-server-plugin/](https://docs.vendure.io/reference/core-plugins/asset-server-plugin/)
# @vendure/common This package contains a set of common utility functions and TypeScript types used by multiple Vendure packages. It is not intended to be directly depended upon by an end-user project.
# Vendure A headless [GraphQL](https://graphql.org/) ecommerce framework built on [Node.js](https://nodejs.org) with [Nest](https://nestjs.com/) with [TypeScript](http://www.typescriptlang.org/). ```bash $ npm install @vendure/core ``` ### [www.vendure.io](https://www.vendure.io/) See the [Getting Started](https://www.vendure.io/docs/getting-started/) guide for instructions on use.
# Vendure Create A CLI tool for rapidly scaffolding a new Vendure server application. Heavily inspired by [create-react-app](https://github.com/facebook/create-react-app). ## Usage Vendure Create requires [Node.js](https://nodejs.org/en/) v8.9.0+ to be installed. To create a new project, you may choose one of the following methods: ### npx ```sh npx @vendure/create my-app ``` *[npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) comes with npm 5.2+ and higher.* ### npm ```sh npm init @vendure my-app ``` *`npm init <initializer>` is available in npm 6+* ### Yarn ```sh yarn create @vendure my-app ``` *`yarn create` is available in Yarn 0.25+* It will create a directory called `my-app` inside the current folder. ## Options ### `--use-npm` By default, Vendure Create will detect whether a compatible version of Yarn is installed, and if so will display a prompt to select the preferred package manager. You can override this and force it to use npm with the `--use-npm` flag. ### `--log-level` You can control how much output is generated during the installation and setup with this flag. Valid options are `silent`, `info` and `verbose`. The default is `silent` Example: ```sh npx @vendure/create my-app --log-level verbose ```
# Vendure Dev Server This package is not published to npm. It is used in development of the Vendure server and plugins. ### Running To run the server, run the `start` script. The database configuration can be specified by the `DB=<type>` environment variable: ```bash DB=mysql npm run start DB=postgres npm run start DB=sqlite npm run start ``` The default if no db is specified is mysql. ### Populating data Test data can be populated by running the `populate` script. This uses the same sample data as is used by the Vendure CLI when running `init`, albeit with the additional step of populating some sample customer & address data too. Specify the database as above to populate that database: ```bash DB=sqlite npm run populate ``` ## Testing custom ui extension compilation In order to compile ui extensions within this monorepo, you need to add the following entry to the [temporary admin ui `tsconfig.json`](./custom-admin-ui/tsconfig.json) file: ``` "paths": { "@vendure/admin-ui/*": ["../../admin-ui/package/*"] } ``` ## Load testing This package also contains scripts for load testing the Vendure server. The load testing infrastructure and scripts are located in the [`./load-testing`](./load-testing) directory. Load testing is done with [k6](https://docs.k6.io/), and to run them you will need k6 installed and (in Windows) available in your PATH environment variable so that it can be run with the command `k6`. The load tests assume the existence of the following tables in the database: * `vendure-load-testing-1000` * `vendure-load-testing-10000` * `vendure-load-testing-100000` The npm scripts `load-test:1k`, `load-test:10k` and `load-test:100k` will populate their respective databases with test data and then run the k6 scripts against them. ## Running individual scripts An individual test script may be by specifying the script name as an argument: ``` npm run load-test:1k deep-query.js ``` ## pg_stat_statements The following queries can be used when running load tests against postgres to analyze the queries: ```sql SELECT dbid, (total_time / 1000 / 60) as total, (total_time/calls) as avg, calls, query FROM pg_stat_statements WHERE dbid = <db_id> ORDER BY total DESC LIMIT 100; -- SELECT pg_stat_statements_reset(); ``` ### Results The results of the test are saved to the [`./load-testing/results`](./load-testing/results) directory. Each test run creates two files: * `load-test-<date>-<product-count>.json` Contains a summary of all load tests run * `load-test-<date>-<product-count>-<script-name>.csv` Contains time-series data which can be used to create charts Historical benchmark results with charts can be found in [this Google Sheet](https://docs.google.com/spreadsheets/d/1UaNhmokbNmKDehrnh4m9XO6-DJte-AI-l_Lnji47Qn8/edit?usp=sharing)
# Example multi-vendor marketplace plugin This is an example plugin which demonstrates how to build a multi-vendor marketplace with Vendure. It uses new APIs and features introduced in Vendure v2.0. The parts of the plugin are documented with explanations, and the overall guide can be found in the [Multi-vendor marketplace](https://docs.vendure.io/developer-guide/multi-vendor-marketplaces/) section of the Vendure docs. ## Setup Add this plugin to your VendureConfig: ```ts import { MultivendorPlugin } from './plugins/multivendor-plugin/multivendor.plugin'; plugins: [ MultivendorPlugin.init({ platformFeePercent: 10, platformFeeSKU: 'FEE', }), // ... ] ``` ## Create a Seller Now you can create new sellers with the following mutation in the Shop API: ```graphql mutation RegisterSeller { registerNewSeller(input: { shopName: "Bob's Parts", seller: { firstName: "Bob" lastName: "Dobalina" emailAddress: "bob@bobs-parts.com" password: "test", } }) { id code token } } ``` This mutation will: - Create a new Seller representing the shop "Bob's Parts" - Create a new Channel and associate it with the new Seller - Create a Role & Administrator for Bob to access his shop admin account - Create a ShippingMethod for Bob's shop - Create a StockLocation for Bob's shop Bob can then go and sign in to the Admin UI using the provided emailAddress & password credentials, and start creating some products. Repeat this process for more Sellers. ## Storefront To create a multivendor Order, use the default Channel in the storefront and add variants to an Order from various Sellers. ### Shipping When it comes to setting the shipping method, the `eligibleShippingMethods` query should just return the shipping methods for the shops from which the OrderLines come. So assuming the Order contains items from 3 different Sellers, there should be at least 3 eligible ShippingMethods (plus any global ones from the default Channel). You should now select the IDs of all the Seller-specific ShippingMethods: ```graphql mutation { setOrderShippingMethod(shippingMethodId: ["3", "4"]) { ... on Order { id } } } ``` ### Payment This plugin automatically creates a "connected payment method" in the default Channel, which is a simple simulation of something like Stripe Connect. ```graphql mutation { addPaymentToOrder(input: { method: "connected-payment-method", metadata: {} }) { ... on Order { id } ... on ErrorResult { errorCode message } ... on PaymentFailedError { paymentErrorMessage } } } ``` After that, you should be able to see that the Order has been split into an "aggregate" order in the default Channel, and then one or more "seller" orders in each Channel from which the customer bought items.
# Example Wishlist plugin This is the complete plugin described in the [Writing your first plugin tutorial](https://docs.vendure.io/guides/getting-started/writing-a-vendure-plugin) in the Vendure docs.
# Reviews Plugin The reviews plugin add product reviews to Vendure. ![Screenshot of the Admin UI product details page with reviews](../../../product-reviews-screenshot.webp) This plugin demonstrates many capabilities of the Vendure plugin system: * Creation of new database entities (see [./entities](./entities)) * Extension of the GraphQL APIs with new types, extensions of existing types, new queries and new mutations (see [./api/api-extensions.ts](api/api-extensions.ts)) * Implementation of custom resolvers for those GraphQL extensions (e.g. [./api/product-entity.resolver.ts](api/product-entity.resolver.ts)) * Modifying the VendureConfig to add CustomFields (see [./reviews-plugin.ts](./reviews-plugin.ts)) * Extending the Admin UI with custom UI components for those CustomFields as well as list and details views for managing reviews. * Adding a custom widget to the Admin UI dashboard * End-to-end testing of the GraphQL extensions & business logic with Vitest & the `@vendure/testing` package. ## Usage Start the Vendure server and then in the Shop API (http://localhost:3000/shop-api) try the following mutation: ```SDL mutation { submitProductReview(input: { productId: 2 summary: "Good tablet" body: "The screen is clear, bright and sharp!" rating: 5 authorName: "Joe Smith" authorLocation: "London" }) { id state } } ``` You should then be able to log into the Admin UI (http://localhost:3000/admin) and see the new "Product Reviews" menu item on the left. Clicking this takes you to a brand new extension module listing all product reviews. You can approve the review that was just submitted. When viewing the Tablet product (http://localhost:3000/admin/catalog/inventory/2) you'll now see the review rating and count which make use of the custom UI controls defined in the ui extension.
# Vendure Elasticsearch Plugin The `ElasticsearchPlugin` uses Elasticsearch to power the Vendure product search. **Requires Elasticsearch v7.0 or higher.** `npm install @vendure/elasticsearch-plugin` For documentation, see [docs.vendure.io/reference/core-plugins/elasticsearch-plugin/](https://docs.vendure.io/reference/core-plugins/elasticsearch-plugin/)
# Vendure EmailPlugin The `EmailPlugin` generates and sends emails based on Vendure server events. `npm install @vendure/email-plugin` For documentation, see [docs.vendure.io/reference/core-plugins/email-plugin/](https://docs.vendure.io/reference/core-plugins/email-plugin/)
# Vendure Harden Plugin Hardens your Vendure GraphQL APIs against attacks. `npm install @vendure/harden-plugin` For documentation, see [docs.vendure.io/reference/core-plugins/harden-plugin/](https://docs.vendure.io/reference/core-plugins/harden-plugin/)
# Vendure Job Queue Plugin This plugin includes alternate JobQueueStrategy implementations built on different technologies. Implemented: * The `PubSubPlugin` uses Google Cloud Pub/Sub to power the Vendure job queue. * The `BullMQJobQueuePlugin` uses Redis via BullMQ.
# Payments plugin For documentation, see [docs.vendure.io/reference/core-plugins/payments-plugin/](https://docs.vendure.io/reference/core-plugins/payments-plugin/) ## Development ### Mollie local development For testing out changes to the Mollie plugin locally, with a real Mollie account, follow the steps below. These steps will create an order, set Mollie as payment method, and create a payment intent link to the Mollie platform. 1. Get a test api key from your Mollie dashboard: https://help.mollie.com/hc/en-us/articles/115000328205-Where-can-I-find-the-API-key- 2. Create the file `packages/payments-plugin/.env` with content `MOLLIE_APIKEY=your-test-apikey` 3. `cd packages/payments-plugin` 5. `npm run dev-server:mollie` 6. Watch the logs for `Mollie payment link` and click the link to finalize the test payment. You can change the order flow, payment methods and more in the file `e2e/mollie-dev-server`, and restart the devserver. ### Stripe local development For testing out changes to the Stripe plugin locally, with a real Stripe account, follow the steps below. These steps will create an order, set Stripe as payment method, and create a payment secret. 1. Get a test api key from your Stripe dashboard: https://dashboard.stripe.com/test/apikeys 2. Use Ngrok or Localtunnel to make your localhost publicly available and create a webhook as described here: https://www.vendure.io/docs/typescript-api/payments-plugin/stripe-plugin/ 3. Create the file `packages/payments-plugin/.env` with these contents: ```sh STRIPE_APIKEY=sk_test_xxxx STRIPE_WEBHOOK_SECRET=webhook-secret STRIPE_PUBLISHABLE_KEY=pk_test_xxxx ``` 1. `cd packages/payments-plugin` 2. `yarn dev-server:stripe` 3. Watch the logs for the link or go to `http://localhost:3050/checkout` to test the checkout. After checkout completion you can see your payment in https://dashboard.stripe.com/test/payments/
# Braintree payment plugin This plugin enables payments to be processed by [Braintree](https://www.braintreepayments.com/). For documentation, see https://docs.vendure.io/reference/core-plugins/payments-plugin/braintree-plugin/
# Vendure Paypal integration
# Stripe payment plugin Plugin to enable payments through [Stripe](https://stripe.com/docs). For documentation, see [https://www.vendure.io/docs/typescript-api/payments-plugin/stripe-plugin](https://docs.vendure.io/reference/core-plugins/payments-plugin/stripe-plugin/)https://docs.vendure.io/reference/core-plugins/payments-plugin/stripe-plugin/
# Vendure Sentry Plugin Integrates your Vendure server with the [Sentry](https://sentry.io/) application monitoring service. `npm install @vendure/sentry-plugin` For documentation, see [docs.vendure.io/reference/core-plugins/sentry-plugin/](https://docs.vendure.io/reference/core-plugins/sentry-plugin/)
# Vendure Stellate Plugin Integrates your Vendure server with the [Stellate](TaxRateEvent) GraphQL API cache. `npm install @vendure/stellate-plugin` For documentation, see [docs.vendure.io/reference/core-plugins/stellate-plugin/](https://docs.vendure.io/reference/core-plugins/stellate-plugin/)
# @vendure/testing This package contains utilities for writing end-to-end tests for Vendure. For documentation, see [www.vendure.io/docs/developer-guide/testing/](https://www.vendure.io/docs/developer-guide/testing/)
# @vendure/ui-devkit This package contains utilities for creating extensions to the Vendure Admin UI.
# Generated Admin UI This directory and its entire contents was generated the `compileUiExtensions()` function of the `@vendure/ui-devkit/compiler` package. It is not recommended to modify these files, since any changes will be overwritten upon re-compiling the ui extensions. ## Production app When compiling in production mode (`devMode: false`), the compiled application will be output to the `./dist` directory. This is a production-ready Angular application which can then be served from any web server, with attention to the [Angular server configuration guide](https://angular.io/guide/deployment#server-configuration).
--- title: 'Collections' --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; [`Collections`](/reference/typescript-api/entities/collection/) are used to categorize and organize your catalog. A collection contains multiple product variants, and a product variant can belong to multiple collections. Collections can be nested to create a hierarchy of categories, which is typically used to create a menu structure in the storefront. ![Collections](./collections.webp) Collections are not _only_ used as the basis of storefront navigation. They are a general-purpose organization tool which can be used for many purposes, such as: - Creating a collection of "new arrivals" which is used on the homepage. - Creating a collection of "best sellers" which is used to display a list of popular products. - Creating a collection of "sale items" which is used to apply a discount to all products in the collection, via a promotion. ## Collection filters The specific product variants that belong to a collection are determined by the collection's [`CollectionFilters`](/reference/typescript-api/configuration/collection-filter/). A collection filter is a piece of logic which is used to determine whether a product variant should be included in the collection. By default, Vendure includes a number of collection filters: - **Filter by facet values**: Include all product variants which have a specific set of facet values. - **Filter by product variant name**: Include all product variants whose name matches a specific string. - **Manually select product variants**: Allows manual selection of individual product variants. - **Manually select products**: Allows manual selection of entire products, and then includes all variants of those products. ![Collection filters](./collection-filters.webp) It is also possible to create your own custom collection filters, which can be used to implement more complex logic. See the section on [creating a collection filter](#creating-a-collection-filter) for more details. ### Filter inheritance When a collection is nested within another collection, the child collection can inherit the parent's collection filters. This means that the child collection will _combine_ its own filters with the parent's filters. ![Filter inheritance](./filter-inheritance.webp) In the example above, we have a parent collection "Menswear", with a child collection "Mens' Casual". The parent collection has a filter which includes all product variants with the "clothing" and "mens" facet values. The child collection is set to inherit the parent's filters, and has an additional filter which includes all product variants with the "casual" facet value. Thus, the child collection will include all product variants which have the "clothing", "mens" and "casual" facet values. :::note When filter inheritance is enabled, a child collection will contain a **subset** of the product variants of its parent collection. In order to create a child collection which contains product variants _not_ contained by the parent collection, you must disable filter inheritance in the child collection. ::: ### Creating a collection filter You can create your own custom collection filters with the [`CollectionFilter`](/reference/typescript-api/configuration/collection-filter/) class. This class is a [configurable operation](/guides/developer-guide/strategies-configurable-operations/#configurable-operations) where the specific filtering logic is implemented in the `apply()` method passed to its constructor. The `apply()` method receives an instance of the [TypeORM SelectQueryBuilder](https://typeorm.io/select-query-builder) which should have filtering logic added to it using the `.andWhere()` method. Here's an example of a collection filter which filters by SKU: ```ts title="src/config/sku-collection-filter.ts" import { CollectionFilter, LanguageCode } from '@vendure/core'; export const skuCollectionFilter = new CollectionFilter({ args: { // The `args` object defines the user-configurable arguments // which will get passed to the filter's `apply()` function. sku: { type: 'string', label: [{ languageCode: LanguageCode.en, value: 'SKU' }], description: [ { languageCode: LanguageCode.en, value: 'Matches any product variants with an SKU containing this value', }, ], }, }, code: 'variant-sku-filter', description: [{ languageCode: LanguageCode.en, value: 'Filter by matching SKU' }], // This is the function that defines the logic of the filter. apply: (qb, args) => { // Sometimes syntax differs between database types, so we use // the `type` property of the connection options to determine // which syntax to use. const LIKE = qb.connection.options.type === 'postgres' ? 'ILIKE' : 'LIKE'; return qb.andWhere(`productVariant.sku ${LIKE} :sku`, { sku: `%${args.sku}%` }); }, }); ``` In the `apply()` method, the product variant entity is aliased as `'productVariant'`. This custom filter is then added to the defaults in your config: ```ts title="src/vendure-config.ts" import { defaultCollectionFilters, VendureConfig } from '@vendure/core'; import { skuCollectionFilter } from './config/sku-collection-filter'; export const config: VendureConfig = { // ... catalogOptions: { collectionFilters: [ ...defaultCollectionFilters, // highlight-next-line skuCollectionFilter ], }, }; ``` :::info To see some more advanced collection filter examples, you can look at the source code of the [default collection filters](https://github.com/vendure-ecommerce/vendure/blob/master/packages/core/src/config/catalog/default-collection-filters.ts). :::
--- title: "Customers" --- A [`Customer`](/reference/typescript-api/entities/customer/) is a person who can buy from your shop. A customer can have one or more [`Addresses`](/reference/typescript-api/entities/address/), which are used for shipping and billing. If a customer has registered an account, they will have an associated [`User`](/reference/typescript-api/entities/user/). The user entity is used for authentication and authorization. **Guest checkouts** are also possible, in which case a customer will not have a user. :::info See the [Auth guide](/guides/core-concepts/auth/#customer-auth) for a detailed explanation of the relationship between customers and users. ::: ![Customer](./customer.webp) Customers can be organized into [`CustomerGroups`](/reference/typescript-api/entities/customer-group/). These groups can be used in logic relating to promotions, shipping rules, payment rules etc. For example, you could create a "VIP" customer group and then create a promotion which grants members of this group free shipping. Or a "B2B" group which is used in a custom tax calculator to apply a different tax rate to B2B customers.
--- title: "Email & Notifications" --- A typical ecommerce application needs to notify customers of certain events, such as when they place an order or when their order has been shipped. This is usually done via email, but can also be done via SMS or push notifications. ## Email Email is the most common way to notify customers of events, so a default Vendure installation includes our [EmailPlugin](/reference/core-plugins/email-plugin). The EmailPlugin by default uses [Nodemailer](https://nodemailer.com/about/) to send emails via a variety of different transports, including SMTP, SendGrid, Mailgun, and more. The plugin is configured with a list of [EmailEventHandlers](/reference/core-plugins/email-plugin/email-event-handler) which are responsible for sending emails in response to specific events. :::note This guide will cover some of the main concepts of the EmailPlugin, but for a more in-depth look at how to configure and use it, see the [EmailPlugin API docs](/reference/core-plugins/email-plugin). ::: Here's an illustration of the flow of an email being sent: ![Email plugin flow](./email-plugin-flow.webp) All emails are triggered by a particular [Event](/guides/developer-guide/events/) - in this case when the state of an Order changes. The EmailPlugin ships with a set of [default email handlers](https://github.com/vendure-ecommerce/vendure/blob/master/packages/email-plugin/src/default-email-handlers.ts), one of which is responsible for sending "order confirmation" emails. ### EmailEventHandlers Let's take a closer look at a simplified version of the `orderConfirmationHandler`: ```ts import { OrderStateTransitionEvent } from '@vendure/core'; import { EmailEventListener, transformOrderLineAssetUrls, hydrateShippingLines } from '@vendure/email-plugin'; // The 'order-confirmation' string is used by the EmailPlugin to identify // which template to use when rendering the email. export const orderConfirmationHandler = new EmailEventListener('order-confirmation') .on(OrderStateTransitionEvent) // Only send the email when the Order is transitioning to the // "PaymentSettled" state and the Order has a customer associated with it. .filter( event => event.toState === 'PaymentSettled' && !!event.order.customer, ) // We commonly need to load some additional data to be able to render the email // template. This is done via the `loadData()` method. In this method we are // mutating the Order object to ensure that product images are correctly // displayed in the email, as well as fetching shipping line data from the database. .loadData(async ({ event, injector }) => { transformOrderLineAssetUrls(event.ctx, event.order, injector); const shippingLines = await hydrateShippingLines(event.ctx, event.order, injector); return { shippingLines }; }) // Here we are setting the recipient of the email to be the // customer's email address. .setRecipient(event => event.order.customer!.emailAddress) // We can interpolate variables from the EmailPlugin's configured // `globalTemplateVars` object. .setFrom('{{ fromAddress }}') // We can also interpolate variables made available by the // `setTemplateVars()` method below .setSubject('Order confirmation for #{{ order.code }}') // The object returned here defines the variables which are // available to the email template. .setTemplateVars(event => ({ order: event.order, shippingLines: event.data.shippingLines })) ``` To recap: - The handler listens for a specific event - It optionally filters those events to determine whether an email should be sent - It specifies the details of the email to be sent, including the recipient, subject, template variables, etc. The full range of methods available when setting up an EmailEventHandler can be found in the [EmailEventHandler API docs](/reference/core-plugins/email-plugin/email-event-handler). ### Email variables In the example above, we used the `setTemplateVars()` method to define the variables which are available to the email template. Additionally, there are global variables which are made available to _all_ email templates & EmailEventHandlers. These are defined in the `globalTemplateVars` property of the EmailPlugin config: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; import { EmailPlugin } from '@vendure/email-plugin'; export const config: VendureConfig = { // ... plugins: [ EmailPlugin.init({ // ... // highlight-start globalTemplateVars: { fromAddress: '"MyShop" <noreply@myshop.com>', verifyEmailAddressUrl: 'https://www.myshop.com/verify', passwordResetUrl: 'https://www.myshop.com/password-reset', changeEmailAddressUrl: 'https://www.myshop.com/verify-email-address-change' }, // highlight-end }), ], }; ``` ### Email integrations The EmailPlugin is designed to be flexible enough to work with many different email services. The default configuration uses Nodemailer to send emails via SMTP, but you can easily configure it to use a different transport. For instance: - [AWS SES](https://www.vendure.io/marketplace/aws-ses) - [SendGrid](https://www.vendure.io/marketplace/sendgrid) ## Other notification methods The pattern of listening for events and triggering some action in response is not limited to emails. You can use the same pattern to trigger other actions, such as sending SMS messages or push notifications. For instance, let's say you wanted to create a plugin which sends an SMS message to the customer when their order is shipped. :::note This is just a simplified example to illustrate the pattern. ::: ```ts title="src/plugins/sms-plugin/sms-plugin.ts" import { OnModuleInit } from '@nestjs/common'; import { PluginCommonModule, VendurePlugin, EventBus } from '@vendure/core'; import { OrderStateTransitionEvent } from '@vendure/core'; // A custom service which sends SMS messages // using a third-party SMS provider such as Twilio. import { SmsService } from './sms.service'; @VendurePlugin({ imports: [PluginCommonModule], providers: [SmsService], }) export class SmsPlugin implements OnModuleInit { constructor( private eventBus: EventBus, private smsService: SmsService, ) {} onModuleInit() { this.eventBus .ofType(OrderStateTransitionEvent) .filter(event => event.toState === 'Shipped') .subscribe(event => { this.smsService.sendOrderShippedMessage(event.order); }); } } ```
--- title: "Images & Assets" --- [`Assets`](/reference/typescript-api/entities/asset/) are used to store files such as images, videos, PDFs, etc. Assets can be assigned to **products**, **variants** and **collections** by default. By using [custom fields](/guides/developer-guide/custom-fields/) it is possible to assign assets to other entities. For example, for implementing customer profile images. The handling of assets in Vendure is implemented in a modular way, allowing you full control over the way assets are stored, named, imported and previewed. ![Asset creation and retrieval](./asset-flow.webp) 1. An asset is created by uploading an image. Internally the [`createAssets` mutation](/reference/graphql-api/admin/mutations/#createassets) will be executed. 2. The [`AssetNamingStrategy`](/reference/typescript-api/assets/asset-naming-strategy/) is used to generate file names for the source image and the preview. This is useful for normalizing file names as well as handling name conflicts. 3. The [`AssetPreviewStrategy`](/reference/typescript-api/assets/asset-preview-strategy) generates a preview image of the asset. For images, this typically involves creating a version with constraints on the maximum dimensions. It could also be used to e.g. generate a preview image for uploaded PDF files, videos or other non-image assets (such functionality would require a custom `AssetPreviewStrategy` to be defined). 4. The source file as well as the preview image are then passed to the [`AssetStorageStrategy`](/reference/typescript-api/assets/asset-storage-strategy) which stores the files to some form of storage. This could be the local disk or an object store such as AWS S3 or Minio. 5. When an asset is later read, e.g. when a customer views a product detail page which includes an image of the product, the `AssetStorageStrategy` can be used to read the file from the storage location. ## AssetServerPlugin Vendure comes with the `@vendure/asset-server-plugin` package pre-installed. This provides the [`AssetServerPlugin`](/reference/core-plugins/asset-server-plugin/) which provides many advanced features to make working with assets easier. The plugin provides a ready-made set of strategies for handling assets, but also allows you to replace these defaults with your own implementations. For example, here are instructions on how to replace the default storage strategy with one that stores your assets on AWS S3 or Minio: [configure S3 asset storage](/reference/core-plugins/asset-server-plugin/s3asset-storage-strategy#configures3assetstorage) It also features a powerful image transformation API, which allows you to specify the dimensions, crop, and image format using query parameters. :::info See the [AssetServerPlugin docs](/reference/core-plugins/asset-server-plugin/) for a detailed description of all the features. ::: ## Asset Tags Assets can be tagged. A [`Tag`](/reference/typescript-api/entities/tag/) is a simple text label that can be applied to an asset. An asset can have multiple tags or none. Tags are useful for organizing assets, since assets are otherwise organized as a flat list with no concept of a directory structure. ![Asset tags](./asset-tags.webp)
--- title: "Money & Currency" --- In Vendure, monetary values are stored as **integers** using the **minor unit** of the selected currency. For example, if the currency is set to USD, then the integer value `100` would represent $1.00. This is a common practice in financial applications, as it avoids the rounding errors that can occur when using floating-point numbers. For example, here's the response from a query for a product's variant prices: ```json { "data": { "product": { "id": "42", "variants": [ { "id": "74", "name": "Bonsai Tree", "currencyCode": "USD", // highlight-start "price": 1999, "priceWithTax": 2399, // highlight-end } ] } } } ``` In this example, the tax-inclusive price of the variant is `$23.99`. :::info To illustrate the problem with storing money as decimals, imagine that we want to add the price of two items: - Product A: `$1.21` - Product B: `$1.22` We should expect the sum of these two amounts to equal `$2.43`. However, if we perform this addition in JavaScript (and the same holds true for most common programming languages), we will instead get `$2.4299999999999997`! For a more in-depth explanation of this issue, see [this StackOverflow answer](https://stackoverflow.com/a/3730040/772859) ::: ## Displaying monetary values When you are building your storefront, or any other client that needs to display monetary values in a human-readable form, you need to divide by 100 to convert to the major currency unit and then format with the correct decimal & grouping dividers. In JavaScript environments such as browsers & Node.js, we can take advantage of the excellent [`Intl.NumberFormat` API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat). Here's a function you can use in your projects: ```ts title="src/utils/format-currency.ts" export function formatCurrency(value: number, currencyCode: string, locale?: string) { const majorUnits = value / 100; try { // Note: if no `locale` is provided, the browser's default // locale will be used. return new Intl.NumberFormat(locale, { style: 'currency', currency: currencyCode, }).format(majorUnits); } catch (e: any) { // A fallback in case the NumberFormat fails for any reason return majorUnits.toFixed(2); } } ``` If you are building an Admin UI extension, you can use the built-in [`LocaleCurrencyPipe`](/reference/admin-ui-api/pipes/locale-currency-pipe/): ```html title="src/plugins/my-plugin/ui/components/my-component/my.component.html" <div> Variant price: {{ variant.price | localeCurrency : variant.currencyCode }} </div> ``` ## Support for multiple currencies Vendure supports multiple currencies out-of-the-box. The available currencies must first be set at the Channel level (see the [Channels, Currencies & Prices section](/guides/core-concepts/channels/#channels-currencies--prices)), and then a price may be set on a `ProductVariant` in each of the available currencies. When using multiple currencies, the [ProductVariantPriceSelectionStrategy](/reference/typescript-api/configuration/product-variant-price-selection-strategy/) is used to determine which of the available prices to return when fetching the details of a `ProductVariant`. The default strategy is to return the price in the currency of the current session request context, which is determined firstly by any `?currencyCode=XXX` query parameter on the request, and secondly by the `defaultCurrencyCode` of the Channel. ## The GraphQL `Money` scalar In the GraphQL APIs, we use a custom [`Money` scalar type](/reference/graphql-api/admin/object-types/#money) to represent all monetary values. We do this for two reasons: 1. The built-in `Int` type is that the GraphQL spec imposes an upper limit of `2147483647`, which in some cases (especially currencies with very large amounts) is not enough. 2. Very advanced use-cases might demand more precision than is possible with an integer type. Using our own custom scalar gives us the possibility of supporting more precision. Here's how the `Money` scalar is used in the `ShippingLine` type: ```graphql type ShippingLine { id: ID! shippingMethod: ShippingMethod! // highlight-start price: Money! priceWithTax: Money! discountedPrice: Money! discountedPriceWithTax: Money! // highlight-end discounts: [Discount!]! } ``` If you are defining custom GraphQL types, or adding fields to existing types (see the [Extending the GraphQL API doc](/guides/developer-guide/extend-graphql-api/)), then you should also use the `Money` scalar for any monetary values. ## The `@Money()` decorator When [defining new database entities](/guides/developer-guide/database-entity//), if you need to store a monetary value, then rather than using the TypeORM `@Column()` decorator, you should use Vendure's [`@Money()` decorator](/reference/typescript-api/money/money-decorator). Using this decorator allows Vendure to correctly store the value in the database according to the configured `MoneyStrategy` (see below). ```ts title="src/plugins/quote/entities/quote.entity.ts" import { DeepPartial } from '@vendure/common/lib/shared-types'; import { VendureEntity, Order, EntityId, Money, CurrencyCode, ID } from '@vendure/core'; import { Column, Entity, ManyToOne } from 'typeorm'; @Entity() class Quote extends VendureEntity { constructor(input?: DeepPartial<Quote>) { super(input); } @ManyToOne(type => Order) order: Order; @EntityId() orderId: ID; @Column() text: string; // highlight-start @Money() value: number; // highlight-end // Whenever you store a monetary value, it's a good idea to also // explicitly store the currency code too. This makes it possible // to support multiple currencies and correctly format the amount // when displaying the value. @Column('varchar') currencyCode: CurrencyCode; @Column() approved: boolean; } ``` ## Advanced configuration: MoneyStrategy For advanced use-cases, it is possible to configure aspects of how Vendure handles monetary values internally by defining a custom [`MoneyStrategy`](/reference/typescript-api/money/money-strategy/). The `MoneyStrategy` allows you to define: - How the value is stored and retrieved from the database - How rounding is applied internally - The precision represented by the monetary value (since v2.2.0) For example, in addition to the [`DefaultMoneyStrategy`](/reference/typescript-api/money/default-money-strategy), Vendure also provides the [`BigIntMoneyStrategy`](/reference/typescript-api/money/big-int-money-strategy) which stores monetary values using the `bigint` data type, allowing much larger amounts to be stored. Here's how you would configure your server to use this strategy: ```ts title="src/vendure-config.ts" import { VendureConfig, BigIntMoneyStrategy } from '@vendure/core'; export const config: VendureConfig = { // ... entityOptions: { moneyStrategy: new BigIntMoneyStrategy(), } } ``` ### Example: supporting three decimal places Let's say you have a B2B store which sells products in bulk, and you want to support prices with three decimal places. For example, you want to be able to sell a product for `$1.234` per unit. To do this, you would need to: 1. Configure the `MoneyStrategy` to use three decimal places ```ts import { DefaultMoneyStrategy, VendureConfig } from '@vendure/core'; export class ThreeDecimalPlacesMoneyStrategy extends DefaultMoneyStrategy { // highlight-next-line readonly precision = 3; } export const config: VendureConfig = { // ... entityOptions: { moneyStrategy: new ThreeDecimalPlacesMoneyStrategy(), } }; ``` 2. Set up your storefront to correctly convert the integer value to a decimal value with three decimal places. Using the `formatCurrency` example above, we can modify it to divide by 1000 instead of 100: ```ts title="src/utils/format-currency.ts" export function formatCurrency(value: number, currencyCode: string, locale?: string) { // highlight-next-line const majorUnits = value / 1000; try { return new Intl.NumberFormat(locale, { style: 'currency', currency: currencyCode, // highlight-start minimumFractionDigits: 3, maximumFractionDigits: 3, // highlight-end }).format(majorUnits); } catch (e: any) { // highlight-next-line return majorUnits.toFixed(3); } } ```
--- title: "Products" --- Your catalog is composed of [`Products`](/reference/typescript-api/entities/product/) and [`ProductVariants`](/reference/typescript-api/entities/product-variant/). A `Product` always has _at least one_ `ProductVariant`. You can think of the product as a "container" which includes a name, description, and images that apply to all of its variants. Here's a visual example, in which we have a "Hoodie" product which is available in 3 sizes. Therefore, we have 3 variants of that product: ![Products and ProductVariants](./products-variants.webp) Multiple variants are made possible by adding one or more [`ProductOptionGroups`](/reference/typescript-api/entities/product-option-group) to the product. These option groups then define the available [`ProductOptions`](/reference/typescript-api/entities/product-option) If we were to add a new option group to the example above for "Color", with 2 options, "Black" and "White", then in total we would be able to define up to 6 variants: - Hoodie Small Black - Hoodie Small White - Hoodie Medium Black - Hoodie Medium White - Hoodie Large Black - Hoodie Large White :::info When a customer adds a product to their cart, they are adding a specific `ProductVariant` to their cart, not the `Product` itself. It is the `ProductVariant` that contains the SKU ("stock keeping unit", or product code) and price information. ::: ## Product price and stock The `ProductVariant` entity contains the price and stock information for a product. Since a given product variant can have more than one price, and more than one stock level (in the case of multiple warehouses), the `ProductVariant` entity contains relations to one or more [`ProductVariantPrice`](/reference/typescript-api/entities/product-variant-price) entities and one or more [`StockLevel`](/reference/typescript-api/entities/stock-level) entities. ![Price and stock](./product-relations.webp) ## Facets [`Facets`](/reference/typescript-api/entities/facet/) are used to add structured labels to products and variants. A facet has one or more [`FacetValues`](/reference/typescript-api/entities/facet-value/). Facet values can be assigned to products or product variants. For example, a "Brand" facet could be used to label products with the brand name, with each facet value representing a different brand. You can also use facets to add other metadata to products and variants such as "New", "Sale", "Featured", etc. ![Facets and FacetValues](./facets.webp) These are the typical uses of facets in Vendure: - As the **basis of [Collections](/guides/core-concepts/collections)**, in order to categorize your catalog. - To **filter products** in the storefront, also known as "faceted search". For example, a customer is on the "hoodies" collection page and wants to filter to only show Nike hoodies. - For **internal logic**, such as a promotion that applies to all variants with the "Summer Sale" facet value, or a shipping calculation that applies a surcharge to all products with the "Fragile" facet value. Such facets can be set to be private so that they are not exposed to the storefront.
--- title: "Taxes" showtoc: true --- E-commerce applications need to correctly handle taxes such as sales tax or value added tax (VAT). In Vendure, tax handling consists of: * **Tax categories** Each ProductVariant is assigned to a specific TaxCategory. In some tax systems, the tax rate differs depending on the type of good. For example, VAT in the UK has 3 rates, "standard" (most goods), "reduced" (e.g. child car seats) and "zero" (e.g. books). * **Tax rates** This is the tax rate applied to a specific tax category for a specific [Zone](/reference/typescript-api/entities/zone/). E.g., the tax rate for "standard" goods in the UK Zone is 20%. * **Channel tax settings** Each Channel can specify whether the prices of product variants are inclusive of tax or not, and also specify the default Zone to use for tax calculations. * **TaxZoneStrategy** Determines the active tax Zone used when calculating what TaxRate to apply. By default, it uses the default tax Zone from the Channel settings. * **TaxLineCalculationStrategy** This determines the taxes applied when adding an item to an Order. If you want to integrate a 3rd-party tax API or other async lookup, this is where it would be done. ## API conventions In the GraphQL API, any type which has a taxable price will split that price into two fields: `price` and `priceWithTax`. This pattern also holds for other price fields, e.g. ```graphql query { activeOrder { ...on Order { lines { linePrice linePriceWithTax } subTotal subTotalWithTax shipping shippingWithTax total totalWithTax } } } ``` In your storefront, you can therefore choose whether to display the prices with or without tax, according to the laws and conventions of the area in which your business operates. ## Calculating tax on order lines When a customer adds an item to the Order, the following logic takes place: 1. The price of the item, and whether that price is inclusive of tax, is determined according to the configured [OrderItemPriceCalculationStrategy](/reference/typescript-api/orders/order-item-price-calculation-strategy/). 2. The active tax Zone is determined based on the configured [TaxZoneStrategy](/reference/typescript-api/tax/tax-zone-strategy/). 3. The applicable TaxRate is fetched based on the ProductVariant's TaxCategory and the active tax Zone determined in step 1. 4. The `TaxLineCalculationStrategy.calculate()` of the configured [TaxLineCalculationStrategy](/reference/typescript-api/tax/tax-line-calculation-strategy/) is called, which will return one or more [TaxLines](/reference/graphql-api/admin/object-types/#taxline). 5. The final `priceWithTax` of the order line is calculated based on all the above. ## Calculating tax on shipping The taxes on shipping is calculated by the [ShippingCalculator](/reference/typescript-api/shipping/shipping-calculator/) of the Order's selected [ShippingMethod](/reference/typescript-api/entities/shipping-method/). ## Configuration This example shows the default configuration for taxes (you don't need to specify this in your own config, as these are the defaults): ```ts title="src/vendure-config.ts" import { DefaultTaxLineCalculationStrategy, DefaultTaxZoneStrategy, DefaultOrderItemPriceCalculationStrategy, VendureConfig } from '@vendure/core'; export const config: VendureConfig = { taxOptions: { taxZoneStrategy: new DefaultTaxZoneStrategy(), taxLineCalculationStrategy: new DefaultTaxLineCalculationStrategy(), }, orderOptions: { orderItemPriceCalculationStrategy: new DefaultOrderItemPriceCalculationStrategy() } } ```
--- title: "Error Handling" showtoc: true --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import Stackblitz from '@site/src/components/Stackblitz'; Errors in Vendure can be divided into two categories: * Unexpected errors * Expected errors These two types have different meanings and are handled differently from one another. ## Unexpected Errors This type of error occurs when something goes unexpectedly wrong during the processing of a request. Examples include internal server errors, database connectivity issues, lacking permissions for a resource, etc. In short, these are errors that are *not supposed to happen*. Internally, these situations are handled by throwing an Error: ```ts const customer = await this.findOneByUserId(ctx, user.id); // in this case, the customer *should always* be found, and if // not then something unknown has gone wrong... if (!customer) { throw new InternalServerError('error.cannot-locate-customer-for-user'); } ``` In the GraphQL APIs, these errors are returned in the standard `errors` array: ```json { "errors": [ { "message": "You are not currently authorized to perform this action", "locations": [ { "line": 2, "column": 2 } ], "path": [ "me" ], "extensions": { "code": "FORBIDDEN" } } ], "data": { "me": null } } ``` So your client applications need a generic way of detecting and handling this kind of error. For example, many http client libraries support "response interceptors" which can be used to intercept all API responses and check the `errors` array. :::note GraphQL will return a `200` status even if there are errors in the `errors` array. This is because in GraphQL it is still possible to return good data _alongside_ any errors. ::: Here's how it might look in a simple Fetch-based client: ```ts title="src/client.ts" export function query(document: string, variables: Record<string, any> = {}) { return fetch(endpoint, { method: 'POST', headers, credentials: 'include', body: JSON.stringify({ query: document, variables, }), }) .then(async (res) => { if (!res.ok) { const body = await res.json(); throw new Error(body); } const newAuthToken = res.headers.get('vendure-auth-token'); if (newAuthToken) { localStorage.setItem(AUTH_TOKEN_KEY, newAuthToken); } return res.json(); }) .catch((err) => { // This catches non-200 responses, such as malformed queries or // network errors. Handle this with your own error handling logic. // For this demo we just show an alert. window.alert(err.message); }) .then((result) => { // highlight-start // We check for any GraphQL errors which would be in the // `errors` array of the response body: if (Array.isArray(result.errors)) { // It looks like we have an unexpected error. // At this point you could take actions like: // - logging the error to a remote service // - displaying an error popup to the user // - inspecting the `error.extensions.code` to determine the // type of error and take appropriate action. E.g. a // in response to a FORBIDDEN_ERROR you can redirect the // user to a login page. // In this example we just display an alert: const errorMessage = result.errors.map((e) => e.message).join('\n'); window.alert(`Unexpected error caught:\n\n${errorMessage}`); } // highlight-end return result; }); } ``` ## Expected errors (ErrorResults) This type of error represents a well-defined result of (typically) a GraphQL mutation which is not considered "successful". For example, when using the `applyCouponCode` mutation, the code may be invalid, or it may have expired. These are examples of "expected" errors and are named in Vendure "ErrorResults". These ErrorResults are encoded into the GraphQL schema itself. ErrorResults all implement the `ErrorResult` interface: ```graphql interface ErrorResult { errorCode: ErrorCode! message: String! } ``` Some ErrorResults add other relevant fields to the type: ```graphql "Returned if there is an error in transitioning the Order state" type OrderStateTransitionError implements ErrorResult { errorCode: ErrorCode! message: String! transitionError: String! fromState: String! toState: String! } ``` Operations that may return ErrorResults use a GraphQL `union` as their return type: ```graphql type Mutation { "Applies the given coupon code to the active Order" applyCouponCode(couponCode: String!): ApplyCouponCodeResult! } union ApplyCouponCodeResult = Order | CouponCodeExpiredError | CouponCodeInvalidError | CouponCodeLimitError ``` ### Querying an ErrorResult union When performing an operation of a query or mutation which returns a union, you will need to use the [GraphQL conditional fragment](https://graphql.org/learn/schema/#union-types) to select the desired fields: ```graphql mutation ApplyCoupon($code: String!) { applyCouponCode(couponCode: $code) { __typename ...on Order { id couponCodes totalWithTax } # querying the ErrorResult fields # "catches" all possible errors ...on ErrorResult { errorCode message } # you can also specify particular fields # if your client app needs that specific data # as part of handling the error. ...on CouponCodeLimitError { limit } } } ``` :::note The `__typename` field is added by GraphQL to _all_ object types, so we can include it no matter whether the result will end up being an `Order` object or an `ErrorResult` object. We can then use the `__typename` value to determine what kind of object we have received. Some clients such as Apollo Client will automatically add the `__typename` field to all queries and mutations. If you are using a client which does not do this, you will need to add it manually. ::: Here's how a response would look in both the success and error result cases: <Tabs> <TabItem value="Success case" label="Success case" > ```json { "data": { "applyCouponCode": { // highlight-next-line "__typename": "Order", "id": "123", "couponCodes": ["VALID-CODE"], "totalWithTax": 12599, } } } ``` </TabItem> <TabItem value="Error case" label="Error case" > ```json { "data": { "applyCouponCode": { // highlight-next-line "__typename": "CouponCodeLimitError", "errorCode": "COUPON_CODE_LIMIT_ERROR", "message": "Coupon code cannot be used more than once per customer", // highlight-next-line "limit": 1 } } } ``` </TabItem> </Tabs> ### Handling ErrorResults in plugin code If you are writing a plugin which deals with internal Vendure service methods that may return ErrorResults, then you can use the `isGraphQlErrorResult()` function to check whether the result is an ErrorResult: ```ts import { Injectable} from '@nestjs/common'; import { isGraphQlErrorResult, Order, OrderService, OrderState, RequestContext } from '@vendure/core'; @Injectable() export class MyService { constructor(private orderService: OrderService) {} async myMethod(ctx: RequestContext, order: Order, newState: OrderState) { const transitionResult = await this.orderService.transitionToState(ctx, order.id, newState); if (isGraphQlErrorResult(transitionResult)) { // The transition failed with an ErrorResult throw transitionResult; } else { // TypeScript will correctly infer the type of `transitionResult` to be `Order` return transitionResult; } } } ``` ### Handling ErrorResults in client code Because we know all possible ErrorResult that may occur for a given mutation, we can handle them in an exhaustive manner. In other words, we can ensure our storefront has some sensible response to all possible errors. Typically this will be done with a `switch` statement: ```ts const result = await query(APPLY_COUPON_CODE, { code: 'INVALID-CODE' }); switch (result.applyCouponCode.__typename) { case 'Order': // handle success break; case 'CouponCodeExpiredError': // handle expired code break; case 'CouponCodeInvalidError': // handle invalid code break; case 'CouponCodeLimitError': // handle limit error break; default: // any other ErrorResult can be handled with a generic error message } ``` If we combine this approach with [GraphQL code generation](/guides/storefront/codegen/), then TypeScript will even be able to help us ensure that we have handled all possible ErrorResults: ```ts // Here we are assuming that the APPLY_COUPON_CODE query has been generated // by the codegen tool, and therefore has the // type `TypedDocumentNode<ApplyCouponCode, ApplyCouponCodeVariables>`. const result = await query(APPLY_COUPON_CODE, { code: 'INVALID-CODE' }); switch (result.applyCouponCode.__typename) { case 'Order': // handle success break; case 'CouponCodeExpiredError': // handle expired code break; case 'CouponCodeInvalidError': // handle invalid code break; case 'CouponCodeLimitError': // handle limit error break; default: // highlight-start // this line will cause a TypeScript error if there are any // ErrorResults which we have not handled in the switch cases // above. const _exhaustiveCheck: never = result.applyCouponCode; // highlight-end } ``` ## Live example Here is a live example which the handling of unexpected errors as well as ErrorResults: <Stackblitz id='vendure-docs-error-handling' />
--- title: 'Events' --- Vendure emits events which can be subscribed to by plugins. These events are published by the [EventBus](/reference/typescript-api/events/event-bus/) and likewise the `EventBus` is used to subscribe to events. An event exists for virtually all significant actions which occur in the system, such as: - When entities (e.g. `Product`, `Order`, `Customer`) are created, updated or deleted - When a user registers an account - When a user logs in or out - When the state of an `Order`, `Payment`, `Fulfillment` or `Refund` changes A full list of the available events follows. ## Event types <div class="row"> <div class="col col--6"> - [`AccountRegistrationEvent`](/reference/typescript-api/events/event-types#accountregistrationevent) - [`AccountVerifiedEvent`](/reference/typescript-api/events/event-types#accountverifiedevent) - [`AdministratorEvent`](/reference/typescript-api/events/event-types#administratorevent) - [`AssetChannelEvent`](/reference/typescript-api/events/event-types#assetchannelevent) - [`AssetEvent`](/reference/typescript-api/events/event-types#assetevent) - [`AttemptedLoginEvent`](/reference/typescript-api/events/event-types#attemptedloginevent) - [`ChangeChannelEvent`](/reference/typescript-api/events/event-types#changechannelevent) - [`ChannelEvent`](/reference/typescript-api/events/event-types#channelevent) - [`CollectionEvent`](/reference/typescript-api/events/event-types#collectionevent) - [`CollectionModificationEvent`](/reference/typescript-api/events/event-types#collectionmodificationevent) - [`CountryEvent`](/reference/typescript-api/events/event-types#countryevent) - [`CouponCodeEvent`](/reference/typescript-api/events/event-types#couponcodeevent) - [`CustomerAddressEvent`](/reference/typescript-api/events/event-types#customeraddressevent) - [`CustomerEvent`](/reference/typescript-api/events/event-types#customerevent) - [`CustomerGroupChangeEvent`](/reference/typescript-api/events/event-types#customergroupchangeevent) - [`CustomerGroupEvent`](/reference/typescript-api/events/event-types#customergroupevent) - [`FacetEvent`](/reference/typescript-api/events/event-types#facetevent) - [`FacetValueEvent`](/reference/typescript-api/events/event-types#facetvalueevent) - [`FulfillmentEvent`](/reference/typescript-api/events/event-types#fulfillmentevent) - [`FulfillmentStateTransitionEvent`](/reference/typescript-api/events/event-types#fulfillmentstatetransitionevent) - [`GlobalSettingsEvent`](/reference/typescript-api/events/event-types#globalsettingsevent) - [`HistoryEntryEvent`](/reference/typescript-api/events/event-types#historyentryevent) - [`IdentifierChangeEvent`](/reference/typescript-api/events/event-types#identifierchangeevent) - [`IdentifierChangeRequestEvent`](/reference/typescript-api/events/event-types#identifierchangerequestevent) - [`InitializerEvent`](/reference/typescript-api/events/event-types#initializerevent) - [`LoginEvent`](/reference/typescript-api/events/event-types#loginevent) - [`LogoutEvent`](/reference/typescript-api/events/event-types#logoutevent) - [`OrderEvent`](/reference/typescript-api/events/event-types#orderevent) </div> <div class="col col--6"> - [`OrderLineEvent`](/reference/typescript-api/events/event-types#orderlineevent) - [`OrderPlacedEvent`](/reference/typescript-api/events/event-types#orderplacedevent) - [`OrderStateTransitionEvent`](/reference/typescript-api/events/event-types#orderstatetransitionevent) - [`PasswordResetEvent`](/reference/typescript-api/events/event-types#passwordresetevent) - [`PasswordResetVerifiedEvent`](/reference/typescript-api/events/event-types#passwordresetverifiedevent) - [`PaymentMethodEvent`](/reference/typescript-api/events/event-types#paymentmethodevent) - [`PaymentStateTransitionEvent`](/reference/typescript-api/events/event-types#paymentstatetransitionevent) - [`ProductChannelEvent`](/reference/typescript-api/events/event-types#productchannelevent) - [`ProductEvent`](/reference/typescript-api/events/event-types#productevent) - [`ProductOptionEvent`](/reference/typescript-api/events/event-types#productoptionevent) - [`ProductOptionGroupChangeEvent`](/reference/typescript-api/events/event-types#productoptiongroupchangeevent) - [`ProductOptionGroupEvent`](/reference/typescript-api/events/event-types#productoptiongroupevent) - [`ProductVariantChannelEvent`](/reference/typescript-api/events/event-types#productvariantchannelevent) - [`ProductVariantEvent`](/reference/typescript-api/events/event-types#productvariantevent) - [`PromotionEvent`](/reference/typescript-api/events/event-types#promotionevent) - [`ProvinceEvent`](/reference/typescript-api/events/event-types#provinceevent) - [`RefundStateTransitionEvent`](/reference/typescript-api/events/event-types#refundstatetransitionevent) - [`RoleChangeEvent`](/reference/typescript-api/events/event-types#rolechangeevent) - [`RoleEvent`](/reference/typescript-api/events/event-types#roleevent) - [`SearchEvent`](/reference/typescript-api/events/event-types#searchevent) - [`SellerEvent`](/reference/typescript-api/events/event-types#sellerevent) - [`ShippingMethodEvent`](/reference/typescript-api/events/event-types#shippingmethodevent) - [`StockMovementEvent`](/reference/typescript-api/events/event-types#stockmovementevent) - [`TaxCategoryEvent`](/reference/typescript-api/events/event-types#taxcategoryevent) - [`TaxRateEvent`](/reference/typescript-api/events/event-types#taxrateevent) - [`TaxRateModificationEvent`](/reference/typescript-api/events/event-types#taxratemodificationevent) - [`ZoneEvent`](/reference/typescript-api/events/event-types#zoneevent) - [`ZoneMembersEvent`](/reference/typescript-api/events/event-types#zonemembersevent) </div> </div> ## Subscribing to events To subscribe to an event, use the `EventBus`'s `.ofType()` method. It is typical to set up subscriptions in the `onModuleInit()` or `onApplicationBootstrap()` lifecycle hooks of a plugin or service (see [NestJS Lifecycle events](https://docs.nestjs.com/fundamentals/lifecycle-events)). Here's an example where we subscribe to the `ProductEvent` and use it to trigger a rebuild of a static storefront: ```ts title="src/plugins/storefront-build/storefront-build.plugin.ts" import { OnModuleInit } from '@nestjs/common'; import { EventBus, ProductEvent, PluginCommonModule, VendurePlugin } from '@vendure/core'; import { StorefrontBuildService } from './services/storefront-build.service'; @VendurePlugin({ imports: [PluginCommonModule], }) export class StorefrontBuildPlugin implements OnModuleInit { constructor( // highlight-next-line private eventBus: EventBus, private storefrontBuildService: StorefrontBuildService, ) {} onModuleInit() { // highlight-start this.eventBus.ofType(ProductEvent).subscribe(event => { this.storefrontBuildService.triggerBuild(); }); // highlight-end } } ``` :::info The `EventBus.ofType()` and related `EventBus.filter()` methods return an RxJS `Observable`. This means that you can use any of the [RxJS operators](https://rxjs-dev.firebaseapp.com/guide/operators) to transform the stream of events. For example, to debounce the stream of events, you could do this: ```ts // highlight-next-line import { debounceTime } from 'rxjs/operators'; // ... this.eventBus .ofType(ProductEvent) // highlight-next-line .pipe(debounceTime(1000)) .subscribe(event => { this.storefrontBuildService.triggerBuild(); }); ``` ::: ### Subscribing to multiple event types Using the `.ofType()` method allows us to subscribe to a single event type. If we want to subscribe to multiple event types, we can use the `.filter()` method instead: ```ts title="src/plugins/my-plugin/my-plugin.plugin.ts" import { Injectable, OnModuleInit } from '@nestjs/common'; import { EventBus, PluginCommonModule, VendurePlugin, ProductEvent, ProductVariantEvent, } from '@vendure/core'; @VendurePlugin({ imports: [PluginCommonModule], }) export class MyPluginPlugin implements OnModuleInit { constructor(private eventBus: EventBus) {} onModuleInit() { this.eventBus // highlight-start .filter(event => event instanceof ProductEvent || event instanceof ProductVariantEvent) // highlight-end .subscribe(event => { // the event will be a ProductEvent or ProductVariantEvent }); } } ``` ## Publishing events You can publish events using the `EventBus.publish()` method. This is useful if you want to trigger an event from within a plugin or service. For example, to publish a `ProductEvent`: ```ts title="src/plugins/my-plugin/services/my-plugin.service.ts" import { Injectable } from '@nestjs/common'; import { EventBus, ProductEvent, RequestContext, Product } from '@vendure/core'; @Injectable() export class MyPluginService { constructor(private eventBus: EventBus) {} async doSomethingWithProduct(ctx: RequestContext, product: Product) { // ... do something // highlight-next-line await this.eventBus.publish(new ProductEvent(ctx, product, 'updated')); } } ``` ## Creating custom events You can create your own custom events by extending the [`VendureEvent`](/reference/typescript-api/events/vendure-event) class. For example, to create a custom event which is triggered when a customer submits a review, you could do this: ```ts title="src/plugins/reviews/events/review-submitted.event.ts" import { ID, RequestContext, VendureEvent } from '@vendure/core'; import { ProductReviewInput } from '../types'; /** * @description * This event is fired whenever a ProductReview is submitted. */ export class ReviewSubmittedEvent extends VendureEvent { constructor( public ctx: RequestContext, public input: ProductReviewInput, ) { super(); } } ``` The event would then be published from your plugin's `ProductReviewService`: ```ts title="src/plugins/reviews/services/product-review.service.ts" import { Injectable } from '@nestjs/common'; import { EventBus, ProductReviewService, RequestContext } from '@vendure/core'; import { ReviewSubmittedEvent } from '../events/review-submitted.event'; import { ProductReviewInput } from '../types'; @Injectable() export class ProductReviewService { constructor( private eventBus: EventBus, private productReviewService: ProductReviewService, ) {} async submitReview(ctx: RequestContext, input: ProductReviewInput) { // highlight-next-line this.eventBus.publish(new ReviewSubmittedEvent(ctx, input)); // handle creation of the new review // ... } } ``` ### Entity events There is a special event class [`VendureEntityEvent`](/reference/typescript-api/events/vendure-entity-event) for events relating to the creation, update or deletion of entities. Let's say you have a custom entity (see [defining a database entity](/guides/developer-guide/database-entity//)) `BlogPost` and you want to trigger an event whenever a new `BlogPost` is created, updated or deleted: ```ts title="src/plugins/blog/events/blog-post-event.ts" import { ID, RequestContext, VendureEntityEvent } from '@vendure/core'; import { BlogPost } from '../entities/blog-post.entity'; import { CreateBlogPostInput, UpdateBlogPostInput } from '../types'; type BlogPostInputTypes = CreateBlogPostInput | UpdateBlogPostInput | ID | ID[]; /** * This event is fired whenever a BlogPost is added, updated * or deleted. */ export class BlogPostEvent extends VendureEntityEvent<BlogPost[], BlogPostInputTypes> { constructor( ctx: RequestContext, entity: BlogPost, type: 'created' | 'updated' | 'deleted', input?: BlogPostInputTypes, ) { super(entity, type, ctx, input); } } ``` Using this event, you can subscribe to all `BlogPost` events, and for instance filter for only the `created` events: ```ts title="src/plugins/blog/blog-plugin.ts" import { Injectable, OnModuleInit } from '@nestjs/common'; import { EventBus, PluginCommonModule, VendurePlugin } from '@vendure/core'; import { filter } from 'rxjs/operators'; import { BlogPostEvent } from './events/blog-post-event'; @VendurePlugin({ imports: [PluginCommonModule], // ... }) export class BlogPlugin implements OnModuleInit { constructor(private eventBus: EventBus) {} onModuleInit() { this.eventBus // highlight-start .ofType(BlogPostEvent) .pipe(filter(event => event.type === 'created')) .subscribe(event => { const blogPost = event.entity; // do something with the newly created BlogPost }); // highlight-end } } ``` ## Blocking event handlers :::note The following section is an advanced topic. The API described in this section was added in Vendure v2.2.0. ::: When using the `.ofType().subscribe()` pattern, the event handler is non-blocking. This means that the code that publishes the event (the "publishing code") will have no knowledge of any subscribers, and in fact any subscribers will be executed after the code that published the event has completed (technically, any ongoing database transactions are completed before the event gets emitted to the subscribers). This follows the typical [Observer pattern](https://en.wikipedia.org/wiki/Observer_pattern) and is a good fit for most use-cases. However, there may be certain situations in which you want the event handler to cause the publishing code to block until the event handler has completed. This is done by using a "blocking event handler", which does _not_ follow the Observer pattern, but rather it behaves more like a synchronous function call occurring within the publishing code. You may want to use a blocking event handler in the following situations: - The event handler is so critical that you need to ensure that it has completed before the publishing code continues. For example, if the event handler must manipulate some financial records. - Errors in the event handler code should cause the publishing code to fail (and any database transaction to be rolled back). - You want to guard against the edge case that a server instance gets shut down (due to e.g. a fatal error or an auto-scaling event) before event subscribers have been invoked. In these cases, you can use the `EventBus.registerBlockingEventHandler()` method: ```ts title="src/plugins/my-plugin/my-plugin.plugin.ts" import { Injectable, OnModuleInit } from '@nestjs/common'; import { EventBus, PluginCommonModule, VendurePlugin, CustomerEvent } from '@vendure/core'; import { CustomerSyncService } from './services/customer-sync.service'; @VendurePlugin({ imports: [PluginCommonModule], }) export class MyPluginPlugin implements OnModuleInit { constructor( private eventBus: EventBus, private customerSyncService: CustomerSyncService, ) {} onModuleInit() { // highlight-start this.eventBus.registerBlockingEventHandler({ event: CustomerEvent, id: 'sync-customer-details-handler', handler: async event => { // This hypothetical service method would do nothing // more than adding a new job to the job queue. This gives us // the guarantee that the job is added before the publishing // code is able to continue, while minimizing the time spent // in the event handler. await this.customerSyncService.triggerCustomerSyncJob(event); }, }); // highlight-end } } ``` Key differences between event subscribers and blocking event handlers: Aspect | Event subscribers | Blocking event handlers | |---|---|---| | **Execution** | Executed _after_ publishing code completes | Execute _during_ the publishing code | | **Error handling** | Errors do not affect publishing code | Errors propagated to publishing code | | **Transactions** | Guaranteed to execute only after the publishing code transaction has completed | Executed within the transaction of the publishing code | | **Performance** | Non-blocking: subscriber function performance has no effect on publishing code | Blocking: handler function will block execution of publishing code. Handler must be fast. | ### Performance considerations Since blocking event handlers execute within the same transaction as the publishing code, it is important to ensure that they are fast. If a single handler takes longer than 100ms to execute, a warning will be logged. Ideally they should be much faster than that - you can set your Logger's `logLevel` to `LogLevel.DEBUG` to see the execution time of each handler. If multiple handlers are registered for a single event, they will be executed sequentially, so the publishing code will be blocked until all handlers have completed. ### Order of execution If you register multiple handlers for the same event, they will be executed in the order in which they were registered. If you need more control over this order, i.e. to _guarantee_ that a particular handler will execute before another, you can use the `before` or `after` options: ```ts // In one part of your code base this.eventBus.registerBlockingEventHandler({ type: CustomerEvent, id: 'sync-customer-details-handler', handler: async event => { // ... }, }); // In another part of your code base this.eventBus.registerBlockingEventHandler({ type: CustomerEvent, id: 'check-customer-details-handler', handler: async event => { // ... }, // highlight-next-line before: 'sync-customer-details-handler', }); ```
--- title: 'Plugins' sidebar_position: 6 --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; The heart of Vendure is its plugin system. Plugins not only allow you to instantly add new functionality to your Vendure server via third-part npm packages, they are also the means by which you build out the custom business logic of your application. Plugins in Vendure allow one to: - Modify the VendureConfig object, such as defining custom fields on existing entities. - Extend the GraphQL APIs, including modifying existing types and adding completely new queries and mutations. - Define new database entities and interact directly with the database. - Interact with external systems that you need to integrate with. - Respond to events such as new orders being placed. - Trigger background tasks to run on the worker process. … and more! In a typical Vendure application, custom logic and functionality is implemented as a set of plugins which are usually independent of one another. For example, there could be a plugin for each of the following: wishlists, product reviews, loyalty points, gift cards, etc. This allows for a clean separation of concerns and makes it easy to add or remove functionality as needed. ## Core Plugins Vendure provides a set of core plugins covering common functionality such as assets handling, email sending, and search. For documentation on these, see the [Core Plugins reference](/reference/core-plugins/). ## Plugin basics Here's a bare-minimum example of a plugin: ```ts title="src/plugins/avatar-plugin/avatar.plugin.ts" import { LanguageCode, PluginCommonModule, VendurePlugin } from '@vendure/core'; @VendurePlugin({ imports: [PluginCommonModule], configuration: config => { config.customFields.Customer.push({ type: 'string', name: 'avatarUrl', label: [{ languageCode: LanguageCode.en, value: 'Avatar URL' }], list: true, }); return config; }, }) export class AvatarPlugin {} ``` This plugin does one thing only: it adds a new custom field to the `Customer` entity. The plugin is then imported into the `VendureConfig`: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; import { AvatarPlugin } from './plugins/avatar-plugin/avatar.plugin'; export const config: VendureConfig = { // ... // highlight-next-line plugins: [AvatarPlugin], }; ``` The key feature is the `@VendurePlugin()` decorator, which marks the class as a Vendure plugin and accepts a configuration object on the type [`VendurePluginMetadata`](/reference/typescript-api/plugin/vendure-plugin-metadata/). A VendurePlugin is actually an enhanced version of a [NestJS Module](https://docs.nestjs.com/modules), and supports all the metadata properties that NestJS modules support: - `imports`: Allows importing other NestJS modules in order to make use of their exported providers. - `providers`: The providers (services) that will be instantiated by the Nest injector and that may be shared across this plugin. - `controllers`: Controllers allow the plugin to define REST-style endpoints. - `exports`: The providers which will be exported from this plugin and made available to other plugins. Additionally, the `VendurePlugin` decorator adds the following Vendure-specific properties: - `configuration`: A function which can modify the `VendureConfig` object before the server bootstraps. - `shopApiExtensions`: Allows the plugin to extend the GraphQL Shop API with new queries, mutations, resolvers & scalars. - `adminApiExtensions`: Allows the plugin to extend the GraphQL Admin API with new queries, mutations, resolvers & scalars. - `entities`: Allows the plugin to define new database entities. - `compatibility`: Allows the plugin to declare which versions of Vendure it is compatible with. :::info Since a Vendure plugin is a superset of a NestJS module, this means that many NestJS modules are actually valid Vendure plugins! ::: ## Plugin lifecycle Since a VendurePlugin is built on top of the NestJS module system, any plugin (as well as any providers it defines) can make use of any of the [NestJS lifecycle hooks](https://docs.nestjs.com/fundamentals/lifecycle-events): - onModuleInit - onApplicationBootstrap - onModuleDestroy - beforeApplicationShutdown - onApplicationShutdown :::caution Note that lifecycle hooks are run in both the server and worker contexts. If you have code that should only run either in the server context or worker context, you can inject the [ProcessContext provider](/reference/typescript-api/common/process-context/). ::: ### Configure 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 used by NestJS to apply middleware. This method is called _only_ for the server and _not_ for the worker, since middleware relates to the network stack, and the worker has no network part. ```ts import { MiddlewareConsumer, NestModule } from '@nestjs/common'; import { EventBus, PluginCommonModule, VendurePlugin } from '@vendure/core'; import { MyMiddleware } from './api/my-middleware'; @VendurePlugin({ imports: [PluginCommonModule] }) export class MyPlugin implements NestModule { configure(consumer: MiddlewareConsumer) { consumer .apply(MyMiddleware) .forRoutes('my-custom-route'); } } ``` ## Create a Plugin via CLI :::cli Run the `npx vendure add` command, and select "Create a new Vendure plugin". This will guide you through the creation of a new plugin and automate all aspects of the process. This is the recommended way of creating a new plugin. ::: ## Writing a plugin from scratch 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 a plugin manually. 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. 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. ```txt β”œβ”€β”€src β”œβ”€β”€ index.ts β”œβ”€β”€ vendure-config.ts β”œβ”€β”€ plugins β”œβ”€β”€ reviews-plugin β”œβ”€β”€ cms-plugin β”œβ”€β”€ wishlist-plugin β”œβ”€β”€ stock-sync-plugin ``` :::info 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) You can also use the [Vendure CLI](/guides/developer-guide/cli) to quickly scaffold a new plugin. 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) ::: 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. ### Step 1: Create the plugin file We'll start by creating a new directory to house our plugin, add create the main plugin file: ```txt β”œβ”€β”€src β”œβ”€β”€ index.ts β”œβ”€β”€ vendure-config.ts β”œβ”€β”€ plugins // highlight-next-line β”œβ”€β”€ wishlist-plugin // highlight-next-line β”œβ”€β”€ wishlist.plugin.ts ``` ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts" import { PluginCommonModule, VendurePlugin } from '@vendure/core'; @VendurePlugin({ imports: [PluginCommonModule], }) export class WishlistPlugin {} ``` 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. ### Step 2: Define an entity 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. First let's create the file to house the entity: ```txt β”œβ”€β”€ wishlist-plugin β”œβ”€β”€ wishlist.plugin.ts β”œβ”€β”€ entities // highlight-next-line β”œβ”€β”€ wishlist-item.entity.ts ``` 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. ```ts title="src/plugins/wishlist-plugin/entities/wishlist-item.entity.ts" import { DeepPartial, ID, ProductVariant, VendureEntity, EntityId } from '@vendure/core'; import { Column, Entity, ManyToOne } from 'typeorm'; @Entity() export class WishlistItem extends VendureEntity { constructor(input?: DeepPartial<WishlistItem>) { super(input); } @ManyToOne(type => ProductVariant) productVariant: ProductVariant; @EntityId() productVariantId: ID; } ``` Let's break down what's happening here: - 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. - The `@Entity()` decorator marks this class as a TypeORM entity. - 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`. - 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. - 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. Next we need to register this entity with our plugin: ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts" import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { WishlistItem } from './entities/wishlist-item.entity'; @VendurePlugin({ imports: [PluginCommonModule], entities: [WishlistItem], }) export class WishlistPlugin {} ``` ### Step 3: Add a custom field to the Customer entity 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. Custom fields are defined in the VendureConfig object, and in a plugin we use the `configuration` function to modify the config object: ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts" import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { WishlistItem } from './entities/wishlist-item.entity'; @VendurePlugin({ imports: [PluginCommonModule], entities: [WishlistItem], configuration: config => { config.customFields.Customer.push({ name: 'wishlistItems', type: 'relation', list: true, entity: WishlistItem, internal: true, }); return config; }, }) export class WishlistPlugin {} ``` 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. 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: ```txt β”œβ”€β”€ wishlist-plugin β”œβ”€β”€ wishlist.plugin.ts // highlight-next-line β”œβ”€β”€ types.ts ``` ```ts title="src/plugins/wishlist-plugin/types.ts" import { WishlistItem } from './entities/wishlist-item.entity'; declare module '@vendure/core/dist/entity/custom-entity-fields' { interface CustomCustomerFields { wishlistItems: WishlistItem[]; } } ``` We can then import this types file in our plugin's main file: ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts" // highlight-next-line import './types'; ``` ### Step 4: Create a service 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. Let's create a service to handle the wishlist functionality: ```txt β”œβ”€β”€ wishlist-plugin β”œβ”€β”€ wishlist.plugin.ts β”œβ”€β”€ services // highlight-next-line β”œβ”€β”€ wishlist.service.ts ``` ```ts title="src/plugins/wishlist-plugin/services/wishlist.service.ts" import { Injectable } from '@nestjs/common'; import { Customer, ForbiddenError, ID, InternalServerError, ProductVariantService, RequestContext, TransactionalConnection, UserInputError, } from '@vendure/core'; import { WishlistItem } from '../entities/wishlist-item.entity'; @Injectable() export class WishlistService { constructor( private connection: TransactionalConnection, private productVariantService: ProductVariantService, ) {} async getWishlistItems(ctx: RequestContext): Promise<WishlistItem[]> { try { const customer = await this.getCustomerWithWishlistItems(ctx); return customer.customFields.wishlistItems; } catch (err: any) { return []; } } /** * Adds a new item to the active Customer's wishlist. */ async addItem(ctx: RequestContext, variantId: ID): Promise<WishlistItem[]> { const customer = await this.getCustomerWithWishlistItems(ctx); const variant = this.productVariantService.findOne(ctx, variantId); if (!variant) { throw new UserInputError(`No ProductVariant with the id ${variantId} could be found`); } const existingItem = customer.customFields.wishlistItems.find(i => i.productVariantId === variantId); if (existingItem) { // Item already exists in wishlist, do not // add it again return customer.customFields.wishlistItems; } const wishlistItem = await this.connection .getRepository(ctx, WishlistItem) .save(new WishlistItem({ productVariantId: variantId })); customer.customFields.wishlistItems.push(wishlistItem); await this.connection.getRepository(ctx, Customer).save(customer, { reload: false }); return this.getWishlistItems(ctx); } /** * Removes an item from the active Customer's wishlist. */ async removeItem(ctx: RequestContext, itemId: ID): Promise<WishlistItem[]> { const customer = await this.getCustomerWithWishlistItems(ctx); const itemToRemove = customer.customFields.wishlistItems.find(i => i.id === itemId); if (itemToRemove) { await this.connection.getRepository(ctx, WishlistItem).remove(itemToRemove); customer.customFields.wishlistItems = customer.customFields.wishlistItems.filter( i => i.id !== itemId, ); } await this.connection.getRepository(ctx, Customer).save(customer); return this.getWishlistItems(ctx); } /** * Gets the active Customer from the context and loads the wishlist items. */ private async getCustomerWithWishlistItems(ctx: RequestContext): Promise<Customer> { if (!ctx.activeUserId) { throw new ForbiddenError(); } const customer = await this.connection.getRepository(ctx, Customer).findOne({ where: { user: { id: ctx.activeUserId } }, relations: { customFields: { wishlistItems: { productVariant: true, }, }, }, }); if (!customer) { throw new InternalServerError(`Customer was not found`); } return customer; } } ``` Let's break down what's happening here: - 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. - 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. - 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`. The service is then registered with the plugin metadata as a provider: ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts" import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { WishlistService } from './services/wishlist.service'; @VendurePlugin({ imports: [PluginCommonModule], // highlight-next-line providers: [WishlistService], entities: [WishlistItem], configuration: config => { // ... }, }) export class WishlistPlugin {} ``` ### Step 5: Extend the GraphQL API This plugin will need to extend the Shop API, adding new mutations and queries to enable the customer to view and manage their wishlist. First we will create a new file to hold the GraphQL schema extensions: ```txt β”œβ”€β”€ wishlist-plugin β”œβ”€β”€ wishlist.plugin.ts β”œβ”€β”€ api // highlight-next-line β”œβ”€β”€ api-extensions.ts ``` ```ts title="src/plugins/wishlist-plugin/api/api-extensions.ts" import gql from 'graphql-tag'; export const shopApiExtensions = gql` type WishlistItem implements Node { id: ID! createdAt: DateTime! updatedAt: DateTime! productVariant: ProductVariant! productVariantId: ID! } extend type Query { activeCustomerWishlist: [WishlistItem!]! } extend type Mutation { addToWishlist(productVariantId: ID!): [WishlistItem!]! removeFromWishlist(itemId: ID!): [WishlistItem!]! } `; ``` :::note 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`. ::: 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. Next we need to pass these extensions to our plugin's metadata: ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts" import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { shopApiExtensions } from './api/api-extensions'; @VendurePlugin({ imports: [PluginCommonModule], shopApiExtensions: { schema: shopApiExtensions, resolvers: [], }, }) export class WishlistPlugin {} ``` ### Step 6: Create a resolver 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: ```txt β”œβ”€β”€ wishlist-plugin β”œβ”€β”€ wishlist.plugin.ts β”œβ”€β”€ api β”œβ”€β”€ api-extensions.ts // highlight-next-line β”œβ”€β”€ wishlist.resolver.ts ``` ```ts title="src/plugins/wishlist-plugin/api/wishlist.resolver.ts" import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { Allow, Ctx, Permission, RequestContext, Transaction } from '@vendure/core'; import { WishlistItem } from '../entities/wishlist-item.entity'; import { WishlistService } from '../services/wishlist.service'; @Resolver() export class WishlistShopResolver { constructor(private wishlistService: WishlistService) {} @Query() @Allow(Permission.Owner) activeCustomerWishlist(@Ctx() ctx: RequestContext) { return this.wishlistService.getWishlistItems(ctx); } @Mutation() @Transaction() @Allow(Permission.Owner) async addToWishlist( @Ctx() ctx: RequestContext, @Args() { productVariantId }: { productVariantId: string }, ) { return this.wishlistService.addItem(ctx, productVariantId); } @Mutation() @Transaction() @Allow(Permission.Owner) async removeFromWishlist(@Ctx() ctx: RequestContext, @Args() { itemId }: { itemId: string }) { return this.wishlistService.removeItem(ctx, itemId); } } ``` 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: - 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. - 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. - 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. - 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. - 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. This resolver is then registered with the plugin metadata: ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts" import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { shopApiExtensions } from './api/api-extensions'; import { WishlistShopResolver } from './api/wishlist.resolver'; @VendurePlugin({ imports: [PluginCommonModule], shopApiExtensions: { schema: shopApiExtensions, // highlight-next-line resolvers: [WishlistShopResolver], }, configuration: config => { // ... }, }) export class WishlistPlugin {} ``` :::info More information about resolvers can be found in the [NestJS docs](https://docs.nestjs.com/graphql/resolvers). ::: ### Step 7: Specify compatibility 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. The compatibility is specified via the `compatibility` property in the plugin metadata: ```ts title="src/plugins/wishlist-plugin/wishlist.plugin.ts" @VendurePlugin({ // ... // highlight-next-line compatibility: '^2.0.0', }) export class WishlistPlugin {} ``` 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`. ### Step 8: Add the plugin to the VendureConfig The final step is to add the plugin to the `VendureConfig` object. This is done in the `vendure-config.ts` file: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; import { WishlistPlugin } from './plugins/wishlist-plugin/wishlist.plugin'; export const config: VendureConfig = { // ... plugins: [ // ... // highlight-next-line WishlistPlugin, ], }; ``` ### Test the plugin 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: ```bash npm run migration:generate wishlist-plugin ``` Then start the server: ```bash npm run dev ``` Once the server is running, we should be able to log in as an existing Customer, and then add a product to the wishlist: <Tabs> <TabItem value="Login mutation" label="Login mutation" default> ```graphql mutation Login { login(username: "alec.breitenberg@gmail.com", password: "test") { ... on CurrentUser { id identifier } ... on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Response" label="Response"> ```json { "data": { "login": { "id": "9", "identifier": "alec.breitenberg@gmail.com" } } } ``` </TabItem> </Tabs> <Tabs> <TabItem value="AddToWishlist mutation" label="AddToWishlist mutation" default> ```graphql mutation AddToWishlist { addToWishlist(productVariantId: "7") { id productVariant { id name } } } ``` </TabItem> <TabItem value="Response" label="Response"> ```json { "data": { "addToWishlist": [ { "id": "4", "productVariant": { "id": "7", "name": "Wireless Optical Mouse" } } ] } } ``` </TabItem> </Tabs> We can then query the wishlist items: <Tabs> <TabItem value="GetWishlist mutation" label="GetWishlist mutation" default> ```graphql query GetWishlist { activeCustomerWishlist { id productVariant { id name } } } ``` </TabItem> <TabItem value="Response" label="Response"> ```json { "data": { "activeCustomerWishlist": [ { "id": "4", "productVariant": { "id": "7", "name": "Wireless Optical Mouse" } } ] } } ``` </TabItem> </Tabs> And finally, we can test removing an item from the wishlist: <Tabs> <TabItem value="RemoveFromWishlist mutation" label="RemoveFromWishlist mutation" default> ```graphql mutation RemoveFromWishlist { removeFromWishlist(itemId: "4") { id productVariant { name } } } ``` </TabItem> <TabItem value="Response" label="Response"> ```json { "data": { "removeFromWishlist": [] } } ``` </TabItem> </Tabs>
--- title: 'Strategies & Configurable Operations' sidebar_position: 4 --- Vendure is built to be highly configurable and extensible. Two methods of providing this extensibility are **strategies** and **configurable operations**. ## Strategies A strategy is named after the [Strategy Pattern](https://en.wikipedia.org/wiki/Strategy_pattern), and is a way of providing a pluggable implementation of a particular feature. Vendure makes heavy use of this pattern to delegate the implementation of key points of extensibility to the developer. Examples of strategies include: - [`OrderCodeStrategy`](/reference/typescript-api/orders/order-code-strategy/) - determines how order codes are generated - [`StockLocationStrategy`](/reference/typescript-api/products-stock/stock-location-strategy/) - determines which stock locations are used to fulfill an order - [`ActiveOrderStrategy`](/reference/typescript-api/orders/active-order-strategy/) - determines how the active order in the Shop API is selected - [`AssetStorageStrategy`](/reference/typescript-api/assets/asset-storage-strategy/) - determines where uploaded assets are stored - [`GuestCheckoutStrategy`](/reference/typescript-api/orders/guest-checkout-strategy/) - defines rules relating to guest checkouts - [`OrderItemPriceCalculationStrategy`](/reference/typescript-api/orders/order-item-price-calculation-strategy/) - determines how items are priced when added to the order - [`TaxLineCalculationStrategy`](/reference/typescript-api/tax/tax-line-calculation-strategy/) - determines how tax is calculated for an order line As an example, let's take the [`OrderCodeStrategy`](/reference/typescript-api/orders/order-code-strategy/). This strategy determines how codes are generated when new orders are created. By default, Vendure will use the built-in `DefaultOrderCodeStrategy` which generates a random 16-character string. What if you need to change this behavior? For instance, you might have an existing back-office system that is responsible for generating order codes, which you need to integrate with. Here's how you would do this: ```ts title="src/config/my-order-code-strategy.ts" import { OrderCodeStrategy, RequestContext } from '@vendure/core'; import { OrderCodeService } from '../services/order-code.service'; export class MyOrderCodeStrategy implements OrderCodeStrategy { private orderCodeService: OrderCodeService; init(injector) { this.orderCodeService = injector.get(OrderCodeService); } async generate(ctx: RequestContext): string { return this.orderCodeService.getNewOrderCode(); } } ``` :::info All strategies can be make use of existing services by using the `init()` method. This is because all strategies extend the underlying [`InjectableStrategy` interface](/reference/typescript-api/common/injectable-strategy). In this example we are assuming that we already created an `OrderCodeService` which contains all the specific logic for connecting to our backend service which generates the order codes. ::: We then need to pass this custom strategy to our config: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; import { MyOrderCodeStrategy } from '../config/my-order-code-strategy'; export const config: VendureConfig = { // ... orderOptions: { // highlight-next-line orderCodeStrategy: new MyOrderCodeStrategy(), }, } ``` ### Strategy lifecycle Strategies can use two optional lifecycle methods: - `init(injector: Injector)` - called during the bootstrap phase when the server or worker is starting up. This is where you can inject any services which you need to use in the strategy. You can also perform any other setup logic needed, such as instantiating a connection to an external service. - `destroy()` - called during the shutdown of the server or worker. This is where you can perform any cleanup logic, such as closing connections to external services. ### Passing options to a strategy Sometimes you might want to pass some configuration options to a strategy. For example, imagine you want to create a custom [`StockLocationStrategy`](/reference/typescript-api/products-stock/stock-location-strategy/) which selects a location within a given proximity to the customer's address. You might want to pass the maximum distance to the strategy in your config: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; import { MyStockLocationStrategy } from '../config/my-stock-location-strategy'; export const config: VendureConfig = { // ... catalogOptions: { // highlight-next-line stockLocationStrategy: new MyStockLocationStrategy({ maxDistance: 100 }), }, } ``` This config will be passed to the strategy's constructor: ```ts title="src/config/my-stock-location-strategy.ts" import { ID, ProductVariant, RequestContext, StockLevel, StockLocationStrategy } from '@vendure/core'; export class MyStockLocationStrategy implements StockLocationStrategy { constructor(private options: { maxDistance: number }) {} getAvailableStock( ctx: RequestContext, productVariantId: ID, stockLevels: StockLevel[] ): ProductVariant[] { const maxDistance = this.options.maxDistance; // ... implementation omitted } } ``` ## Configurable Operations Configurable operations are similar to strategies in that they allow certain aspects of the system to be customized. However, the main difference is that they can also be _configured_ via the Admin UI. This allows the store owner to make changes to the behavior of the system without having to restart the server. So they are typically used to supply some custom logic that needs to accept configurable arguments which can change at runtime. Vendure uses the following configurable operations: - [`CollectionFilter`](/reference/typescript-api/configuration/collection-filter/) - determines which products are included in a collection - [`PaymentMethodHandler`](/reference/typescript-api/payment/payment-method-handler/) - determines how payments are processed - [`PromotionCondition`](/reference/typescript-api/promotions/promotion-condition/) - determines whether a promotion is applicable - [`PromotionAction`](/reference/typescript-api/promotions/promotion-action/) - determines what happens when a promotion is applied - [`ShippingEligibilityChecker`](/reference/typescript-api/shipping/shipping-eligibility-checker/) - determines whether a shipping method is available - [`ShippingCalculator`](/reference/typescript-api/shipping/shipping-calculator/) - determines how shipping costs are calculated Whereas strategies are typically used to provide a single implementation of a particular feature, configurable operations are used to provide a set of implementations which can be selected from at runtime. For example, Vendure ships with a set of default CollectionFilters: ```ts title="default-collection-filters.ts" export const defaultCollectionFilters = [ facetValueCollectionFilter, variantNameCollectionFilter, variantIdCollectionFilter, productIdCollectionFilter, ]; ``` When setting up a Collection, you can choose from these available default filters: ![CollectionFilters](./collection-filters.webp) When one is selected, the UI will allow you to configure the arguments for that filter: ![CollectionFilters args](./collection-filters-args.webp) Let's take a look at a simplified implementation of the `variantNameCollectionFilter`: ```ts title="variant-name-collection-filter.ts" import { CollectionFilter, LanguageCode } from '@vendure/core'; export const variantNameCollectionFilter = new CollectionFilter({ args: { operator: { type: 'string', ui: { component: 'select-form-input', options: [ { value: 'startsWith' }, { value: 'endsWith' }, { value: 'contains' }, { value: 'doesNotContain' }, ], }, }, term: { type: 'string' }, }, code: 'variant-name-filter', description: [{ languageCode: LanguageCode.en, value: 'Filter by product variant name' }], apply: (qb, args) => { // ... implementation omitted }, }); ``` Here are the important parts: - Configurable operations are **instances** of a pre-defined class, and are instantiated before being passed to your config. - They must have a `code` property which is a unique string identifier. - They must have a `description` property which is a localizable, human-readable description of the operation. - They must have an `args` property which defines the arguments which can be configured via the Admin UI. If the operation has no arguments, then this would be an empty object. - They will have one or more methods that need to be implemented, depending on the type of operation. In this case, the `apply()` method is used to apply the filter to the query builder. ### Configurable operation args The `args` property is an object which defines the arguments which can be configured via the Admin UI. Each property of the `args` object is a key-value pair, where the key is the name of the argument, and the value is an object which defines the type of the argument and any additional configuration. As an example let's look at the `dummyPaymentMethodHandler`, a test payment method which we ship with Vendure core: ```ts title="dummy-payment-method.ts" import { PaymentMethodHandler, LanguageCode } from '@vendure/core'; export const dummyPaymentHandler = new PaymentMethodHandler({ code: 'dummy-payment-handler', description: [/* omitted for brevity */], args: { automaticSettle: { type: 'boolean', label: [ { languageCode: LanguageCode.en, value: 'Authorize and settle in 1 step', }, ], description: [ { languageCode: LanguageCode.en, value: 'If enabled, Payments will be created in the "Settled" state.', }, ], required: true, defaultValue: false, }, }, createPayment: async (ctx, order, amount, args, metadata, method) => { // Inside this method, the `args` argument is type-safe and will be // an object with the following shape: // { // automaticSettle: boolean // } // ... implementation omitted }, }) ``` The following properties are used to configure the argument: #### type <span class="badge badge--primary">Required</span> [`ConfigArgType`](/reference/typescript-api/configurable-operation-def/config-arg-type) The following types are available: `string`, `int`, `float`, `boolean`, `datetime`, `ID`. #### label <span class="badge badge--secondary">Optional</span> [`LocalizedStringArray`](/reference/typescript-api/configurable-operation-def/localized-string-array/) A human-readable label for the argument. This is used in the Admin UI. #### description <span class="badge badge--secondary">Optional</span> [`LocalizedStringArray`](/reference/typescript-api/configurable-operation-def/localized-string-array/) A human-readable description for the argument. This is used in the Admin UI as a tooltip. #### required <span class="badge badge--secondary">Optional</span> `boolean` Whether the argument is required. If `true`, then the Admin UI will not allow the user to save the configuration unless a value has been provided for this argument. #### defaultValue <span class="badge badge--secondary">Optional</span> `any` (depends on the `type`) The default value for the argument. If not provided, then the argument will be `undefined` by default. #### list <span class="badge badge--secondary">Optional</span> `boolean` Whether the argument is a list of values. If `true`, then the Admin UI will allow the user to add multiple values for this argument. Defaults to `false`. #### ui <span class="badge badge--secondary">Optional</span> Allows you to specify the UI component that will be used to render the argument in the Admin UI, by specifying a `component` property, and optional properties to configure that component. ```ts { args: { operator: { type: 'string', ui: { component: 'select-form-input', options: [ { value: 'startsWith' }, { value: 'endsWith' }, { value: 'contains' }, { value: 'doesNotContain' }, ], }, }, } } ``` A full description of the available UI components can be found in the [Custom Fields guide](/guides/developer-guide/custom-fields/#custom-field-ui). ### Injecting dependencies Configurable operations are instantiated before being passed to your config, so the mechanism for injecting dependencies is similar to that of strategies: namely you use an optional `init()` method to inject dependencies into the operation instance. The main difference is that the injected dependency cannot then be stored as a class property, since you are not defining a class when you define a configurable operation. Instead, you can store the dependency as a closure variable. Here’s an example of a ShippingCalculator that injects a service which has been defined in a plugin: ```ts title="src/config/custom-shipping-calculator.ts" import { Injector, ShippingCalculator } from '@vendure/core'; import { ShippingRatesService } from './shipping-rates.service'; // We keep reference to our injected service by keeping it // in the top-level scope of the file. let shippingRatesService: ShippingRatesService; export const customShippingCalculator = new ShippingCalculator({ code: 'custom-shipping-calculator', description: [], args: {}, init(injector: Injector) { // The init function is called during bootstrap, and allows // us to inject any providers we need. shippingRatesService = injector.get(ShippingRatesService); }, calculate: async (order, args) => { // We can now use the injected provider in the business logic. const { price, priceWithTax } = await shippingRatesService.getRate({ destination: order.shippingAddress, contents: order.lines, }); return { price, priceWithTax, }; }, }); ```
--- title: 'The API Layer' sidebar_position: 1 --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Vendure is a headless platform, which means that all functionality is exposed via GraphQL APIs. The API can be thought of as a number of layers through which a request will pass, each of which is responsible for a different aspect of the request/response lifecycle. ## The journey of an API call Let's take a basic API call and trace its journey from the client to the server and back again. <Tabs> <TabItem value="Request" label="Request" default> ```graphql title="GraphQL Playground Shop API" query { product(id: "1") { id name description } } ``` This query is asking for the `id`, `name` and `description` of a `Product` with the id of `1`. </TabItem> <TabItem value="Response" label="Response"> ```json { "data": { "product": { "id": "1", "name": "Laptop", "description": "Now equipped with seventh-generation Intel Core processors, Laptop is snappier than ever. From daily tasks like launching apps and opening files to more advanced computing, you can power through your day thanks to faster SSDs and Turbo Boost processing up to 3.6GHz." } } } ``` GraphQL returns only the specific fields you ask for in your query. </TabItem> </Tabs> :::note If you have your local development server running, you can try this out by opening the GraphQL Playground in your browser: [http://localhost:3000/shop-api](http://localhost:3000/shop-api) ::: ![./Vendure_docs-api_request.webp](./Vendure_docs-api_request.webp) ## Middleware "Middleware" is a term for a function which is executed before or after the main logic of a request. In Vendure, middleware is used to perform tasks such as authentication, logging, and error handling. There are several types of middleware: ### Express middleware At the lowest level, Vendure makes use of the popular Express server library. [Express middleware](https://expressjs.com/en/guide/using-middleware.html) can be added to the sever via the [`apiOptions.middleware`](/reference/typescript-api/configuration/api-options#middleware) config property. There are hundreds of tried-and-tested Express middleware packages available, and they can be used to add functionality such as CORS, compression, rate-limiting, etc. Here's a simple example demonstrating Express middleware which will log a message whenever a request is received to the Admin API: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; import { RequestHandler } from 'express'; /** * This is a custom middleware function that logs a message whenever a request is received. */ const myMiddleware: RequestHandler = (req, res, next) => { console.log('Request received!'); next(); }; export const config: VendureConfig = { // ... apiOptions: { middleware: [ { // We will execute our custom handler only for requests to the Admin API route: 'admin-api', handler: myMiddleware, } ], }, }; ``` ### NestJS middleware You can also define [NestJS middleware](https://docs.nestjs.com/middleware) which works like Express middleware but also has access to the NestJS dependency injection system. ```ts title="src/vendure-config.ts" import { VendureConfig, ConfigService } from '@vendure/core'; import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() class MyNestMiddleware implements NestMiddleware { // Dependencies can be injected via the constructor constructor(private configService: ConfigService) {} use(req: Request, res: Response, next: NextFunction) { console.log(`NestJS middleware: current port is ${this.configService.apiOptions.port}`); next(); } } export const config: VendureConfig = { // ... apiOptions: { middleware: [ { route: 'admin-api', handler: MyNestMiddleware, } ], }, }; ``` NestJS allows you to define specific types of middleware including [Guards](https://docs.nestjs.com/guards), [Interceptors](https://docs.nestjs.com/interceptors), [Pipes](https://docs.nestjs.com/pipes) and [Filters](https://docs.nestjs.com/exception-filters). Vendure uses a number of these mechanisms internally to handle authentication, transaction management, error handling and data transformation. ### Global NestJS middleware Guards, interceptors, pipes and filters can be added to your own custom resolvers and controllers using the NestJS decorators as given in the NestJS docs. However, a common pattern is to register them globally via a [Vendure plugin](/guides/developer-guide/plugins/): ```ts title="src/plugins/my-plugin/my-plugin.ts" import { VendurePlugin } from '@vendure/core'; import { APP_GUARD, APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core'; // Some custom NestJS middleware classes which we want to apply globally import { MyCustomGuard, MyCustomInterceptor, MyCustomExceptionFilter } from './my-custom-middleware'; @VendurePlugin({ // ... providers: [ // This is the syntax needed to apply your guards, // interceptors and filters globally { provide: APP_GUARD, useClass: MyCustomGuard, }, { provide: APP_INTERCEPTOR, useClass: MyCustomInterceptor, }, { // Note: registering a global "catch all" exception filter // must be used with caution as it will override the built-in // Vendure exception filter. See https://github.com/nestjs/nest/issues/3252 // To implement custom error handling, it is recommended to use // a custom ErrorHandlerStrategy instead. provide: APP_FILTER, useClass: MyCustomExceptionFilter, }, ], }) export class MyPlugin {} ``` Adding this plugin to your Vendure config `plugins` array will now apply these middleware classes to all requests. ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; import { MyPlugin } from './plugins/my-plugin/my-plugin'; export const config: VendureConfig = { // ... plugins: [ MyPlugin, ], }; ``` ### Apollo Server plugins Apollo Server (the underlying GraphQL server library used by Vendure) allows you to define [plugins](https://www.apollographql.com/docs/apollo-server/integrations/plugins/) which can be used to hook into various stages of the GraphQL request lifecycle and perform tasks such as data transformation. These are defined via the [`apiOptions.apolloServerPlugins`](/reference/typescript-api/configuration/api-options#apolloserverplugins) config property. ## Resolvers A "resolver" is a GraphQL concept, and refers to a function which is responsible for returning the data for a particular field. In Vendure, a resolver can also refer to a class which contains multiple resolver functions. For every query or mutation, there is a corresponding resolver function which is responsible for returning the requested data (and performing side-effect such as updating data in the case of mutations). Here's a simplified example of a resolver function for the `product` query: ```ts import { Query, Resolver, Args } from '@nestjs/graphql'; import { Ctx, RequestContext, ProductService } from '@vendure/core'; @Resolver() export class ShopProductsResolver { constructor(private productService: ProductService) {} @Query() product(@Ctx() ctx: RequestContext, @Args() args: { id: string }) { return this.productService.findOne(ctx, args.id); } } ``` - The `@Resolver()` decorator marks this class as a resolver. - The `@Query()` decorator marks the `product()` method as a resolver function. - The `@Ctx()` decorator injects the [`RequestContext` object](/reference/typescript-api/request/request-context/), which contains information about the current request, such as the current user, the active channel, the active language, etc. The `RequestContext` is a key part of the Vendure architecture, and is used throughout the application to provide context to the various services and plugins. In general, your resolver functions should always accept a `RequestContext` as the first argument, and pass it through to the services. - The `@Args()` decorator injects the arguments passed to the query, in this case the `id` that we provided in our query. As you can see, the resolver function is very simple, and simply delegates the work to the `ProductService` which is responsible for fetching the data from the database. :::tip In general, resolver functions should be kept as simple as possible, and the bulk of the business logic should be delegated to the service layer. ::: ## API Decorators Following the pattern of NestJS, Vendure makes use of decorators to control various aspects of the API. Here are the important decorators to be aware of: ### `@Resolver()` This is exported by the `@nestjs/graphql` package. It marks a class as a resolver, meaning that its methods can be used to resolve the fields of a GraphQL query or mutation. ```ts title="src/plugins/wishlist/api/wishlist.resolver.ts" import { Resolver } from '@nestjs/graphql'; // highlight-next-line @Resolver() export class WishlistResolver { // ... } ``` ### `@Query()` This is exported by the `@nestjs/graphql` package. It marks a method as a resolver function for a query. The method name should match the name of the query in the GraphQL schema, or if the method name is different, a name can be provided as an argument to the decorator. ```ts title="src/plugins/wishlist/api/wishlist.resolver.ts" import { Query, Resolver } from '@nestjs/graphql'; @Resolver() export class WishlistResolver { // highlight-next-line @Query() wishlist() { // ... } } ``` ### `@Mutation()` This is exported by the `@nestjs/graphql` package. It marks a method as a resolver function for a mutation. The method name should match the name of the mutation in the GraphQL schema, or if the method name is different, a name can be provided as an argument to the decorator. ```ts title="src/plugins/wishlist/api/wishlist.resolver.ts" import { Mutation, Resolver } from '@nestjs/graphql'; @Resolver() export class WishlistResolver { // highlight-next-line @Mutation() addItemToWishlist() { // ... } } ``` ### `@Allow()` The [`Allow` decorator](/reference/typescript-api/request/allow-decorator) is exported by the `@vendure/core` package. It is used to control access to queries and mutations. It takes a list of [Permissions](/reference/typescript-api/common/permission/) and if the current user does not have at least one of the permissions, then the query or mutation will return an error. ```ts title="src/plugins/wishlist/api/wishlist.resolver.ts" import { Mutation, Resolver } from '@nestjs/graphql'; import { Allow, Permission } from '@vendure/core'; @Resolver() export class WishlistResolver { @Mutation() // highlight-next-line @Allow(Permission.UpdateCustomer) updateCustomerWishlist() { // ... } } ``` ### `@Transaction()` The [`Transaction` decorator](/reference/typescript-api/request/transaction-decorator/) is exported by the `@vendure/core` package. It is used to wrap a resolver function in a database transaction. It is normally used with mutations, since queries typically do not modify data. ```ts title="src/plugins/wishlist/api/wishlist.resolver.ts" import { Mutation, Resolver } from '@nestjs/graphql'; import { Transaction } from '@vendure/core'; @Resolver() export class WishlistResolver { // highlight-next-line @Transaction() @Mutation() addItemToWishlist() { // if an error is thrown here, the // entire transaction will be rolled back } } ``` :::note The `@Transaction()` decorator _only_ works when used with a `RequestContext` object (see the `@Ctx()` decorator below). This is because the `Transaction` decorator stores the transaction context on the `RequestContext` object, and by passing this object to the service layer, the services and thus database calls can access the transaction context. ::: ### `@Ctx()` The [`Ctx` decorator](/reference/typescript-api/request/ctx-decorator/) is exported by the `@vendure/core` package. It is used to inject the [`RequestContext` object](/reference/typescript-api/request/request-context/) into a resolver function. The `RequestContext` contains information about the current request, such as the current user, the active channel, the active language, etc. The `RequestContext` is a key part of the Vendure architecture, and is used throughout the application to provide context to the various services and plugins. ```ts title="src/plugins/wishlist/api/wishlist.resolver.ts" import { Mutation, Resolver } from '@nestjs/graphql'; import { Ctx, RequestContext } from '@vendure/core'; @Resolver() export class WishlistResolver { @Mutation() // highlight-next-line addItemToWishlist(@Ctx() ctx: RequestContext) { // ... } } ``` :::tip As a general rule, _always_ use the `@Ctx()` decorator to inject the `RequestContext` into your resolver functions. ::: ### `@Args()` This is exported by the `@nestjs/graphql` package. It is used to inject the arguments passed to a query or mutation. Given the a schema definition like this: ```graphql extend type Mutation { addItemToWishlist(variantId: ID!): Wishlist } ``` The resolver function would look like this: ```ts title="src/plugins/wishlist/api/wishlist.resolver.ts" import { Mutation, Resolver, Args } from '@nestjs/graphql'; import { Ctx, RequestContext, ID } from '@vendure/core'; @Resolver() export class WishlistResolver { @Mutation() addItemToWishlist( @Ctx() ctx: RequestContext, // highlight-next-line @Args() args: { variantId: ID } ) { // ... } } ``` As you can see, the `@Args()` decorator injects the arguments passed to the query, in this case the `variantId` that we provided in our query. ## Field resolvers So far, we've seen examples of resolvers for queries and mutations. However, there is another type of resolver which is used to resolve the fields of a type. For example, given the following schema definition: ```graphql type WishlistItem { id: ID! // highlight-next-line product: Product! } ``` The `product` field is a relation to the `Product` type. The `product` field resolver would look like this: ```ts title="src/plugins/wishlist/api/wishlist-item.resolver.ts" import { Parent, ResolveField, Resolver } from '@nestjs/graphql'; import { Ctx, RequestContext } from '@vendure/core'; import { WishlistItem } from '../entities/wishlist-item.entity'; // highlight-next-line @Resolver('WishlistItem') export class WishlistItemResolver { // highlight-next-line @ResolveField() product( @Ctx() ctx: RequestContext, // highlight-next-line @Parent() wishlistItem: WishlistItem ) { // ... } } ``` Note that in this example, the `@Resolver()` decorator has an argument of `'WishlistItem'`. This tells NestJS that this resolver is for the `WishlistItem` type, and that when we use the `@ResolveField()` decorator, we are defining a resolver for a field of that type. In this example we're defining a resolver for the `product` field of the `WishlistItem` type. The `@ResolveField()` decorator is used to mark a method as a field resolver. The method name should match the name of the field in the GraphQL schema, or if the method name is different, a name can be provided as an argument to the decorator. ## REST endpoints Although Vendure is primarily a GraphQL-based API, it is possible to add REST endpoints to the API. This is useful if you need to integrate with a third-party service or client application which only supports REST, for example. Creating a REST endpoint is covered in detail in the [Add a REST endpoint guide](/guides/developer-guide/rest-endpoint/).
--- title: 'The Service Layer' sidebar_position: 2 --- The service layer is the core of the application. This is where the business logic is implemented, and where the application interacts with the database. When a request comes in to the API, it gets routed to a resolver which then calls a service method to perform the required operation. ![../the-api-layer/Vendure_docs-api_request.webp](../the-api-layer/Vendure_docs-api_request.webp) :::info Services are classes which, in NestJS terms, are [providers](https://docs.nestjs.com/providers#services). They follow all the rules of NestJS providers, including dependency injection, scoping, etc. ::: Services are generally scoped to a specific domain or entity. For instance, in the Vendure core, there is a [`Product` entity](/reference/typescript-api/entities/product), and a corresponding [`ProductService`](/reference/typescript-api/services/product-service) which contains all the methods for interacting with products. Here's a simplified example of a `ProductService`, including an implementation of the `findOne()` method that was used in the example in the [previous section](/guides/developer-guide/the-api-layer/#resolvers): ```ts title="src/services/product.service.ts" import { Injectable } from '@nestjs/common'; import { IsNull } from 'typeorm'; import { ID, Product, RequestContext, TransactionalConnection, TranslatorService } from '@vendure/core'; @Injectable() export class ProductService { constructor(private connection: TransactionalConnection, private translator: TranslatorService){} /** * @description * Returns a Product with the given id, or undefined if not found. */ async findOne(ctx: RequestContext, productId: ID): Promise<Product | undefined> { const product = await this.connection.findOneInChannel(ctx, Product, productId, ctx.channelId, { where: { deletedAt: IsNull(), }, }); if (!product) { return; } return this.translator.translate(product, ctx); } // ... other methods findMany() {} create() {} update() {} } ``` - The `@Injectable()` decorator is a [NestJS](https://docs.nestjs.com/providers#services) decorator which allows the service to be injected into other services or resolvers. - The `constructor()` method is where the dependencies of the service are injected. In this case, the `TransactionalConnection` is used to access the database, and the `TranslatorService` is used to translate the Product entity into the current language. ## Using core services All the internal Vendure services can be used in your own plugins and scripts. They are listed in the [Services API reference](/reference/typescript-api/services/) and can be imported from the `@vendure/core` package. To make use of a core service in your own plugin, you need to ensure your plugin is importing the `PluginCommonModule` and then inject the desired service into your own service's constructor: ```ts title="src/my-plugin/my.plugin.ts" import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { MyService } from './services/my.service'; @VendurePlugin({ // highlight-start imports: [PluginCommonModule], providers: [MyService], // highlight-end }) export class MyPlugin {} ``` ```ts title="src/my-plugin/services/my.service.ts" import { Injectable } from '@nestjs/common'; import { ProductService } from '@vendure/core'; @Injectable() export class MyService { // highlight-next-line constructor(private productService: ProductService) {} // you can now use the productService methods } ``` ## Accessing the database One of the main responsibilities of the service layer is to interact with the database. For this, you will be using the [`TransactionalConnection` class](/reference/typescript-api/data-access/transactional-connection/), which is a wrapper around the [TypeORM `DataSource` object](https://typeorm.io/data-source-api). The primary purpose of the `TransactionalConnection` is to ensure that database operations can be performed within a transaction (which is essential for ensuring data integrity), even across multiple services. Furthermore, it exposes some helper methods which make it easier to perform common operations. :::info Always pass the `RequestContext` (`ctx`) to the `TransactionalConnection` methods. This ensures the operation occurs within any active transaction. ::: There are two primary APIs for accessing data provided by TypeORM: the **Find API** and the **QueryBuilder API**. ### The Find API This API is the most convenient and type-safe way to query the database. It provides a powerful type-safe way to query including support for eager relations, pagination, sorting, filtering and more. Here are some examples of using the Find API: ```ts title="src/services/item.service.ts" import { Injectable } from '@nestjs/common'; import { ID, RequestContext, TransactionalConnection } from '@vendure/core'; import { IsNull } from 'typeorm'; import { Item } from '../entities/item.entity'; @Injectable() export class ItemService { constructor(private connection: TransactionalConnection) {} findById(ctx: RequestContext, itemId: ID): Promise<Item | null> { return this.connection.getRepository(ctx, Item).findOne({ where: { id: itemId }, }); } findByName(ctx: RequestContext, name: string): Promise<Item | null> { return this.connection.getRepository(ctx, Item).findOne({ where: { // Multiple where clauses can be specified, // which are joined with AND name, deletedAt: IsNull(), }, }); } findWithRelations() { return this.connection.getRepository(ctx, Item).findOne({ where: { name }, relations: { // Join the `item.customer` relation customer: true, product: { // Here we are joining a nested relation `item.product.featuredAsset` featuredAsset: true, }, }, }); } findMany(ctx: RequestContext): Promise<Item[]> { return this.connection.getRepository(ctx, Item).find({ // Pagination skip: 0, take: 10, // Sorting order: { name: 'ASC', }, }); } } ``` :::info Further examples can be found in the [TypeORM Find Options documentation](https://typeorm.io/find-options). ::: ### The QueryBuilder API When the Find API is not sufficient, the QueryBuilder API can be used to construct more complex queries. For instance, if you want to have a more complex `WHERE` clause than what can be achieved with the Find API, or if you want to perform sub-queries, then the QueryBuilder API is the way to go. Here are some examples of using the QueryBuilder API: ```ts title="src/services/item.service.ts" import { Injectable } from '@nestjs/common'; import { ID, RequestContext, TransactionalConnection } from '@vendure/core'; import { Brackets, IsNull } from 'typeorm'; import { Item } from '../entities/item.entity'; @Injectable() export class ItemService { constructor(private connection: TransactionalConnection) {} findById(ctx: RequestContext, itemId: ID): Promise<Item | null> { // This is simple enough that you should prefer the Find API, // but here is how it would be done with the QueryBuilder API: return this.connection.getRepository(ctx, Item).createQueryBuilder('item') .where('item.id = :id', { id: itemId }) .getOne(); } findManyWithSubquery(ctx: RequestContext, name: string) { // Here's a more complex query that would not be possible using the Find API: return this.connection.getRepository(ctx, Item).createQueryBuilder('item') .where('item.name = :name', { name }) .andWhere( new Brackets(qb1 => { qb1.where('item.state = :state1', { state1: 'PENDING' }) .orWhere('item.state = :state2', { state2: 'RETRYING' }); }), ) .orderBy('item.createdAt', 'ASC') .getMany(); } } ``` :::info Further examples can be found in the [TypeORM QueryBuilder documentation](https://typeorm.io/select-query-builder). ::: ### Working with relations One limitation of TypeORM's typings is that we have no way of knowing at build-time whether a particular relation will be joined at runtime. For instance, the following code will build without issues, but will result in a runtime error: ```ts const product = await this.connection.getRepository(ctx, Product).findOne({ where: { id: productId }, }); if (product) { // highlight-start console.log(product.featuredAsset.preview); // ^ Error: Cannot read property 'preview' of undefined // highlight-end } ``` This is because the `featuredAsset` relation is not joined by default. The simple fix for the above example is to use the `relations` option: ```ts const product = await this.connection.getRepository(ctx, Product).findOne({ where: { id: productId }, // highlight-next-line relations: { featuredAsset: true }, }); ``` or in the case of the QueryBuilder API, we can use the `leftJoinAndSelect()` method: ```ts const product = await this.connection.getRepository(ctx, Product).createQueryBuilder('product') // highlight-next-line .leftJoinAndSelect('product.featuredAsset', 'featuredAsset') .where('product.id = :id', { id: productId }) .getOne(); ``` ### Using the EntityHydrator But what about when we do not control the code which fetches the entity from the database? For instance, we might be implementing a function which gets an entity passed to it by Vendure. In this case, we can use the [`EntityHydrator`](/reference/typescript-api/data-access/entity-hydrator/) to ensure that a given relation is "hydrated" (i.e. joined) before we use it: ```ts import { EntityHydrator, ShippingCalculator } from '@vendure/core'; let entityHydrator: EntityHydrator; const myShippingCalculator = new ShippingCalculator({ // ... rest of config omitted for brevity init(injector) { entityHydrator = injector.get(EntityHydrator); }, calculate: (ctx, order, args) => { // highlight-start // ensure that the customer and customer.groups relations are joined await entityHydrator.hydrate(ctx, order, { relations: ['customer.groups' ]}); // highlight-end if (order.customer?.groups?.some(g => g.name === 'VIP')) { // ... do something special for VIP customers } else { // ... do something else } }, }); ``` ### Joining relations in built-in service methods Many of the core services allow an optional `relations` argument in their `findOne()` and `findMany()` and related methods. This allows you to specify which relations should be joined when the query is executed. For instance, in the [`ProductService`](/reference/typescript-api/services/product-service) there is a `findOne()` method which allows you to specify which relations should be joined: ```ts const productWithAssets = await this.productService .findOne(ctx, productId, ['featuredAsset', 'assets']); ```
--- title: 'Worker & Job Queue' sidebar_position: 5 --- The Vendure Worker is a Node.js process responsible for running computationally intensive or otherwise long-running tasks in the background. For example, updating a search index or sending emails. Running such tasks in the background allows the server to stay responsive, since a response can be returned immediately without waiting for the slower tasks to complete. Put another way, the Worker executes **jobs** which have been placed in the **job queue**. ![Worker & Job Queue](./worker-job-queue.webp) ## The worker The worker is started by calling the [`bootstrapWorker()`](/reference/typescript-api/worker/bootstrap-worker/) function with the same configuration as is passed to the main server `bootstrap()`. In a standard Vendure installation, this is found in the `index-worker.ts` file: ```ts title="src/index-worker.ts" import { bootstrapWorker } from '@vendure/core'; import { config } from './vendure-config'; bootstrapWorker(config) .then(worker => worker.startJobQueue()) .catch(err => { console.log(err); }); ``` ### Underlying architecture The Worker is a NestJS standalone application. This means it is almost identical to the main server app, but does not have any network layer listening for requests. The server communicates with the worker via a β€œjob queue” architecture. The exact implementation of the job queue is dependent on the configured [`JobQueueStrategy`](/reference/typescript-api/job-queue/job-queue-strategy/), but by default the worker polls the database for new jobs. ### Multiple workers It is possible to run multiple workers in parallel to better handle heavy loads. Using the [`JobQueueOptions.activeQueues`](/reference/typescript-api/job-queue/job-queue-options#activequeues) configuration, it is even possible to have particular workers dedicated to one or more specific types of jobs. For example, if your application does video transcoding, you might want to set up a dedicated worker just for that task: ```ts title="src/transcoder-worker.ts" import { bootstrapWorker, mergeConfig } from '@vendure/core'; import { config } from './vendure-config'; const transcoderConfig = mergeConfig(config, { jobQueueOptions: { activeQueues: ['transcode-video'], } }); bootstrapWorker(transcoderConfig) .then(worker => worker.startJobQueue()) .catch(err => { console.log(err); }); ``` ### Running jobs on the main process It is possible to run jobs from the Job Queue on the main server. This is mainly used for testing and automated tasks, and is not advised for production use, since it negates the benefits of running long tasks off of the main process. To do so, you need to manually start the JobQueueService: ```ts title="src/index.ts" import { bootstrap, JobQueueService } from '@vendure/core'; import { config } from './vendure-config'; bootstrap(config) .then(app => app.get(JobQueueService).start()) .catch(err => { console.log(err); process.exit(1); }); ``` ### ProcessContext Sometimes your code may need to be aware of whether it is being run as part of a server or worker process. In this case you can inject the [`ProcessContext`](/reference/typescript-api/common/process-context/) provider and query it like this: ```ts title="src/plugins/my-plugin/services/my.service.ts" import { Injectable, OnApplicationBootstrap } from '@nestjs/common'; import { ProcessContext } from '@vendure/core'; @Injectable() export class MyService implements OnApplicationBootstrap { constructor(private processContext: ProcessContext) {} onApplicationBootstrap() { if (this.processContext.isServer) { // code which will only execute when running in // the server process } } } ``` ## The job queue Vendure uses a [job queue](https://en.wikipedia.org/wiki/Job_queue) to handle the processing of certain tasks which are typically too slow to run in the normal request-response cycle. A normal request-response looks like this: ![Regular request response](./Vendure_docs-job-queue.webp) In the normal request-response, all intermediate tasks (looking up data in the database, performing business logic etc.) occur before the response can be returned. For most operations this is fine, since those intermediate tasks are very fast. Some operations however will need to perform much longer-running tasks. For example, updating the search index on thousands of products could take up to a minute or more. In this case, we certainly don’t want to delay the response until that processing has completed. That’s where a job queue comes in: ![Request response with job queue](./Vendure_docs-job-queue-2.webp) ### What does Vendure use the job queue for? By default, Vendure uses the job queue for the following tasks: - Re-building the search index - Updating the search index when changes are made to Products, ProductVariants, Assets etc. - Updating the contents of Collections - Sending transactional emails ### How does the Job Queue work? This diagram illustrates the job queue mechanism: ![Job queue sequence](./Vendure_docs-job-queue-3.webp) The server adds jobs to the queue. The worker then picks up these jobs from the queue and processes them in sequence, one by one (it is possible to increase job queue throughput by running multiple workers or by increasing the concurrency of a single worker). ### JobQueueStrategy The actual queue part is defined by the configured [`JobQueueStrategy`](/reference/typescript-api/job-queue/job-queue-strategy/). If no strategy is defined, Vendure uses an [in-memory store](/reference/typescript-api/job-queue/in-memory-job-queue-strategy/) of the contents of each queue. While this has the advantage of requiring no external dependencies, it is not suitable for production because when the server is stopped, the entire queue will be lost and any pending jobs will never be processed. Moreover, it cannot be used when running the worker as a separate process. A better alternative is to use the [DefaultJobQueuePlugin](/reference/typescript-api/job-queue/default-job-queue-plugin/) (which will be used in a standard `@vendure/create` installation), which configures Vendure to use the [SqlJobQueueStrategy](/reference/typescript-api/job-queue/sql-job-queue-strategy). This strategy uses the database as a queue, and means that even if the Vendure server stops, pending jobs will be persisted and upon re-start, they will be processed. It is also possible to implement your own JobQueueStrategy to take advantage of other technologies. Examples include RabbitMQ, Google Cloud Pub Sub & Amazon SQS. It may make sense to implement a custom strategy based on one of these if the default database-based approach does not meet your performance requirements. ### Job Queue Performance It is common for larger Vendure projects to define multiple custom job queues, When using the [DefaultJobQueuePlugin](/reference/typescript-api/job-queue/default-job-queue-plugin/) with many queues, performance may be impacted. This is because the `SqlJobQueueStrategy` uses polling to check for new jobs in the database. Each queue will (by default) query the database every 200ms. So if there are 10 queues, this will result in a constant 50 queries/second. In this case it is recommended to try the [BullMQJobQueuePlugin](/reference/core-plugins/job-queue-plugin/bull-mqjob-queue-plugin/), which uses an efficient push-based strategy built on Redis. ## Using Job Queues in a plugin If your plugin involves long-running tasks, you can also make use of the job queue. :::info A real example of this can be seen in the [EmailPlugin source](https://github.com/vendure-ecommerce/vendure/blob/master/packages/email-plugin/src/plugin.ts) ::: Let's say you are building a plugin which allows a video URL to be specified, and then that video gets transcoded into a format suitable for streaming on the storefront. This is a long-running task which should not block the main thread, so we will use the job queue to run the task on the worker. First we'll add a new mutation to the Admin API schema: ```ts title="src/plugins/product-video/api/api-extensions.ts" import gql from 'graphql-tag'; export const adminApiExtensions = gql` extend type Mutation { addVideoToProduct(productId: ID! videoUrl: String!): Job! } `; ``` The resolver looks like this: ```ts title="src/plugins/product-video/api/product-video.resolver.ts" import { Args, Mutation, Resolver } from '@nestjs/graphql'; import { Allow, Ctx, RequestContext, Permission, RequestContext } from '@vendure/core' import { ProductVideoService } from '../services/product-video.service'; @Resolver() export class ProductVideoResolver { constructor(private productVideoService: ProductVideoService) {} @Mutation() @Allow(Permission.UpdateProduct) addVideoToProduct(@Ctx() ctx: RequestContext, @Args() args: { productId: ID; videoUrl: string; }) { return this.productVideoService.transcodeForProduct( args.productId, args.videoUrl, ); } } ``` The resolver just defines how to handle the new `addVideoToProduct` mutation, delegating the actual work to the `ProductVideoService`. ### Creating a job queue :::cli Use `npx vendure add` to easily add a job queue to a service. ::: The [`JobQueueService`](/reference/typescript-api/job-queue/job-queue-service/) creates and manages job queues. The queue is created when the application starts up (see [NestJS lifecycle events](https://docs.nestjs.com/fundamentals/lifecycle-events)), and then we can use the `add()` method to add jobs to the queue. ```ts title="src/plugins/product-video/services/product-video.service.ts" import { Injectable, OnModuleInit } from '@nestjs/common'; import { JobQueue, JobQueueService, ID, Product, TransactionalConnection } from '@vendure/core'; import { transcode } from 'third-party-video-sdk'; @Injectable() class ProductVideoService implements OnModuleInit { private jobQueue: JobQueue<{ productId: ID; videoUrl: string; }>; constructor(private jobQueueService: JobQueueService, private connection: TransactionalConnection) { } async onModuleInit() { this.jobQueue = await this.jobQueueService.createQueue({ name: 'transcode-video', process: async job => { // Inside the `process` function we define how each job // in the queue will be processed. // In this case we call out to some imaginary 3rd-party video // transcoding API, which performs the work and then // returns a new URL of the transcoded video, which we can then // associate with the Product via the customFields. const result = await transcode(job.data.videoUrl); await this.connection.getRepository(Product).save({ id: job.data.productId, customFields: { videoUrl: result.url, }, }); // The value returned from the `process` function is stored as the "result" // field of the job (for those JobQueueStrategies that support recording of results). // // Any error thrown from this function will cause the job to fail. return result; }, }); } transcodeForProduct(productId: ID, videoUrl: string) { // Add a new job to the queue and immediately return the // job itself. return this.jobQueue.add({productId, videoUrl}, {retries: 2}); } } ``` Notice the generic type parameter of the `JobQueue`: ```ts JobQueue<{ productId: ID; videoUrl: string; }> ``` This means that when we call `jobQueue.add()` we must pass in an object of this type. This data will then be available in the `process` function as the `job.data` property. :::note The data passed to `jobQueue.add()` must be JSON-serializable, because it gets serialized into a string when stored in the job queue. Therefore you should avoid passing in complex objects such as `Date` instances, `Buffer`s, etc. ::: The `ProductVideoService` is in charge of setting up the JobQueue and adding jobs to that queue. Calling ```ts productVideoService.transcodeForProduct(id, url); ``` will add a transcoding job to the queue. :::tip Plugin code typically gets executed on both the server _and_ the worker. Therefore, you sometimes need to explicitly check what context you are in. This can be done with the [ProcessContext](/reference/typescript-api/common/process-context/) provider. ::: Finally, the `ProductVideoPlugin` brings it all together, extending the GraphQL API, defining the required CustomField to store the transcoded video URL, and registering our service and resolver. The [PluginCommonModule](/reference/typescript-api/plugin/plugin-common-module/) is imported as it exports the `JobQueueService`. ```ts title="src/plugins/product-video/product-video.plugin.ts" import gql from 'graphql-tag'; import { PluginCommonModule, VendurePlugin } from '@vendure/core'; import { ProductVideoService } from './services/product-video.service'; import { ProductVideoResolver } from './api/product-video.resolver'; import { adminApiExtensions } from './api/api-extensions'; @VendurePlugin({ imports: [PluginCommonModule], providers: [ProductVideoService], adminApiExtensions: { schema: adminApiExtensions, resolvers: [ProductVideoResolver] }, configuration: config => { config.customFields.Product.push({ name: 'videoUrl', type: 'string', }); return config; } }) export class ProductVideoPlugin {} ``` ### Passing the RequestContext It is common to need to pass the [RequestContext object](/reference/typescript-api/request/request-context) to the `process` function of a job, since `ctx` is required by many Vendure service methods that you may be using inside your `process` function. However, the `RequestContext` object itself is not serializable, so it cannot be passed directly to the `JobQueue.add()` method. Instead, you can serialize the `RequestContext` using the [`RequestContext.serialize()` method](/reference/typescript-api/request/request-context/#serialize), and then deserialize it in the `process` function using the static `deserialize` method: ```ts import { Injectable, OnModuleInit } from '@nestjs/common'; import { JobQueue, JobQueueService, Product, TransactionalConnection, SerializedRequestContext, RequestContext } from '@vendure/core'; @Injectable() class ProductExportService implements OnModuleInit { // highlight-next-line private jobQueue: JobQueue<{ ctx: SerializedRequestContext; }>; constructor(private jobQueueService: JobQueueService, private connection: TransactionalConnection) { } async onModuleInit() { this.jobQueue = await this.jobQueueService.createQueue({ name: 'export-products', process: async job => { // highlight-next-line const ctx = RequestContext.deserialize(job.data.ctx); const allProducts = await this.connection.getRepository(ctx, Product).find(); // ... logic to export the product omitted for brevity }, }); } exportAllProducts(ctx: RequestContext) { // highlight-next-line return this.jobQueue.add({ ctx: RequestContext.serialize(ctx) }); } } ``` ### Handling job cancellation It is possible for an administrator to cancel a running job. Doing so will cause the configured job queue strategy to mark the job as cancelled, but on its own this will not stop the job from running. This is because the job queue itself has no direct control over the `process` function once it has been started. It is up to the `process` function to check for cancellation and stop processing if the job has been cancelled. This can be done by checking the `job.state` property, and if the job is cancelled, the `process` function can throw an error to indicate that the job was interrupted by early cancellation: ```ts import { Injectable, OnModuleInit } from '@nestjs/common'; import { JobQueue, JobQueueService, Product, TransactionalConnection, SerializedRequestContext, RequestContext, Job, JobState } from '@vendure/core'; import { IsNull } from 'typeorm'; @Injectable() class ProductExportService implements OnModuleInit { private jobQueue: JobQueue<{ ctx: SerializedRequestContext; }>; constructor(private jobQueueService: JobQueueService, private connection: TransactionalConnection) { } async onModuleInit() { this.jobQueue = await this.jobQueueService.createQueue({ name: 'export-products', process: async job => { const ctx = RequestContext.deserialize(job.data.ctx); const allProducts = await this.connection.getRepository(ctx, Product).find({ where: { deletedAt: IsNull() } }); let successfulExportCount = 0; for (const product of allProducts) { // highlight-start if (job.state === JobState.CANCELLED) { // If the job has been cancelled, stop processing // to prevent unnecessary work. throw new Error('Job was cancelled'); } // highlight-end // ... logic to export the product omitted for brevity successfulExportCount++; } return { successfulExportCount }; }, }); } exportAllProducts(ctx: RequestContext) { return this.jobQueue.add({ ctx: RequestContext.serialize(ctx) }); } } ``` ### Subscribing to job updates When creating a new job via `JobQueue.add()`, it is possible to subscribe to updates to that Job (progress and status changes). This allows you, for example, to create resolvers which are able to return the results of a given Job. In the video transcoding example above, we could modify the `transcodeForProduct()` call to look like this: ```ts title="src/plugins/product-video/services/product-video.service.ts" import { Injectable, OnModuleInit } from '@nestjs/common'; import { of } from 'rxjs'; import { map, catchError } from 'rxjs/operators'; import { ID, Product, TransactionalConnection } from '@vendure/core'; @Injectable() class ProductVideoService implements OnModuleInit { // ... omitted (see above) transcodeForProduct(productId: ID, videoUrl: string) { const job = await this.jobQueue.add({productId, videoUrl}, {retries: 2}); return job.updates().pipe( map(update => { // The returned Observable will emit a value for every update to the job // such as when the `progress` or `status` value changes. Logger.info(`Job ${update.id}: progress: ${update.progress}`); if (update.state === JobState.COMPLETED) { Logger.info(`COMPLETED ${update.id}: ${update.result}`); } return update.result; }), catchError(err => of(err.message)), ); } } ``` If you prefer to work with Promises rather than Rxjs Observables, you can also convert the updates to a promise: ```ts const job = await this.jobQueue.add({ productId, videoUrl }, { retries: 2 }); return job.updates().toPromise() .then(/* ... */) .catch(/* ... */); ```
--- title: Introducing GraphQL --- import Playground from '@site/src/components/Playground'; import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; :::info Vendure uses [GraphQL](https://graphql.org/) as its API layer. This is an introduction to GraphQL for those who are new to it. If you are already familiar with GraphQL, you may choose to skip this section. ::: ## What is GraphQL? From [graphql.org](https://graphql.org/): > GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. To put it simply: GraphQL allows you to fetch data from an API via _queries_, and to update data via _mutations_. Here's a GraphQL query which fetches the product with the slug "football": <Playground api="shop" document={` query { product(slug: "football") { id name slug } } `} /> ## GraphQL vs REST If you are familiar with REST-style APIs, you may be wondering how GraphQL differs. Here are the key ways in which GraphQL differs from REST: - GraphQL uses **a single endpoint**, whereas REST uses a different endpoint for each resource. - GraphQL allows you to **specify exactly which fields** you want to fetch, whereas REST APIs usually return all fields by default. - GraphQL allows you to fetch data from **multiple resources** in a single request (e.g. "fetch a customer including their last 5 orders"), whereas REST APIs usually require you to make multiple requests. - GraphQL APIs are always defined by a **statically typed schema**, whereas REST APIs do not have this guarantee. ## Why GraphQL? Both GraphQL and REST are valid approaches to building an API. These are some of the reasons we chose GraphQL when building Vendure: - **No over-fetching**: With REST, you often end up fetching more data than you need. For example, if you want to fetch a list of products, you might end up fetching the product name, description, price, and other fields. With GraphQL, you can specify exactly which fields you want to fetch, so you only fetch the data you need. This can result in a significant reduction in the amount of data transferred over the network. - **Many resources in a single request**: Very often, a single page in a web app will need to fetch data from multiple resources. For example, a product detail page might need to fetch the product, the product's variants, the product's collections, the product's reviews, and the product's images. With REST, this would require multiple requests. With GraphQL, you can fetch all of this data in a single request. - **Static typing**: GraphQL APIs are always defined by a statically typed schema. This means that you can be sure that the data you receive from the API will always be in the format you expect. - **Developer tooling**: The schema definition allows for powerful developer tooling. For example, the GraphQL Playground above with auto-complete and full documentation is generated automatically from the schema definition. You can also get auto-complete and type-checking directly in your IDE. - **Code generation**: TypeScript types can be generated automatically from the schema definition. This means that you can be sure that your frontend code is always in sync with the API. This end-to-end type safety is extremely valuable, especially when working on large projects or with teams. See the [GraphQL Code Generation guide](/guides/storefront/codegen/) - **Extensible**: Vendure is designed with extensibility in mind, and GraphQL is a perfect fit. You can extend the GraphQL API with your own custom queries, mutations, and types. You can also extend the built-in types with your own custom fields, or supply you own custom logic to resolve existing fields. See the [Extend the GraphQL API guide](/guides/developer-guide/extend-graphql-api/) ## GraphQL Terminology Let's clear up some of the terminology used in GraphQL. ### Types & Fields GraphQL has a type system which works in a similar way to other statically typed languages like TypeScript. Here is an example of a GraphQL type: ```graphql type Customer { id: ID! name: String! email: String! } ``` The `Customer` is an **object type**, and it has three **fields**: `id`, `name`, and `email`. Each field has a **type** (e.g. `ID!` or `String!`), which can refer to either a **scalar type** (a "primitive" type which does not have any fields, but represents a single value) or another object type. GraphQL has a number of built-in scalar types, including `ID`, `String`, `Int`, `Float`, `Boolean`. Vendure further defines a few custom scalar types: `DateTime`, `JSON`, `Upload` & `Money`. It is also possible to define your own custom scalar types if required. The `!` symbol after the type name indicates that the field is **required** (it cannot be `null`). If a field does not have the `!` symbol, it is **optional** (it can be `null`). Here's another example of a couple of types: ```graphql type Order { id: ID! orderPlacedAt: DateTime isActive: Boolean! customer: Customer! lines: [OrderLine!]! } type OrderLine { id: ID! productId: ID! quantity: Int! } ``` Here the `Order` type has a field called `customer` which is of type `Customer`. The `Order` type also has a field called `lines` which is a list (an array) of `OrderLine` objects. In GraphQL, lists are denoted by square brackets (`[]`). The `!` symbol inside the square brackets indicates that the list cannot contain `null` values. :::note The types given here are not the actual types used in the Vendure GraphQL schema, but are used here for illustrative purposes. ::: ### Query & Mutation types There are two special types in GraphQL: `Query` and `Mutation`. These are the entry points into the API. The `Query` type is used for fetching data, and the `Mutation` type is used for updating data. Here is an example of a query type: ```graphql type Query { customers: [Customer!]! } ``` This defines a `customers` field on the `Query` type. This field returns a list of `Customer` objects. Here's a mutation type: ```graphql type Mutation { updateCustomerEmail(customerId: ID!, email: String!): Customer! } ``` This defines a `updateCustomerEmail` field on the `Mutation` type. This field takes two arguments, `customerId` and `email`, and returns a `Customer` object. It would be used to update the name of the specified customer. ### Input types Input types are used to pass complex (non-scalar) data to queries or mutations. For example, the `updateCustomerEmail` mutation above could be re-written to use an input type: ```graphql type Mutation { updateCustomerEmail(input: UpdateCustomerEmailInput!): Customer! } input UpdateCustomerEmailInput { customerId: ID! email: String! } ``` Input types look just like object types, but with the `input` keyword rather than `type`. ### Schema The schema is the complete definition of the GraphQL API. It defines the types, fields, queries and mutations which are available. In a GraphQL API like Vendure, you can only query data according to the fields which are defined in the schema. Here is a complete, minimal schema: ```graphql schema { query: Query mutation: Mutation } type Query { customers: [Customer!]! } type Mutation { updateCustomerEmail(input: UpdateCustomerEmailInput!): Customer! } input UpdateCustomerEmailInput { customerId: ID! email: String! } type Customer { id: ID! name: String! email: String! } ``` The schema above tells you _everything_ that you can do with the API. You can fetch a list of customers, and you can update a customer's name. :::info The schema is one of the key benefits of GraphQL. It allows advanced tooling to be built around the API, such as autocomplete in IDEs, and automatic code generation. It also ensures that only valid queries can be made against the API. ::: ### Operations An **operation** is the general name for a GraphQL query or mutation. When you are building your client application, you will be defining operations which you can then send to the server. Here's an example of a query operation based on the schema above: <Tabs> <TabItem value="Query" label="Query" default> ```graphql query { customers { id name email } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "customers": [ { "id": "1", "name": "John Smith", "email": "j.smith@email.com" }, { "id": "2", "name": "Jane Doe", "email": "j.doe@email.com" } ] } } ``` </TabItem> </Tabs> Here's an example mutation operation to update the first customer's email: <Tabs> <TabItem value="Query" label="Query" default> ```graphql mutation { updateCustomerEmail(input: { customerId: "1", email: "john.smith@email.com" }) { id name email } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "updateCustomerEmail": { "id": "1", "name": "John Smith", // highlight-next-line "email": "john.smith@email.com" } } } ``` </TabItem> </Tabs> Operations can also have a **name**, which, while not required, is recommended for real applications as it makes debugging easier (similar to having named vs anonymous functions in JavaScript), and also allows you to take advantage of code generation tools. Here's the above query with a name: ```graphql // highlight-next-line query GetCustomers { customers { id name email } } ``` ### Variables Operations can also have **variables**. Variables are used to pass input values into the operation. In the example `updateCustomerEmail` mutation operation above, we are passing an input object specifying the `customerId` and `email`. However, in that example they are hard-coded into the operation. In a real application, you would want to pass those values in dynamically. Here's how we can re-write the above mutation operation to use variables: <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql // highlight-next-line mutation UpdateCustomerEmail($input: UpdateCustomerEmailInput!) { // highlight-next-line updateCustomerEmail(input: $input) { id name email } } ``` </TabItem> <TabItem value="Variables" label="Variables" > ```json { "input": { "customerId": "1", "email": "john.smith@email.com" } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "updateCustomerEmail": { "id": "1", "name": "John Smith", // highlight-next-line "email": "john.smith@email.com" } } } ``` </TabItem> </Tabs> ### Fragments A **fragment** is a reusable set of fields on an object type. Let's define a fragment for the `Customer` type that we can re-use in both the query and the mutation: ```graphql fragment CustomerFields on Customer { id name email } ``` Now we can re-write the query and mutation operations to use the fragment: ```graphql query GetCustomers{ customers { ...CustomerFields } } ``` ```graphql mutation UpdateCustomerEmail($input: UpdateCustomerEmailInput!) { updateCustomerEmail(input: $input) { ...CustomerFields } } ``` You can think of the syntax as similar to the JavaScript object spread operator (`...`). ### Union types A **union type** is a special type which can be one of a number of other types. Let's say for example that when attempting to update a customer's email address, we want to return an error type if the email address is already in use. We can update our schema to model this as a union type: ```graphql type Mutation { updateCustomerEmail(input: UpdateCustomerEmailInput!): UpdateCustomerEmailResult! } // highlight-next-line union UpdateCustomerEmailResult = Customer | EmailAddressInUseError type EmailAddressInUseError { errorCode: String! message: String! } ``` :::info In Vendure, we use this pattern for almost all mutations. You can read more about it in the [Error Handling guide](/guides/developer-guide/error-handling/). ::: Now, when we perform this mutation, we need alter the way we select the fields in the response, since the response could be one of two types: <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation UpdateCustomerEmail($input: UpdateCustomerEmailInput!) { updateCustomerEmail(input: $input) { __typename ... on Customer { id name email } ... on EmailAddressInUseError { errorCode message } } } ``` </TabItem> <TabItem value="Success case" label="Success case" > ```json { "data": { "updateCustomerEmail": { "__typename": "Customer", "id": "1", "name": "John Smith", "email": "john.smith@email.com" } } } ``` </TabItem> <TabItem value="Error case" label="Error case" > ```json { "data": { "updateCustomerEmail": { "__typename": "EmailAddressInUseError", "errorCode": "EMAIL_ADDRESS_IN_USE", "message": "The email address is already in use" } } } ``` </TabItem> </Tabs> The `__typename` field is a special field available on all types which returns the name of the type. This is useful for determining which type was returned in the response in your client application. :::tip The above operation could also be written to use the `CustomerFields` fragment we defined earlier: ```graphql mutation UpdateCustomerEmail($input: UpdateCustomerEmailInput!) { updateCustomerEmail(input: $input) { // highlight-next-line ...CustomerFields ... on EmailAddressInUseError { errorCode message } } } ``` ::: ### Resolvers The schema defines the _shape_ of the data, but it does not define _how_ the data is fetched. This is the job of the resolvers. A resolver is a function which is responsible for fetching the data for a particular field. For example, the `customers` field on the `Query` type would be resolved by a function which fetches the list of customers from the database. To get started with Vendure's APIs, you don't need to know much about resolvers beyond this basic understanding. However, later on you may want to write your own custom resolvers to extend the API. This is covered in the [Extending the GraphQL API guide](/guides/developer-guide/extend-graphql-api/). ## Querying data Now that we have a basic understanding of the GraphQL type system, let's look at how we can use it to query data from the Vendure API. In REST terms, a GraphQL query is equivalent to a GET request. It is used to fetch data from the API. Queries should not change any data on the server. This is a GraphQL Playground running on a real Vendure server. You can run the query by clicking the "play" button in the middle of the two panes. <Playground api="shop" document={` query { product(slug: "football") { id name slug } } `} /> Let's get familiar with the schema: 1. Hover your mouse over any field to see its type, and in the case of the `product` field itself, you'll see documentation about what it does. 2. Add a new line after `slug` and press `Ctrl / ⌘` + `space` to see the available fields. At the bottom of the field list, you'll see the type of that field. 3. Try adding the `description` field and press play. You should see the product's description in the response. 4. Try adding `variants` to the field list. You'll see a red warning in the left edge, and hovering over `variants` will inform you that it must have a selection of subfields. This is because the `variants` field refers to an **object type**, so we must select which fields of that object type we want to fetch. For example: ```graphql query { product(slug: "football") { id name slug variants { // highlight-start # Sub-fields are required for object types sku priceWithTax // highlight-end } } } ``` ## IDE plugins Plugins are available for most popular IDEs & editors which provide auto-complete and type-checking for GraphQL operations as you write them. This is a huge productivity boost, and is **highly recommended**. - [GraphQL extension for VS Code](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) - [GraphQL plugin for IntelliJ](https://plugins.jetbrains.com/plugin/8097-graphql) (including WebStorm) ## Code generation Code generation means the automatic generation of TypeScript types based on your GraphQL schema and your GraphQL operations. This is a very powerful feature that allows you to write your code in a type-safe manner, without you needing to manually write any types for your API calls. For more information see the [GraphQL Code Generation guide](/guides/storefront/codegen). ## Further reading This is just a very brief overview, intended to introduce you to the main concepts you'll need to build with Vendure. There are many more language features and best practices to learn about which we did not cover here. Here are some resources you can use to gain a deeper understanding of GraphQL: - The official [Introduction to GraphQL on graphql.org](https://graphql.org/learn/) is comprehensive and easy to follow. - For a really fundamental understanding, see the [GraphQL language spec](https://spec.graphql.org/). - If you like to learn from videos, the [graphql.wtf](https://graphql.wtf/) series is a great resource.
--- title: "Try the API" --- import Playground from '@site/src/components/Playground'; Once you have successfully installed Vendure locally following the [installation guide](/guides/getting-started/installation), it's time to try out the API! :::note This guide assumes you chose to populate sample data when installing Vendure. You can also follow along with these example using the public demo playground at [demo.vendure.io/shop-api](https://demo.vendure.io/shop-api) ::: ## GraphQL Playground The Vendure server comes with a GraphQL Playground which allows you to explore the API and run queries and mutations. It is a great way to explore the API and to get a feel for how it works. In this guide, we'll be using the GraphQL Playground to run queries and mutations against the Shop and Admin APIs. At each step, you paste the query or mutation into the left-hand pane of the Playground, and then click the "Play" button to run it. You'll then see the response in the right-hand pane. ![Graphql playground](./playground.webp) :::note Before we start using the GraphQL Playground, we need to alter a setting to make sure it is handling session cookies correctly. In the "settings" panel, we need to change the `request.credentials` setting from `omit` to `include`: ![Graphql playground setup](./playground-setup.webp) ::: ## Shop API The Shop API is the public-facing API which is used by the storefront application. Open the GraphQL Playground at [http://localhost:3000/shop-api](http://localhost:3000/shop-api). ### Fetch a list of products Let's start with a **query**. Queries are used to fetch data. We will make a query to get a list of products. <Playground api="shop" document={` query { products { totalItems items { id name } } } `} /> Note that the response only includes the properties we asked for in our query (id and name). This is one of the key benefits of GraphQL - the client can specify exactly which data it needs, and the server will only return that data! Let's add a few more properties to the query: <Playground api="shop" document={` query { products { totalItems items { id name slug description featuredAsset { id preview } } } } `} /> You should see that the response now includes the `slug`, `description` and `featuredAsset` properties. Note that the `featuredAsset` property is itself an object, and we can specify which properties of that object we want to include in the response. This is another benefit of GraphQL - you can "drill down" into the data and specify exactly which properties you want to include. Now let's add some arguments to the query. Some queries (and most mutations) can accept argument, which you put in parentheses after the query name. For example, let's fetch the first 5 products: <Playground api="shop" document={` query { products(options: { take: 5 }) { totalItems items { id name } } } `} /> On running this query, you should see just the first 5 results being returned. Let's add a more complex argument: this time we'll filter for only those products which contain the string "shoe" in the name: <Playground api="shop" document={` query { products(options: { filter: { name: { contains: "shoe" } } }) { totalItems items { id name } } } `} /> ### Add a product to an order Next, let's look at a **mutation**. Mutations are used to modify data on the server. Here's a mutation which adds a product to an order: <Playground api="shop" document={` mutation { addItemToOrder(productVariantId: 42, quantity: 1) { ...on Order { id code totalQuantity totalWithTax lines { productVariant { name } quantity linePriceWithTax } } ...on ErrorResult { errorCode message } } } `} /> This mutation adds a product variant with ID `42` to the order. The response will either be an `Order` object, or an `ErrorResult`. We use a special syntax called a **fragment** to specify which properties we want to include in the response. In this case, we are saying that if the response is an `Order`, we want to include the `id`, `code`, `totalQuantity`, `totalWithTax` etc., and if the response is an `ErrorResult`, we want to include the `errorCode` and `message`. Running this mutation a second time should show that the quantity of the product in the order has increased by 1. If not, then the session is not being persisted correctly (see the note earlier in this guide about the `request.credentials` setting). :::info For more information about `ErrorResult` and the handling of errors in Vendure, see the [Error Handling guide](/guides/developer-guide/error-handling). ::: ## Admin API The Admin API exposes all the functionality required to manage the store. It is used by the Admin UI, but can also be used by integrations and custom scripts. :::note The examples in this section are not interactive, due to security settings on our demo server, but you can paste them into your local GraphQL playground. ::: Open the GraphQL Playground at [http://localhost:3000/admin-api](http://localhost:3000/admin-api). ### Logging in Most Admin API operations are restricted to authenticated users. So first of all we'll need to log in. ```graphql title="Admin API" mutation { login(username: "superadmin", password: "superadmin") { ...on CurrentUser { id identifier } ...on ErrorResult { errorCode message } } } ``` ### Fetch a product The Admin API exposes a lot more information about products than you can get from the Shop API: ```graphql title="Admin API" query { product(id: 42) { // highlight-next-line enabled name variants { id name // highlight-next-line enabled prices { currencyCode price } // highlight-start stockLevels { stockLocationId stockOnHand stockAllocated } // highlight-end } } } ``` :::info GraphQL is statically typed and uses a **schema** containing information about all the available queries, mutations and types. In the GraphQL playground, you can explore the schema by clicking the "docs" tab on the right hand side. ![Graphql playground docs](./playground-docs.webp) :::
--- title: "Digital Products" --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Digital products include things like ebooks, online courses, and software. They are products that are delivered to the customer electronically, and do not require physical shipping. This guide will show you how you can add support for digital products to Vendure. ## Creating the plugin :::info The complete source of the following example plugin can be found here: [example-plugins/digital-products](https://github.com/vendure-ecommerce/vendure/tree/master/packages/dev-server/example-plugins/digital-products) ::: ### Define custom fields If some products are digital and some are physical, we can distinguish between them by adding a customField to the ProductVariant entity. ```ts title="src/plugins/digital-products/digital-products-plugin.ts" import { LanguageCode, PluginCommonModule, VendurePlugin } from '@vendure/core'; @VendurePlugin({ imports: [PluginCommonModule], configuration: config => { // highlight-start config.customFields.ProductVariant.push({ type: 'boolean', name: 'isDigital', defaultValue: false, label: [{ languageCode: LanguageCode.en, value: 'This product is digital' }], public: true, }); // highlight-end return config; }, }) export class DigitalProductsPlugin {} ``` We will also define a custom field on the `ShippingMethod` entity to indicate that this shipping method is only available for digital products: ```ts title="src/plugins/digital-products/digital-products-plugin.ts" import { LanguageCode, PluginCommonModule, VendurePlugin } from '@vendure/core'; @VendurePlugin({ imports: [PluginCommonModule], configuration: config => { // config.customFields.ProductVariant.push({ ... omitted // highlight-start config.customFields.ShippingMethod.push({ type: 'boolean', name: 'digitalFulfilmentOnly', defaultValue: false, label: [{ languageCode: LanguageCode.en, value: 'Digital fulfilment only' }], public: true, }); // highlight-end return config; }, }) ``` Lastly we will define a custom field on the `Fulfillment` entity where we can store download links for the digital products. If your own implementation you may wish to handle this part differently, e.g. storing download links on the `Order` entity or in a custom entity. ```ts title="src/plugins/digital-products/digital-products-plugin.ts" import { LanguageCode, PluginCommonModule, VendurePlugin } from '@vendure/core'; @VendurePlugin({ imports: [PluginCommonModule], configuration: config => { // config.customFields.ProductVariant.push({ ... omitted // config.customFields.ShippingMethod.push({ ... omitted // highlight-start config.customFields.Fulfillment.push({ type: 'string', name: 'downloadUrls', nullable: true, list: true, label: [{ languageCode: LanguageCode.en, value: 'Urls of any digital purchases' }], public: true, }); // highlight-end return config; }, }) ``` ### Create a custom FulfillmentHandler The `FulfillmentHandler` is responsible for creating the `Fulfillment` entities when an Order is fulfilled. We will create a custom handler which is responsible for performing the logic related to generating the digital download links. In your own implementation, this may look significantly different depending on your requirements. ```ts title="src/plugins/digital-products/config/digital-fulfillment-handler.ts" import { FulfillmentHandler, LanguageCode, OrderLine, TransactionalConnection } from '@vendure/core'; import { In } from 'typeorm'; let connection: TransactionalConnection; /** * @description * This is a fulfillment handler for digital products which generates a download url * for each digital product in the order. */ export const digitalFulfillmentHandler = new FulfillmentHandler({ code: 'digital-fulfillment', description: [ { languageCode: LanguageCode.en, value: 'Generates product keys for the digital download', }, ], args: {}, init: injector => { connection = injector.get(TransactionalConnection); }, createFulfillment: async (ctx, orders, lines) => { const digitalDownloadUrls: string[] = []; const orderLines = await connection.getRepository(ctx, OrderLine).find({ where: { id: In(lines.map(l => l.orderLineId)), }, relations: { productVariant: true, }, }); for (const orderLine of orderLines) { if (orderLine.productVariant.customFields.isDigital) { // This is a digital product, so generate a download url const downloadUrl = await generateDownloadUrl(orderLine); digitalDownloadUrls.push(downloadUrl); } } return { method: 'Digital Fulfillment', trackingCode: 'DIGITAL', customFields: { downloadUrls: digitalDownloadUrls, }, }; }, }); function generateDownloadUrl(orderLine: OrderLine) { // This is a dummy function that would generate a download url for the given OrderLine // by interfacing with some external system that manages access to the digital product. // In this example, we just generate a random string. const downloadUrl = `https://example.com/download?key=${Math.random().toString(36).substring(7)}`; return Promise.resolve(downloadUrl); } ``` ### Create a custom ShippingEligibilityChecker We want to ensure that the digital shipping method is only applicable to orders containing at least one digital product. We do this with a custom ShippingEligibilityChecker: ```ts title="src/plugins/digital-products/config/digital-shipping-eligibility-checker.ts" import { LanguageCode, ShippingEligibilityChecker } from '@vendure/core'; export const digitalShippingEligibilityChecker = new ShippingEligibilityChecker({ code: 'digital-shipping-eligibility-checker', description: [ { languageCode: LanguageCode.en, value: 'Allows only orders that contain at least 1 digital product', }, ], args: {}, check: (ctx, order, args) => { const digitalOrderLines = order.lines.filter(l => l.productVariant.customFields.isDigital); return digitalOrderLines.length > 0; }, }); ``` ### Create a custom ShippingLineAssignmentStrategy When adding shipping methods to the order, we want to ensure that digital products are correctly assigned to the digital shipping method, and physical products are not. ```ts title="src/plugins/digital-products/config/digital-shipping-line-assignment-strategy.ts" import { Order, OrderLine, RequestContext, ShippingLine, ShippingLineAssignmentStrategy, } from '@vendure/core'; /** * @description * This ShippingLineAssignmentStrategy ensures that digital products are assigned to a * ShippingLine which has the `isDigital` flag set to true. */ export class DigitalShippingLineAssignmentStrategy implements ShippingLineAssignmentStrategy { assignShippingLineToOrderLines( ctx: RequestContext, shippingLine: ShippingLine, order: Order, ): OrderLine[] | Promise<OrderLine[]> { if (shippingLine.shippingMethod.customFields.isDigital) { return order.lines.filter(l => l.productVariant.customFields.isDigital); } else { return order.lines.filter(l => !l.productVariant.customFields.isDigital); } } } ``` ### Define a custom OrderProcess In order to automatically fulfill any digital products as soon as the order completes, we can define a custom OrderProcess: ```ts title="src/plugins/digital-products/config/digital-order-process.ts" import { OrderProcess, OrderService } from '@vendure/core'; import { digitalFulfillmentHandler } from './digital-fulfillment-handler'; let orderService: OrderService; /** * @description * This OrderProcess ensures that when an Order transitions from ArrangingPayment to * PaymentAuthorized or PaymentSettled, then any digital products are automatically * fulfilled. */ export const digitalOrderProcess: OrderProcess<string> = { init(injector) { orderService = injector.get(OrderService); }, async onTransitionEnd(fromState, toState, data) { if ( fromState === 'ArrangingPayment' && (toState === 'PaymentAuthorized' || toState === 'PaymentSettled') ) { const digitalOrderLines = data.order.lines.filter(l => l.productVariant.customFields.isDigital); if (digitalOrderLines.length) { await orderService.createFulfillment(data.ctx, { lines: digitalOrderLines.map(l => ({ orderLineId: l.id, quantity: l.quantity })), handler: { code: digitalFulfillmentHandler.code, arguments: [] }, }); } } }, }; ``` ### Complete plugin & add to config The complete plugin can be found here: [example-plugins/digital-products](https://github.com/vendure-ecommerce/vendure/tree/master/packages/dev-server/example-plugins/digital-products) We can now add the plugin to the VendureConfig: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; import { DigitalProductsPlugin } from './plugins/digital-products/digital-products-plugin'; const config: VendureConfig = { // ... other config omitted plugins: [ // ... other plugins omitted // highlight-next-line DigitalProductsPlugin, ], }; ``` ## Create the ShippingMethod Once these parts have been defined and bundled up in a Vendure plugin, we can create a new ShippingMethod via the Admin UI, and make sure to check the "isDigital" custom field, and select the custom fulfillment handler and eligibility checker: ![Create ShippingMethod](./shipping-method.webp) ## Mark digital products We can now also set any digital product variants by checking the custom field: ![Digital product variant](./product-variant.webp) ## Storefront integration In the storefront, when the customer is checking out, we can use the `eligibleShippingMethods` query to determine which shipping methods are available to the customer. If the customer has any digital products in the order, the "digital-download" shipping method will be available: <Tabs> <TabItem value="Query" label="Query" default> ```graphql query { eligibleShippingMethods { id name price priceWithTax customFields { isDigital } } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "eligibleShippingMethods": [ // highlight-start { "id": "3", "name": "Digital Download", "price": 0, "priceWithTax": 0, "customFields": { "isDigital": true } }, // highlight-end { "id": "1", "name": "Standard Shipping", "price": 500, "priceWithTax": 500, "customFields": { "isDigital": false } }, { "id": "2", "name": "Express Shipping", "price": 1000, "priceWithTax": 1000, "customFields": { "isDigital": false } } ] } } ``` </TabItem> </Tabs> If the "digital download" shipping method is eligible, it should be set as a shipping method along with any other method required by any physical products in the order. <Tabs> <TabItem value="Query" label="Query" default> ```graphql mutation SetShippingMethod { setOrderShippingMethod( // highlight-next-line shippingMethodId: ["3", "1"] ) { ... on Order { id code total lines { id quantity linePriceWithTax productVariant { name sku customFields { isDigital } } } shippingLines { id shippingMethod { name } priceWithTax } } } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "setOrderShippingMethod": { "id": "11", "code": "C6H3UZ6WQ62LAPS8", "total": 5262, "lines": [ { "id": "16", "quantity": 1, "linePriceWithTax": 1458, "productVariant": { "name": "Jeff Buckley Grace mp3 download", "sku": "1231241241231", "customFields": { // highlight-next-line "isDigital": true } } }, { "id": "17", "quantity": 1, "linePriceWithTax": 4328, "productVariant": { "name": "Basketball", "sku": "WTB1418XB06", "customFields": { "isDigital": false } } } ], "shippingLines": [ // highlight-start { "id": "13", "shippingMethod": { "name": "Digital Download" }, "priceWithTax": 0 }, // highlight-end { "id": "14", "shippingMethod": { "name": "Standard Shipping" }, "priceWithTax": 500 } ] } } } ``` </TabItem> </Tabs>
--- title: "Paginated lists" --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Vendure's list queries follow a set pattern which allows for pagination, filtering & sorting. This guide will demonstrate how to implement your own paginated list queries. ## API definition Let's start with defining the GraphQL schema for our query. In this example, we'll image that we have defined a [custom entity](/guides/developer-guide/database-entity/) to represent a `ProductReview`. We want to be able to query a list of reviews in the Admin API. Here's how the schema definition would look: ```ts title="src/plugins/reviews/api/api-extensions.ts" import gql from 'graphql-tag'; export const adminApiExtensions = gql` type ProductReview implements Node { id: ID! createdAt: DateTime! updatedAt: DateTime! product: Product! productId: ID! text: String! rating: Float! } type ProductReviewList implements PaginatedList { items: [ProductReview!]! totalItems: Int! } # Generated at run-time by Vendure input ProductReviewListOptions extend type Query { productReviews(options: ProductReviewListOptions): ProductReviewList! } `; ``` Note that we need to follow these conventions: - The type must implement the `Node` interface, i.e. it must have an `id: ID!` field. - The list type must be named `<EntityName>List` and must implement the `PaginatedList` interface. - The list options input type must be named `<EntityName>ListOptions`. Given this schema, at runtime Vendure will automatically generate the `ProductReviewListOptions` input type, including all the filtering & sorting fields. This means that we don't need to define the input type ourselves. ## Resolver Next, we need to define the resolver for the query. ```ts title="src/plugins/reviews/api/admin.resolver.ts" import { Args, Query, Resolver } from '@nestjs/graphql'; import { Ctx, PaginatedList, RequestContext } from '@vendure/core'; import { ProductReview } from '../entities/product-review.entity'; import { ProductReviewService } from '../services/product-review.service'; @Resolver() export class ProductReviewAdminResolver { constructor(private productReviewService: ProductReviewService) {} @Query() async productReviews( @Ctx() ctx: RequestContext, @Args() args: any, ): Promise<PaginatedList<ProductReview>> { return this.productReviewService.findAll(ctx, args.options || undefined); } } ``` ## Service Finally, we need to implement the `findAll()` method on the `ProductReviewService`. Here we will use the [`ListQueryBuilder`](/reference/typescript-api/data-access/list-query-builder/) to build the list query. The `ListQueryBuilder` will take care of ```ts title="src/plugins/reviews/services/product-review.service.ts" import { Injectable } from '@nestjs/common'; import { InjectConnection } from '@nestjs/typeorm'; import { ListQueryBuilder, ListQueryOptions, PaginatedList, RequestContext } from '@vendure/core'; import { ProductReview } from '../entities/product-review.entity'; @Injectable() export class ProductReviewService { constructor( private listQueryBuilder: ListQueryBuilder, ) {} findAll(ctx: RequestContext, options?: ListQueryOptions<ProductReview>): Promise<PaginatedList<ProductReview>> { return this.listQueryBuilder .build(ProductReview, options, { relations: ['product'], ctx }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems })); } } ``` ## Usage Given the above parts of the plugin, we can now query the list of reviews in the Admin API: <Tabs> <TabItem value="Query" label="Query" default> ```graphql query { productReviews( options: { // highlight-start skip: 0 take: 10 sort: { createdAt: DESC } filter: { rating: { between: { start: 3, end: 5 } } } // highlight-end }) { totalItems items { id createdAt product { name } text rating } } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "productReviews": { "totalItems": 3, "items": [ { "id": "12", "createdAt": "2023-08-23T12:00:00Z", "product": { "name": "Smartphone X" }, "text": "The best phone I've ever had!", "rating": 5 }, { "id": "42", "createdAt": "2023-08-22T15:30:00Z", "product": { "name": "Laptop Y" }, "text": "Impressive performance and build quality.", "rating": 4 }, { "id": "33", "createdAt": "2023-08-21T09:45:00Z", "product": { "name": "Headphones Z" }, "text": "Decent sound quality but uncomfortable.", "rating": 3 } ] } } } ``` </TabItem> </Tabs> In the above example, we are querying the first 10 reviews, sorted by `createdAt` in descending order, and filtered to only include reviews with a rating between 3 and 5. ## Advanced filtering Vendure v2.2.0 introduced the ability to construct complex nested filters on any PaginatedList query. For example, we could filter the above query to only include reviews for products with a name starting with "Smartphone": <Tabs> <TabItem value="Query" label="Query" default> ```graphql query { productReviews( options: { skip: 0 take: 10 // highlight-start filter: { _and: [ { text: { startsWith: "phone" } }, { _or: [ { rating: { gte: 4 } }, { rating: { eq: 0 } } ] } ] } // highlight-end }) { totalItems items { id createdAt product { name } text rating } } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "productReviews": { "totalItems": 3, "items": [ { "id": "12", "createdAt": "2023-08-23T12:00:00Z", "product": { "name": "Smartphone X" }, "text": "The best phone I've ever had!", "rating": 5 }, { "id": "42", "createdAt": "2023-08-22T15:30:00Z", "product": { "name": "Smartphone Y" }, "text": "Not a very good phone at all.", "rating": 0 } ] } } } ``` </TabItem> </Tabs> In the example above, we are filtering for reviews of products with the word "phone" and a rating of 4 or more, or a rating of 0. The `_and` and `_or` operators can be nested to any depth, allowing for arbitrarily complex filters. ## Filtering by custom properties By default, the `ListQueryBuilder` will only allow filtering by properties which are defined on the entity itself. So in the case of the `ProductReview`, we can filter by `rating` and `text` etc., but not by `product.name`. However, it is possible to extend your GraphQL type to allow filtering by custom properties. Let's implement filtering but the `product.name` property. First, we need to manually add the `productName` field to the `ProductReviewFilterParameter` type: ```ts title="src/plugins/reviews/api/api-extensions.ts" import gql from 'graphql-tag'; export const adminApiExtensions = gql` # ... existing definitions from earlier example omitted // highlight-start input ProductReviewFilterParameter { productName: StringOperators } // highlight-end `; ``` Next we need to update our `ProductReviewService` to be able to handle filtering on this new field using the [customPropertyMap](/reference/typescript-api/data-access/list-query-builder/#custompropertymap) option: ```ts title="src/plugins/reviews/services/product-review.service.ts" import { Injectable } from '@nestjs/common'; import { InjectConnection } from '@nestjs/typeorm'; import { ListQueryBuilder, ListQueryOptions, PaginatedList, RequestContext } from '@vendure/core'; import { ProductReview } from '../entities/product-review.entity'; @Injectable() export class ProductReviewService { constructor( private listQueryBuilder: ListQueryBuilder, ) {} findAll(ctx: RequestContext, options?: ListQueryOptions<ProductReview>): Promise<PaginatedList<ProductReview>> { return this.listQueryBuilder .build(ProductReview, options, { // highlight-next-line relations: ['product'], ctx, // highlight-start customPropertyMap: { productName: 'product.name', } // highlight-end }) .getManyAndCount() .then(([items, totalItems]) => ({ items, totalItems })); } } ``` Upon restarting your server, you should now be able to filter by `productName`: ```graphql query { productReviews( options: { skip: 0 take: 10 // highlight-start filter: { productName: { contains: "phone" } } // highlight-end }) { totalItems items { id createdAt product { name } text rating } } } ```
--- title: "Managing the Active Order" --- import Stackblitz from '@site/src/components/Stackblitz'; The "active order" is what is also known as the "cart" - it is the order that is currently being worked on by the customer. An order remains active until it is completed, and during this time it can be modified by the customer in various ways: - Adding an item - Removing an item - Changing the quantity of items - Applying a coupon - Removing a coupon This guide will cover how to manage the active order. ## Define an Order fragment Since all the mutations that we will be using in this guide require an `Order` object, we will define a fragment that we can reuse in all of our mutations. ```ts title="src/fragments.ts" const ACTIVE_ORDER_FRAGMENT = /*GraphQL*/` fragment ActiveOrder on Order { __typename id code couponCodes state currencyCode totalQuantity subTotalWithTax shippingWithTax totalWithTax discounts { description amountWithTax } lines { id unitPriceWithTax quantity linePriceWithTax productVariant { id name sku } featuredAsset { id preview } } shippingLines { shippingMethod { description } priceWithTax } }` ``` :::note The `__typename` field is used to determine the type of the object returned by the GraphQL server. In this case, it will always be `'Order'`. Some GraphQL clients such as Apollo Client will automatically add the `__typename` field to all queries and mutations, but if you are using a different client you may need to add it manually. ::: This fragment can then be used in subsequent queries and mutations by using the `...` spread operator in the place where an `Order` object is expected. You can then embed the fragment in the query or mutation by using the `${ACTIVE_ORDER_FRAGMENT}` syntax: ```ts title="src/queries.ts" import { ACTIVE_ORDER_FRAGMENT } from './fragments'; export const GET_ACTIVE_ORDER = /*GraphQL*/` query GetActiveOrder { activeOrder { // highlight-next-line ...ActiveOrder } } // highlight-next-line ${ACTIVE_ORDER_FRAGMENT} `; ``` For the remainder of this guide, we will list just the body of the query or mutation, and assume that the fragment is defined and imported as above. ## Get the active order This fragment can then be used in subsequent queries and mutations. Let's start with a query to get the active order using the [`activeOrder` query](/reference/graphql-api/shop/queries#activeorder): ```graphql query GetActiveOrder { activeOrder { ...ActiveOrder } } ``` ## Add an item To add an item to the active order, we use the [`addItemToOrder` mutation](/reference/graphql-api/shop/mutations/#additemtoorder), as we have seen in the [Product Detail Page guide](/guides/storefront/product-detail/). ```graphql mutation AddItemToOrder($productVariantId: ID!, $quantity: Int!) { addItemToOrder(productVariantId: $productVariantId, quantity: $quantity) { ...ActiveOrder ... on ErrorResult { errorCode message } ... on InsufficientStockError { quantityAvailable order { ...ActiveOrder } } } } ``` :::info If you have defined any custom fields on the `OrderLine` entity, you will be able to pass them as a `customFields` argument to the `addItemToOrder` mutation. See the [Configurable Products guide](/guides/how-to/configurable-products/) for more information. ::: ## Remove an item To remove an item from the active order, we use the [`removeOrderLine` mutation](/reference/graphql-api/shop/mutations/#removeorderline), and pass the `id` of the `OrderLine` to remove. ```graphql mutation RemoveItemFromOrder($orderLineId: ID!) { removeOrderLine(orderLineId: $orderLineId) { ...ActiveOrder ... on ErrorResult { errorCode message } } } ``` ## Change the quantity of an item To change the quantity of an item in the active order, we use the [`adjustOrderLine` mutation](/reference/graphql-api/shop/mutations/#adjustorderline). ```graphql mutation AdjustOrderLine($orderLineId: ID!, $quantity: Int!) { adjustOrderLine(orderLineId: $orderLineId, quantity: $quantity) { ...ActiveOrder ... on ErrorResult { errorCode message } } } ``` :::info If you have defined any custom fields on the `OrderLine` entity, you will be able to update their values by passing a `customFields` argument to the `adjustOrderLine` mutation. See the [Configurable Products guide](/guides/how-to/configurable-products/) for more information. ::: ## Applying a coupon code If you have defined any [Promotions](/guides/core-concepts/promotions/) which use coupon codes, you can apply the a coupon code to the active order using the [`applyCouponCode` mutation](/reference/graphql-api/shop/mutations/#applycouponcode). ```graphql mutation ApplyCouponCode($couponCode: String!) { applyCouponCode(couponCode: $couponCode) { ...ActiveOrder ... on ErrorResult { errorCode message } } } ``` ## Removing a coupon code To remove a coupon code from the active order, we use the [`removeCouponCode` mutation](/reference/graphql-api/shop/mutations/#removecouponcode). ```graphql mutation RemoveCouponCode($couponCode: String!) { removeCouponCode(couponCode: $couponCode) { ...ActiveOrder ... on ErrorResult { errorCode message } } } ``` ## Live example Here is a live example which demonstrates adding, updating and removing items from the active order: <Stackblitz id='vendure-docs-active-order' />
--- title: "Checkout Flow" --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Once the customer has added the desired products to the active order, it's time to check out. This guide assumes that you are using the [default OrderProcess](/guides/core-concepts/orders/#the-order-process), so if you have defined a custom process, some of these steps may be slightly different. :::note In this guide, we will assume that an `ActiveOrder` fragment has been defined, as detailed in the [Managing the Active Order guide](/guides/storefront/active-order/#define-an-order-fragment), but for the purposes of checking out the fragment should also include `customer` `shippingAddress` and `billingAddress` fields. ::: ## Add a customer Every order must be associated with a customer. If the customer is not logged in, then the [`setCustomerForOrder`](/reference/graphql-api/shop/mutations/#setcustomerfororder) mutation must be called. This will create a new Customer record if the provided email address does not already exist in the database. :::note If the customer is already logged in, then this step is skipped. ::: <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation SetCustomerForOrder($input: CreateCustomerInput!) { setCustomerForOrder(input: $input) { ...ActiveOrder ...on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "input": { "title": "Mr.", "firstName": "Bob", "lastName": "Dobalina", "phoneNumber": "1234556", "emailAddress": "b.dobalina@email.com", } } ``` </TabItem> </Tabs> ## Set the shipping address The [`setOrderShippingAddress`](/reference/graphql-api/shop/mutations/#setordershippingaddress) mutation must be called to set the shipping address for the order. <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation SetOrderShippingAddress($input: CreateAddressInput!) { setOrderShippingAddress(input: $input) { ...ActiveOrder ...on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "input": { "fullName": "John Doe", "company": "ABC Inc.", "streetLine1": "123 Main St", "streetLine2": "Apt 4B", "city": "New York", "province": "NY", "postalCode": "10001", "countryCode": "US", "phoneNumber": "123-456-7890", "defaultShippingAddress": true, "defaultBillingAddress": false } } ``` </TabItem> </Tabs> If the customer is logged in, you can check their existing addresses and pre-populate an address form if an existing address is found. <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetCustomerAddresses { activeCustomer { id addresses { id fullName company streetLine1 streetLine2 city province postalCode country { code name } phoneNumber defaultShippingAddress defaultBillingAddress } } } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "activeCustomer": { "id": "123456", "addresses": [ { "id": "123", "fullName": "John Doe", "company": "", "streetLine1": "123 Main St", "streetLine2": "Apt 4B", "city": "New York", "province": "NY", "postalCode": "10001", "country": { "code": "US", "name": "United States" }, "phoneNumber": "123-456-7890", "defaultShippingAddress": true, "defaultBillingAddress": false }, { "id": "124", "fullName": "John Doe", "company": "", "streetLine1": "456 Elm St", "streetLine2": "", "city": "Los Angeles", "province": "CA", "postalCode": "90001", "country": { "code": "US", "name": "United States" }, "phoneNumber": "987-654-3210", "defaultShippingAddress": false, "defaultBillingAddress": true } ] } } } ``` </TabItem> </Tabs> ## Set the shipping method Now that we know the shipping address, we can check which shipping methods are available with the [`eligibleShippingMethods`](/reference/graphql-api/shop/queries/#eligibleshippingmethods) query. <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetShippingMethods { eligibleShippingMethods { id price description } } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "eligibleShippingMethods": [ { "id": "1", "price": 545, "description": "Standard Shipping" }, { "id": "2", "price": 1250, "description": "Expedited Shipping" }, { "id": "3", "price": 1695, "description": "Overnight Shipping" } ] } } ``` </TabItem> </Tabs> The results can then be displayed to the customer so they can choose the desired shipping method. If there is only a single result, then it can be automatically selected. The desired shipping method's id is the passed to the [`setOrderShippingMethod`](/reference/graphql-api/shop/mutations/#setordershippingmethod) mutation. ```graphql mutation SetShippingMethod($id: [ID!]!) { setOrderShippingMethod(shippingMethodId: $id) { ...ActiveOrder ...on ErrorResult { errorCode message } } } ``` ## Add payment The [`eligiblePaymentMethods`](/reference/graphql-api/shop/queries/#eligiblepaymentmethods) query can be used to get a list of available payment methods. This list can then be displayed to the customer, so they can choose the desired payment method. <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetPaymentMethods { eligiblePaymentMethods { id name code isEligible } } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "eligiblePaymentMethods": [ { "id": "1", "name": "Stripe", "code": "stripe", "isEligible": true }, { "id": "2", "name": "Apple Pay", "code": "apple-pay", "isEligible": true } { "id": "3", "name": "Pay on delivery", "code": "pay-on-delivery", "isEligible": false } ] } } ``` </TabItem> </Tabs> Next, we need to transition the order to the `ArrangingPayment` state. This state ensures that no other changes can be made to the order while the payment is being arranged. The [`transitionOrderToState`](/reference/graphql-api/shop/mutations/#transitionordertostate) mutation is used to transition the order to the `ArrangingPayment` state. <Tabs> <TabItem value="Query" label="Query" default> ```graphql mutation TransitionToState($state: String!) { transitionOrderToState(state: $state) { ...ActiveOrder ...on OrderStateTransitionError { errorCode message transitionError fromState toState } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "state": "ArrangingPayment" } ``` </TabItem> </Tabs> At this point, your storefront will use an integration with the payment provider to collect the customer's payment details, and then the exact sequence of API calls will depend on the payment integration. The [`addPaymentToOrder`](/reference/graphql-api/shop/mutations/#addpaymenttoorder) mutation is the general-purpose mutation for adding a payment to an order. It accepts a `method` argument which must corresponde to the `code` of the selected payment method, and a `metadata` argument which is a JSON object containing any additional information required by that particular integration. For example, the demo data populated in a new Vendure installation includes a "Standard Payment" method, which uses the [`dummyPaymentHandler`](/reference/typescript-api/payment/dummy-payment-handler) to simulate a payment provider. Here's how you would add a payment using this method: <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation AddPaymentToOrder($input: PaymentInput!) { addPaymentToOrder(input: $input) { ...ActiveOrder ...on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "method": "standard-payment", "metadata": { "shouldDecline": false, "shouldError": false, "shouldErrorOnSettle": false, } } ``` </TabItem> </Tabs> Other payment integrations have specific setup instructions you must follow: ### Stripe Our [`StripePlugin docs`](/reference/core-plugins/payments-plugin/stripe-plugin/) describe how to set up your checkout to use Stripe. ### Braintree Our [`BraintreePlugin` docs](/reference/core-plugins/payments-plugin/braintree-plugin/) describe how to set up your checkout to use Braintree. ### Mollie Our [`MolliePlugin` docs](/reference/core-plugins/payments-plugin/mollie-plugin/) describe how to set up your checkout to use Mollie. ### Other payment providers For more information on how to integrate with a payment provider, see the [Payment](/guides/core-concepts/payment/) guide. ## Display confirmation Once the checkout has completed, the order will no longer be considered "active" (see the [`OrderPlacedStrategy`](/reference/typescript-api/orders/order-placed-strategy/)) and so the [`activeOrder`](/reference/graphql-api/shop/queries/#activeorder) query will return `null`. Instead, the [`orderByCode`](/reference/graphql-api/shop/queries/#orderbycode) query can be used to retrieve the order by its code to display a confirmation page. <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetOrderByCode($code: String!) { orderByCode(code: $code) { ...Order } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "code": "PJGY46GCB1EDU9YH" } ``` </TabItem> </Tabs> :::info By default Vendure will only allow access to the order by code for the first 2 hours after the order is placed if the customer is not logged in. This is to prevent a malicious user from guessing order codes and viewing other customers' orders. This can be configured via the [`OrderByCodeAccessStrategy`](/reference/typescript-api/orders/order-by-code-access-strategy/). :::
--- title: "Storefront GraphQL Code Generation" --- Code generation means the automatic generation of TypeScript types based on your GraphQL schema and your GraphQL operations. This is a very powerful feature that allows you to write your code in a type-safe manner, without you needing to manually write any types for your API calls. To do this, we will use [Graphql Code Generator](https://the-guild.dev/graphql/codegen). :::note This guide is for adding codegen to your storefront. For a guide on adding codegen to your backend Vendure plugins or UI extensions, see the [Plugin Codegen](/guides/how-to/codegen/) guide. ::: ## Installation Follow the installation instructions in the [GraphQL Code Generator Quick Start](https://the-guild.dev/graphql/codegen/docs/getting-started/installation). Namely: ```bash npm i graphql npm i -D typescript @graphql-codegen/cli npx graphql-code-generator init npm install ``` During the `init` step, you'll be prompted to select various options about how to configure the code generation. - Where is your schema?: Use `http://localhost:3000/shop-api` (unless you have configured a different GraphQL API URL) - Where are your operations and fragments?: Use the appropriate glob pattern for you project. For example, `src/**/*.{ts,tsx}`. - Select `codegen.ts` as the name of the config file. ## Configuration The `init` step above will create a `codegen.ts` file in your project root. Add the highlighted lines: ```ts title="codegen.ts" import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { overwrite: true, schema: 'http://localhost:3000/shop-api', documents: 'src/**/*.graphql.ts', generates: { 'src/gql/': { preset: 'client', plugins: [], // highlight-start config: { scalars: { // This tells codegen that the `Money` scalar is a number Money: 'number', }, namingConvention: { // This ensures generated enums do not conflict with the built-in types. enumValues: 'keep', }, } // highlight-end }, } }; export default config; ``` ## Running Codegen During the `init` step, you will have installed a `codegen` script in your `package.json`. You can run this script to generate the TypeScript types for your GraphQL operations. :::note Ensure you have the Vendure server running before running the codegen script. ::: ```bash npm run codegen ``` This will generate a `src/gql` directory containing the TypeScript types for your GraphQL operations. ## Use the `graphql()` function If you have existing GraphQL queries and mutations in your application, you can now use the `graphql()` function exported by the `src/gql/index.ts` file to execute them. If you were previously using the `gql` tagged template function, replace it with the `graphql()` function. ```ts title="src/App.tsx" import { useQuery } from '@tanstack/react-query'; import request from 'graphql-request' // highlight-next-line import { graphql } from './gql'; // highlight-start // GET_PRODUCTS will be a `TypedDocumentNode` type, // which encodes the types of the query variables and the response data. const GET_PRODUCTS = graphql(` // highlight-end query GetProducts($options: ProductListOptions) { products(options: $options) { items { id name slug featuredAsset { preview } } } } `); export default function App() { // highlight-start // `data` will now be correctly typed const { isLoading, data } = useQuery({ // highlight-end queryKey: ['products'], queryFn: async () => request( 'http://localhost:3000/shop-api', // highlight-start GET_PRODUCTS, { // The variables will also be correctly typed options: { take: 3 }, } // highlight-end ), }); if (isLoading) return <p>Loading...</p>; return data ? ( data.products.items.map(({ id, name, slug, featuredAsset }) => ( <div key={id}> <h3>{name}</h3> <img src={`${featuredAsset.preview}?preset=small`} alt={name} /> </div> )) ) : ( <>Loading...</> ); } ``` In the above example, the type information all works out of the box because the `graphql-request` library from v5.0.0 has built-in support for the [`TypedDocumentNode`](https://github.com/dotansimha/graphql-typed-document-node) type, as do the latest versions of most of the popular GraphQL client libraries, such as Apollo Client & Urql. :::note In the documentation examples on other pages, we do not assume the use of code generation in order to keep the examples as simple as possible. :::
--- title: Connect to the API --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import Stackblitz from '@site/src/components/Stackblitz'; The first thing you'll need to do is to connect your storefront app to the **Shop API**. The Shop API is a GraphQL API that provides access to the products, collections, customer data, and exposes mutations that allow you to add items to the cart, checkout, manage customer accounts, and more. :::tip You can explore the Shop API by opening the GraphQL Playground in your browser at [`http://localhost:3000/shop-api`](http://localhost:3000/shop-api) when your Vendure server is running locally. ::: ## Select a GraphQL client GraphQL requests are made over HTTP, so you can use any HTTP client such as the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to make requests to the Shop API. However, there are also a number of specialized GraphQL clients which can make working with GraphQL APIs easier. Here are some popular options: * [Apollo Client](https://www.apollographql.com/docs/react): A full-featured client which includes a caching layer and React integration. * [urql](https://formidable.com/open-source/urql/): The highly customizable and versatile GraphQL client for React, Svelte, Vue, or plain JavaScript * [graphql-request](https://github.com/jasonkuhrt/graphql-request): Minimal GraphQL client supporting Node and browsers for scripts or simple apps * [TanStack Query](https://tanstack.com/query/latest): Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte, which can be combined with `graphql-request`. ## Managing Sessions Vendure supports two ways to manage user sessions: **cookies** and **bearer token**. The method you choose depends on your requirements, and is specified by the [`authOptions.tokenMethod` property](/reference/typescript-api/auth/auth-options/#tokenmethod) of the VendureConfig. By default, both are enabled on the server: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; export const config: VendureConfig = { // ... authOptions: { // highlight-next-line tokenMethod: ['bearer', 'cookie'], }, }; ``` ### Cookie-based sessions Using cookies is the simpler approach for browser-based applications, since the browser will manage the cookies for you automatically. 1. Enable the `credentials` option in your HTTP client. This allows the browser to send the session cookie with each request. For example, if using a fetch-based client (such as [Apollo client](https://www.apollographql.com/docs/react/recipes/authentication/#cookie)) you would set `credentials: 'include'` or if using [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials), you would set `withCredentials: true` 2. When using cookie-based sessions, you should set the [`authOptions.cookieOptions.secret` property](/reference/typescript-api/auth/cookie-options#secret) to some secret string which will be used to sign the cookies sent to clients to prevent tampering. This string could be hard-coded in your config file, or (better) reside in an environment variable: ```ts title="src/vendure-config.ts" import { VendureConfig } from '@vendure/core'; export const config: VendureConfig = { // ... authOptions: { tokenMethod: ['bearer', 'cookie'], // highlight-start cookieOptions: { secret: process.env.COOKIE_SESSION_SECRET } // highlight-end } } ``` :::caution **SameSite cookies** When using cookies to manage sessions, you need to be aware of the SameSite cookie policy. This policy is designed to prevent cross-site request forgery (CSRF) attacks, but can cause problems when using a headless storefront app which is hosted on a different domain to the Vendure server. See [this article](https://web.dev/samesite-cookies-explained/) for more information. ::: ### Bearer-token sessions Using bearer tokens involves a bit more work on your part: you'll need to manually read response headers to get the token, and once you have it you'll have to manually add it to the headers of each request. The workflow would be as follows: 1. Certain mutations and queries initiate a session (e.g. logging in, adding an item to an order etc.). When this happens, the response will contain a HTTP header which [by default is called `'vendure-auth-token'`](/reference/typescript-api/auth/auth-options#authtokenheaderkey). 2. So your http client would need to check for the presence of this header each time it receives a response from the server. 3. If the `'vendure-auth-token'` header is present, read the value and store it because this is your bearer token. 4. Attach this bearer token to each subsequent request as `Authorization: Bearer <token>`. Here's a simplified example of how that would look: ```ts let token: string | undefined = localStorage.getItem('token') export async function request(query: string, variables: any) { // If we already know the token, set the Authorization header. const headers = token ? { Authorization: `Bearer ${token}` } : {}; const response = await someGraphQlClient(query, variables, headers); // Check the response headers to see if Vendure has set the // auth token. The header key "vendure-auth-token" may be set to // a custom value with the authOptions.authTokenHeaderKey config option. const authToken = response.headers.get('vendure-auth-token'); if (authToken != null) { token = authToken; } return response.data; } ``` There are some concrete examples of this approach in the examples later on in this guide. ### Session duration The duration of a session is determined by the [AuthOptions.sessionDuration](/reference/typescript-api/auth/auth-options#sessionduration) config property. Sessions will automatically extend (or "refresh") when a user interacts with the API, so in effect the `sessionDuration` signifies the length of time that a session will stay valid since the last API call. ## Specifying a channel If your project has multiple [channels](/guides/core-concepts/channels/), you can specify the active channel by setting the `vendure-token` header on each request to match the `channelToken` for the desired channel. Let's say you have a channel with the token `uk-channel` and you want to make a request to the Shop API to get the products in that channel. You would set the `vendure-token` header to `uk-channel`: ```ts title="src/client.ts" export function query(document: string, variables: Record<string, any> = {}) { return fetch('https://localhost:3000/shop-api', { method: 'POST', headers: { 'content-type': 'application/json', // highlight-start 'vendure-token': 'uk-channel', // highlight-end }, credentials: 'include', body: JSON.stringify({ query: document, variables, }), }) .then((res) => res.json()) .catch((err) => console.log(err)); } ``` :::note If no channel token is specified, then the **default channel** will be used. ::: :::info The header name `vendure-token` is the default, but can be changed using the [`apiOptions.channelTokenKey`](/reference/typescript-api/configuration/api-options/#channeltokenkey) config option. ::: ## Setting language If you have translations of your products, collections, facets etc, you can specify the language for the request by setting the `languageCode` query string on the request. The value should be one of the ISO 639-1 codes defined by the [`LanguageCode` enum](/reference/typescript-api/common/language-code/). ``` POST http://localhost:3000/shop-api?languageCode=de ``` ## Code generation If you are building your storefront with TypeScript, we highly recommend you set up code generation to ensure that the responses from your queries & mutation are always correctly typed according the fields you request. See the [GraphQL Code Generation guide](/guides/storefront/codegen/) for more information. ## Examples Here are some examples of how to set up clients to connect to the Shop API. All of these examples include functions for setting the language and channel token. ### Fetch First we'll look at a plain [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)-based implementation, to show you that there's no special magic to a GraphQL request - it's just a POST request with a JSON body. Note that we also include a React hook in this example, but that's just to make it more convenient to use the client in a React component - it is not required. <Tabs> <TabItem value="client.ts" label="client.ts" default> ```ts title="src/client.ts" import { useState, useEffect } from 'react'; // If using bearer-token based session management, we'll store the token // in localStorage using this key. const AUTH_TOKEN_KEY = 'auth_token'; const API_URL = 'https://readonlydemo.vendure.io/shop-api'; let languageCode: string | undefined; let channelToken: string | undefined; export function setLanguageCode(value: string | undefined) { languageCode = value; } export function setChannelToken(value: string | undefined) { channelToken = value; } export function query(document: string, variables: Record<string, any> = {}) { const authToken = localStorage.getItem(AUTH_TOKEN_KEY); const headers = new Headers({ 'content-type': 'application/json', }); if (authToken) { headers.append('authorization', `Bearer ${authToken}`); } if (channelToken) { headers.append('vendure-token', channelToken); } let endpoint = API_URL; if (languageCode) { endpoint += `?languageCode=${languageCode}`; } // highlight-start return fetch(endpoint, { method: 'POST', headers, credentials: 'include', body: JSON.stringify({ query: document, variables, }), // highlight-end }).then((res) => { if (!res.ok) { throw new Error(`An error ocurred, HTTP status: ${res.status}`); } const newAuthToken = res.headers.get('vendure-auth-token'); if (newAuthToken) { localStorage.setItem(AUTH_TOKEN_KEY, newAuthToken); } return res.json(); }); } /** * Here we have wrapped the `query` function into a React hook for convenient use in * React components. */ export function useQuery( document: string, variables: Record<string, any> = {} ) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { query(document, variables) .then((result) => { setData(result.data); setError(null); }) .catch((err) => { setError(err.message); setData(null); }) .finally(() => { setLoading(false); }); }, []); return { data, loading, error }; } ``` </TabItem> <TabItem value="App.tsx" label="App.tsx" default> ```ts title="src/App.tsx" import { useQuery } from './client'; import './style.css'; const GET_PRODUCTS = /*GraphQL*/ ` query GetProducts($options: ProductListOptions) { products(options: $options) { items { id name slug featuredAsset { preview } } } } `; export default function App() { const { data, loading, error } = useQuery(GET_PRODUCTS, { options: { take: 3 }, }); if (loading) return <p>Loading...</p>; if (error) return <p>Error : {error.message}</p>; return data.products.items.map(({ id, name, slug, featuredAsset }) => ( <div key={id}> <h3>{name}</h3> <img src={`${featuredAsset.preview}?preset=small`} alt={name} /> </div> )); } ``` </TabItem> <TabItem value="index.ts" label="index.ts" default> ```ts title="src/index.ts" import * as React from 'react'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import App from './App'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); root.render( <StrictMode> <App /> </StrictMode> ); ``` </TabItem> </Tabs> Here's a live version of this example: <Stackblitz id='vendure-docs-fetch-react' /> As you can see, the basic implementation with `fetch` is quite straightforward. However, it is also lacking some features that other, dedicated client libraries will provide. ### Apollo Client Here's an example configuration for [Apollo Client](https://www.apollographql.com/docs/react/) with a React app. Follow the [getting started instructions](https://www.apollographql.com/docs/react/get-started) to install the required packages. <Tabs> <TabItem value="client.ts" label="client.ts" default> ```ts title="src/client.ts" import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, } from '@apollo/client'; import { setContext } from '@apollo/client/link/context'; const API_URL = `https://demo.vendure.io/shop-api`; // If using bearer-token based session management, we'll store the token // in localStorage using this key. const AUTH_TOKEN_KEY = 'auth_token'; let channelToken: string | undefined; let languageCode: string | undefined; const httpLink = new HttpLink({ uri: () => { if (languageCode) { return `${API_URL}?languageCode=${languageCode}`; } else { return API_URL; } }, // This is required if using cookie-based session management, // so that any cookies get sent with the request. credentials: 'include', }); // This part is used to check for and store the session token // if it is returned by the server. const afterwareLink = new ApolloLink((operation, forward) => { return forward(operation).map((response) => { const context = operation.getContext(); const authHeader = context.response.headers.get('vendure-auth-token'); if (authHeader) { // If the auth token has been returned by the Vendure // server, we store it in localStorage localStorage.setItem(AUTH_TOKEN_KEY, authHeader); } return response; }); }); /** * Used to specify a channel token for projects that use * multiple Channels. */ export function setChannelToken(value: string | undefined) { channelToken = value; } /** * Used to specify a language for any localized results. */ export function setLanguageCode(value: string | undefined) { languageCode = value; } export const client = new ApolloClient({ link: ApolloLink.from([ // If we have stored the authToken from a previous // response, we attach it to all subsequent requests. setContext((request, operation) => { const authToken = localStorage.getItem(AUTH_TOKEN_KEY); let headers: Record<string, any> = {}; if (authToken) { headers.authorization = `Bearer ${authToken}`; } if (channelToken) { headers['vendure-token'] = channelToken; } return { headers }; }), afterwareLink, httpLink, ]), cache: new InMemoryCache(), }); ``` </TabItem> <TabItem value='index.tsx' label='index.tsx'> ```tsx title="src/index.tsx" import React from 'react'; import * as ReactDOM from 'react-dom/client'; import { ApolloProvider } from '@apollo/client'; import App from './App'; import { client } from './client'; // Supported in React 18+ const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <ApolloProvider client={client}> <App /> </ApolloProvider>, ); ``` </TabItem> <TabItem value="App.tsx" label="App.tsx"> ```tsx title="src/App.tsx" import { useQuery, gql } from '@apollo/client'; const GET_PRODUCTS = gql` query GetProducts($options: ProductListOptions) { products(options: $options) { items { id name slug featuredAsset { preview } } } } `; export default function App() { const { loading, error, data } = useQuery(GET_PRODUCTS, { variables: { options: { take: 3 } }, }); if (loading) return <p>Loading...</p>; if (error) return <p>Error : {error.message}</p>; return data.products.items.map(({ id, name, slug, featuredAsset }) => ( <div key={id}> <h3>{name}</h3> <img src={`${featuredAsset.preview}?preset=small`} alt={name} /> </div> )); } ``` </TabItem> </Tabs> Here's a live version of this example: <Stackblitz id='vendure-docs-apollo-client' /> ### TanStack Query Here's an example using [@tanstack/query](https://tanstack.com/query/latest) in combination with [graphql-request](https://github.com/jasonkuhrt/graphql-request) based on [this guide](https://tanstack.com/query/v4/docs/react/graphql). Note that in this example we have also installed the [`@graphql-typed-document-node/core` package](https://github.com/dotansimha/graphql-typed-document-node), which allows the client to work with TypeScript code generation for type-safe queries. <Tabs> <TabItem value="client.ts" label="client.ts" default> ```tsx title="src/client.ts" import type { TypedDocumentNode } from '@graphql-typed-document-node/core'; import { GraphQLClient, RequestDocument, RequestMiddleware, ResponseMiddleware, Variables, } from 'graphql-request'; // If using bearer-token based session management, we'll store the token // in localStorage using this key. const AUTH_TOKEN_KEY = 'auth_token'; const API_URL = 'http://localhost:3000/shop-api'; // If we have a session token, add it to the outgoing request const requestMiddleware: RequestMiddleware = async (request) => { const authToken = localStorage.getItem(AUTH_TOKEN_KEY); return { ...request, headers: { ...request.headers, ...(authToken ? { authorization: `Bearer ${authToken}` } : {}), }, }; }; // Check all responses for a new session token const responseMiddleware: ResponseMiddleware = (response) => { if (!(response instanceof Error) && !response.errors) { const authHeader = response.headers.get('vendure-auth-token'); if (authHeader) { // If the session token has been returned by the Vendure // server, we store it in localStorage localStorage.setItem(AUTH_TOKEN_KEY, authHeader); } } }; const client = new GraphQLClient(API_URL, { // Required for cookie-based sessions credentials: 'include', requestMiddleware, responseMiddleware, }); /** * Sets the languageCode to be used for all subsequent requests. */ export function setLanguageCode(languageCode: string | undefined) { if (!languageCode) { client.setEndpoint(API_URL); } else { client.setEndpoint(`${API_URL}?languageCode=${languageCode}`); } } /** * Sets the channel token to be used for all subsequent requests. */ export function setChannelToken(channelToken: string | undefined) { if (!channelToken) { client.setHeader('vendure-token', undefined); } else { client.setHeader('vendure-token', channelToken); } } /** * Makes a GraphQL request using the `graphql-request` client. */ export function request<T, V extends Variables = Variables>( document: RequestDocument | TypedDocumentNode<T, V>, variables: Record<string, any> = {} ) { return client.request(document, variables); } ``` </TabItem> <TabItem value="App.tsx" label="App.tsx"> ```tsx title="src/App.tsx" import * as React from 'react'; import { gql } from 'graphql-request'; import { useQuery } from '@tanstack/react-query'; import { request } from './client'; const GET_PRODUCTS = gql` query GetProducts($options: ProductListOptions) { products(options: $options) { items { id name slug featuredAsset { preview } } } } `; export default function App() { const { isLoading, data } = useQuery({ queryKey: ['products'], queryFn: async () => request(GET_PRODUCTS, { options: { take: 3 }, }), }); if (isLoading) return <p>Loading...</p>; return data ? ( data.products.items.map(({ id, name, slug, featuredAsset }) => ( <div key={id}> <h3>{name}</h3> <img src={`${featuredAsset.preview}?preset=small`} alt={name} /> </div> )) ) : ( <>Loading...</> ); } ``` </TabItem> <TabItem value="index.tsx" label="index.tsx" default> ```ts title="src/index.tsx" import * as React from 'react'; import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import App from './App'; // Create a client const queryClient = new QueryClient(); const rootElement = document.getElementById('root'); const root = createRoot(rootElement); root.render( <StrictMode> <QueryClientProvider client={queryClient}> <App /> </QueryClientProvider> </StrictMode> ); ``` </TabItem> </Tabs> Here's a live version of this example: <Stackblitz id='vendure-docs-tanstack-query' />
--- title: "Customer Accounts" --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Customers can register accounts and thereby gain the ability to: - View past orders - Store multiple addresses - Maintain an active order across devices - Take advantage of plugins that expose functionality to registered customers only, such as wishlists & loyalty points. ## Querying the active customer The [`activeCustomer` query](/reference/graphql-api/shop/queries/#activecustomer) will return a [`Customer`](/reference/graphql-api/shop/object-types#customer) object if the customer is registered and logged in, otherwise it will return `null`. This can be used in the storefront header for example to determine whether to display a "sign in" or "my account" link. <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetCustomerAddresses { activeCustomer { id title firstName lastName emailAddress } } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "activeCustomer": { "id": "12345", "title": "Mr.", "firstName": "John", "lastName": "Doe", "emailAddress": "john.doe@email.com" } } } ``` </TabItem> </Tabs> ## Logging in and out The [`login` mutation](/reference/graphql-api/shop/mutations#login) is used to attempt to log in using email address and password. Given correct credentials, a new authenticated session will begin for that customer. <Tabs> <TabItem value="Query" label="Query" default> ```graphql mutation LogIn($emailAddress: String!, $password: String!, $rememberMe: Boolean!) { login(username: $emailAddress, password: $password, rememberMe: $rememberMe) { ... on CurrentUser { id identifier } ... on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "emailAddress": "john.doe@email.com", "password": "**********", "rememberMe": true, } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "login": { "id": "12345", "identifier": "john.doe@email.com" } } } ``` </TabItem> </Tabs> The [`logout` mutation](/reference/graphql-api/shop/mutations#logout) will end an authenticated customer session. <Tabs> <TabItem value="Query" label="Query" default> ```graphql mutation LogOut { logout { success } } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "logout": { "success": true, } } } ``` </TabItem> </Tabs> :::note The `login` mutation, as well as the following mutations related to registration & password recovery only apply when using the built-in [`NativeAuthenticationStrategy`](/reference/typescript-api/auth/native-authentication-strategy/). If you are using alternative authentication strategies in your storefront, you would use the [`authenticate` mutation](/reference/graphql-api/shop/mutations/#authenticate) as covered in the [External Authentication guide](/guides/core-concepts/auth/#external-authentication). ::: ## Registering a customer account The [`registerCustomerAccount` mutation](/reference/graphql-api/shop/mutations/#registercustomeraccount) is used to register a new customer account. There are three possible registration flows: If [`authOptions.requireVerification`](/reference/typescript-api/auth/auth-options/#requireverification) is set to `true` (the default): 1. **The Customer is registered _with_ a password**. A verificationToken will be created (and typically emailed to the Customer). That verificationToken would then be passed to the verifyCustomerAccount mutation _without_ a password. The Customer is then verified and authenticated in one step. 2. **The Customer is registered _without_ a password**. A verificationToken will be created (and typically emailed to the Customer). That verificationToken would then be passed to the verifyCustomerAccount mutation _with_ the chosen password of the Customer. The Customer is then verified and authenticated in one step. If `authOptions.requireVerification` is set to `false`: 3. The Customer _must_ be registered _with_ a password. No further action is needed - the Customer is able to authenticate immediately. Here's a diagram of the second scenario, where the password is supplied during the _verification_ step. ![Verification flow](./verification.webp) Here's how the mutations would look for the above flow: <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation Register($input: RegisterCustomerInput!) { registerCustomerAccount(input: $input) { ... on Success { success } ...on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "input: { "title": "Mr." "firstName": "Nicky", "lastName": "Wire", "emailAddress": "nicky@example.com", "phoneNumber": "1234567", } } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "registerCustomerAccount": { "success": true, } } } ``` </TabItem> </Tabs> Note that in the variables above, we did **not** specify a password, as this will be done at the verification step. If a password _does_ get passed at this step, then it won't be needed at the verification step. This is a decision you can make based on the desired user experience of your storefront. Upon registration, the [EmailPlugin](/reference/core-plugins/email-plugin/) will generate an email to the customer containing a link to the verification page. In a default Vendure installation this is set in the vendure config file: ```ts title="src/vendure-config.ts" EmailPlugin.init({ route: 'mailbox', handlers: defaultEmailHandlers, templatePath: path.join(__dirname, '../static/email/templates'), outputPath: path.join(__dirname, '../static/email/output'), globalTemplateVars: { fromAddress: '"Vendure Demo Store" <noreply@vendure.io>', // highlight-next-line verifyEmailAddressUrl: 'https://demo.vendure.io/storefront/account/verify', passwordResetUrl: 'https://demo.vendure.io/storefront/account/reset-password', changeEmailAddressUrl: 'https://demo.vendure.io/storefront/account/change-email-address' }, devMode: true, }), ``` The verification page needs to get the token from the query string, and pass it to the [`verifyCustomerAccount` mutation](/reference/graphql-api/shop/mutations/#verifycustomeraccount): <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation Verify($password: String!, $token: String!) { verifyCustomerAccount(password: $password, token: $token) { ...on CurrentUser { id identifier } ...on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "password": "*********", "token": "MjAxOS0xMC0wMlQxNToxOTo1NC45NDVa_1DYEWYAB7S3S82JT" } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "verifyCustomerAccount": { "id": "123", "identifier": "nicky@example.com" } } } ``` </TabItem> </Tabs> ## Password reset Here's how to implement a password reset flow. It is conceptually very similar to the verification flow described above. ![Password reset flow](./pw-reset.webp) A password reset is triggered by the [`requestPasswordReset` mutation](/reference/graphql-api/shop/mutations/#requestpasswordreset): <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation RequestPasswordReset($emailAddress: String!) { requestPasswordReset(emailAddress: $emailAddress) { ... on Success { success } ... on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "emailAddress": "nicky@example.com", } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "requestPasswordReset": { "success": true, } } } ``` </TabItem> </Tabs> Again, this mutation will trigger an event which the EmailPlugin's default email handlers will pick up and send an email to the customer. The password reset page then needs to get the token from the url and pass it to the [`resetPassword` mutation](/reference/graphql-api/shop/mutations/#resetpassword): <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation ResetPassword($token: String! $password: String!) { resetPassword(token: $token password: $password) { ...on CurrentUser { id identifier } ... on ErrorResult { errorCode message } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "token": "MjAxOS0xMC0wMlQxNToxOTo1NC45NDVa_1DYEWYAB7S3S82JT", "password": "************" } ``` </TabItem> <TabItem value="Result" label="Result"> ```json { "data": { "resetPassword": { "id": "123", "identifier": "nicky@example.com" } } } ``` </TabItem> </Tabs>
--- title: "Listing Products" --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import Stackblitz from '@site/src/components/Stackblitz'; Products are listed when: - Displaying the contents of a collection - Displaying search results In Vendure, we usually use the `search` query for both of these. The reason is that the `search` query is optimized for high performance, because it is backed by a dedicated search index. Other queries such as `products` or `Collection.productVariants` _can_ also be used to fetch a list of products, but they need to perform much more complex database queries, and are therefore slower. ## Listing products in a collection Following on from the [navigation example](/guides/storefront/navigation-menu/), let's assume that a customer has clicked on a collection item from the menu, and we want to display the products in that collection. Typically, we will know the `slug` of the selected collection, so we can use the `collection` query to fetch the details of this collection: <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetCollection($slug: String!) { collection(slug: $slug) { id name slug description featuredAsset { id preview } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "slug": "electronics" } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "collection": { "id": "2", "name": "Electronics", "slug": "electronics", "description": "", "featuredAsset": { "id": "16", "preview": "https://demo.vendure.io/assets/preview/5b/jakob-owens-274337-unsplash__preview.jpg" } } } } ``` </TabItem> </Tabs> The collection data can be used to render the page header. Next, we can use the `search` query to fetch the products in the collection: <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetCollectionProducts($slug: String!, $skip: Int, $take: Int) { search( input: { // highlight-next-line collectionSlug: $slug, groupByProduct: true, skip: $skip, take: $take } ) { totalItems items { productName slug productAsset { id preview } priceWithTax { ... on SinglePrice { value } ... on PriceRange { min max } } currencyCode } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "slug": "electronics", "skip": 0, "take": 10 } ``` </TabItem> <TabItem value="Response" label="Response" > (the following data has been truncated for brevity) ```json { "data": { "search": { "totalItems": 20, "items": [ { "productName": "Laptop", "slug": "laptop", "productAsset": { "id": "1", "preview": "https://demo.vendure.io/assets/preview/71/derick-david-409858-unsplash__preview.jpg" }, "priceWithTax": { "min": 155880, "max": 275880 }, "currencyCode": "USD" }, { "productName": "Tablet", "slug": "tablet", "productAsset": { "id": "2", "preview": "https://demo.vendure.io/assets/preview/b8/kelly-sikkema-685291-unsplash__preview.jpg" }, "priceWithTax": { "min": 39480, "max": 53400 }, "currencyCode": "USD" }, ], }, }, } ``` </TabItem> </Tabs> :::note The key thing to note here is that we are using the `collectionSlug` input to the `search` query. This ensures that the results all belong to the selected collection. ::: Here's a live demo of the above code in action: <Stackblitz id='vendure-docs-listing-collection-products' /> ## Product search The `search` query can also be used to perform a full-text search of the products in the catalog by passing the `term` input: <Tabs> <TabItem value="Query" label="Query"> ```graphql query SearchProducts($term: String!, $skip: Int, $take: Int) { search( input: { // highlight-next-line term: $term, groupByProduct: true, skip: $skip, take: $take } ) { totalItems items { productName slug productAsset { id preview } priceWithTax { ... on SinglePrice { value } ... on PriceRange { min max } } currencyCode } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "term": "camera", "skip": 0, "take": 10 } ``` </TabItem> <TabItem value="Response" label="Response" > (the following data has been truncated for brevity) ```json { "data": { "search": { "totalItems": 8, "items": [ { "productName": "Instant Camera", "slug": "instant-camera", "productAsset": { "id": "12", "preview": "https://demo.vendure.io/assets/preview/b5/eniko-kis-663725-unsplash__preview.jpg" }, "priceWithTax": { "min": 20999, "max": 20999 }, "currencyCode": "USD" }, { "productName": "Camera Lens", "slug": "camera-lens", "productAsset": { "id": "13", "preview": "https://demo.vendure.io/assets/preview/9b/brandi-redd-104140-unsplash__preview.jpg" }, "priceWithTax": { "min": 12480, "max": 12480 }, "currencyCode": "USD" } ] } } } ``` </TabItem> </Tabs> :::tip You can also limit the full-text search to a specific collection by passing the `collectionSlug` or `collectionId` input. ::: ## Faceted search The `search` query can also be used to perform faceted search. This is a powerful feature which allows customers to filter the results according to the facet values assigned to the products & variants. By using the `facetValues` field, the search query will return a list of all the facet values which are present in the result set. This can be used to render a list of checkboxes or other UI elements which allow the customer to filter the results. <Tabs> <TabItem value="Query" label="Query"> ```graphql query SearchProducts($term: String!, $skip: Int, $take: Int) { search( input: { term: $term, groupByProduct: true, skip: $skip, take: $take } ) { totalItems // highlight-start facetValues { count facetValue { id name facet { id name } } } // highlight-end items { productName slug productAsset { id preview } priceWithTax { ... on SinglePrice { value } ... on PriceRange { min max } } currencyCode } } } ``` </TabItem> <TabItem value="Variables" label="Variables" default> ```json { "term": "camera", "skip": 0, "take": 10 } ``` </TabItem> <TabItem value="Response" label="Response" > (the following data has been truncated for brevity) ```json { "data": { "search": { "totalItems": 8, // highlight-start "facetValues": [ { "facetValue": { "id": "1", "name": "Electronics", "facet": { "id": "1", "name": "category" } }, "count": 8 }, { "facetValue": { "id": "9", "name": "Photo", "facet": { "id": "1", "name": "category" } }, "count": 8 }, { "facetValue": { "id": "10", "name": "Polaroid", "facet": { "id": "2", "name": "brand" } }, "count": 1 }, { "facetValue": { "id": "11", "name": "Nikkon", "facet": { "id": "2", "name": "brand" } }, "count": 2 }, { "facetValue": { "id": "12", "name": "Agfa", "facet": { "id": "2", "name": "brand" } }, "count": 1 }, { "facetValue": { "id": "14", "name": "Kodak", "facet": { "id": "2", "name": "brand" } }, "count": 1 }, { "facetValue": { "id": "15", "name": "Sony", "facet": { "id": "2", "name": "brand" } }, "count": 1 }, { "facetValue": { "id": "16", "name": "Rolleiflex", "facet": { "id": "2", "name": "brand" } }, "count": 1 } ], // highlight-end "items": [ { "productName": "Instant Camera", "slug": "instant-camera", "productAsset": { "id": "12", "preview": "https://demo.vendure.io/assets/preview/b5/eniko-kis-663725-unsplash__preview.jpg" }, "priceWithTax": { "min": 20999, "max": 20999 }, "currencyCode": "USD" }, { "productName": "Camera Lens", "slug": "camera-lens", "productAsset": { "id": "13", "preview": "https://demo.vendure.io/assets/preview/9b/brandi-redd-104140-unsplash__preview.jpg" }, "priceWithTax": { "min": 12480, "max": 12480 }, "currencyCode": "USD" }, { "productName": "Vintage Folding Camera", "slug": "vintage-folding-camera", "productAsset": { "id": "14", "preview": "https://demo.vendure.io/assets/preview/3c/jonathan-talbert-697262-unsplash__preview.jpg" }, "priceWithTax": { "min": 642000, "max": 642000 }, "currencyCode": "USD" } ] } } } ``` </TabItem> </Tabs> These facet values can then be used to filter the results by passing them to the `facetValueFilters` input For example, let's filter the results to only include products which have the "Nikkon" brand. Based on our last request we know that there should be 2 such products, and that the `facetValue.id` for the "Nikkon" brand is `11`. ```json { "facetValue": { // highlight-next-line "id": "11", "name": "Nikkon", "facet": { "id": "2", "name": "brand" } }, // highlight-next-line "count": 2 } ``` Here's how we can use this information to filter the results: :::note In the next example, rather than passing each individual variable (skip, take, term) as a separate argument, we are passing the entire `SearchInput` object as a variable. This allows us more flexibility in how we use the query, as we can easily add or remove properties from the input object without having to change the query itself. ::: <Tabs> <TabItem value="Query" label="Query"> ```graphql query SearchProducts($input: SearchInput!) { // highlight-next-line search(input: $input) { totalItems facetValues { count facetValue { id name facet { id name } } } items { productName slug productAsset { id preview } priceWithTax { ... on SinglePrice { value } ... on PriceRange { min max } } currencyCode } } } ``` </TabItem> <TabItem value="Variables" label="Variables" default> ```json { "input": { "term": "camera", "skip": 0, "take": 10, "groupByProduct": true, // highlight-start "facetValueFilters": [ { "and": "11" } ] // highlight-end } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "search": { "totalItems": 2, "facetValues": [ { "facetValue": { "id": "1", "name": "Electronics", "facet": { "id": "1", "name": "category" } }, "count": 2 }, { "facetValue": { "id": "9", "name": "Photo", "facet": { "id": "1", "name": "category" } }, "count": 2 }, { "facetValue": { "id": "11", "name": "Nikkon", "facet": { "id": "2", "name": "brand" } }, "count": 2 } ], "items": [ { "productName": "Camera Lens", "slug": "camera-lens", "productAsset": { "id": "13", "preview": "https://demo.vendure.io/assets/preview/9b/brandi-redd-104140-unsplash__preview.jpg" }, "priceWithTax": { "value": 12480 }, "currencyCode": "USD" }, { "productName": "Nikkormat SLR Camera", "slug": "nikkormat-slr-camera", "productAsset": { "id": "18", "preview": "https://demo.vendure.io/assets/preview/95/chuttersnap-324234-unsplash__preview.jpg" }, "priceWithTax": { "value": 73800 }, "currencyCode": "USD" } ] } } } ``` </TabItem> </Tabs> :::info The `facetValueFilters` input can be used to specify multiple filters, combining each with either `and` or `or`. For example, to filter by both the "Camera" **and** "Nikkon" facet values, we would use: ```json { "facetValueFilters": [ { "and": "9" }, { "and": "11" } ] } ``` To filter by "Nikkon" **or** "Sony", we would use: ```json { "facetValueFilters": [ { "or": ["11", "15"] } ] } ``` ::: Here's a live example of faceted search. Try searching for terms like "shoe", "plant" or "ball". <Stackblitz id="vendure-docs-faceted-search"></Stackblitz> ## Listing custom product data If you have defined custom fields on the `Product` or `ProductVariant` entity, you might want to include these in the search results. With the [`DefaultSearchPlugin`](/reference/typescript-api/default-search-plugin/) this is not possible, as this plugin is designed to be a minimal and simple search implementation. Instead, you can use the [`ElasticsearchPlugin`](/reference/core-plugins/elasticsearch-plugin/) which provides advanced features which allow you to index custom data. The Elasticsearch plugin is designed as a drop-in replacement for the `DefaultSearchPlugin`, so you can simply swap out the plugins in your `vendure-config.ts` file.
--- title: "Navigation Menu" --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import Stackblitz from '@site/src/components/Stackblitz'; A navigation menu allows your customers to navigate your store and find the products they are looking for. Typically, navigation is based on a hierarchy of [collections](/guides/core-concepts/collections/). We can get the top-level collections using the `collections` query with the `topLevelOnly` filter: <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetTopLevelCollections { collections(options: { topLevelOnly: true }) { items { id slug name featuredAsset { id preview } } } } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "collections": { "items": [ { "id": "2", "slug": "electronics", "name": "Electronics", "featuredAsset": { "id": "16", "preview": "https://demo.vendure.io/assets/preview/5b/jakob-owens-274337-unsplash__preview.jpg" } }, { "id": "5", "slug": "home-garden", "name": "Home & Garden", "featuredAsset": { "id": "47", "preview": "https://demo.vendure.io/assets/preview/3e/paul-weaver-1120584-unsplash__preview.jpg" } }, { "id": "8", "slug": "sports-outdoor", "name": "Sports & Outdoor", "featuredAsset": { "id": "24", "preview": "https://demo.vendure.io/assets/preview/96/michael-guite-571169-unsplash__preview.jpg" } } ] } } } ``` </TabItem> </Tabs> ## Building a navigation tree The `collections` query returns a flat list of collections, but we often want to display them in a tree-like structure. This way, we can build up a navigation menu which reflects the hierarchy of collections. First of all we need to ensure that we have the `parentId` property on each collection. ```graphql title="Shop API" query GetAllCollections { collections(options: { topLevelOnly: true }) { items { id slug name // highlight-next-line parentId featuredAsset { id preview } } } } ``` Then we can use this data to build up a tree structure. The following code snippet shows how this can be done in TypeScript: ```ts title="src/utils/array-to-tree.ts" export type HasParent = { id: string; parentId: string | null }; export type TreeNode<T extends HasParent> = T & { children: Array<TreeNode<T>>; }; export type RootNode<T extends HasParent> = { id?: string; children: Array<TreeNode<T>>; }; /** * Builds a tree from an array of nodes which have a parent. * Based on https://stackoverflow.com/a/31247960/772859, modified to preserve ordering. */ export function arrayToTree<T extends HasParent>(nodes: T[]): RootNode<T> { const topLevelNodes: Array<TreeNode<T>> = []; const mappedArr: { [id: string]: TreeNode<T> } = {}; // First map the nodes of the array to an object -> create a hash table. for (const node of nodes) { mappedArr[node.id] = { ...(node as any), children: [] }; } for (const id of nodes.map((n) => n.id)) { if (mappedArr.hasOwnProperty(id)) { const mappedElem = mappedArr[id]; const parentId = mappedElem.parentId; if (!parent) { continue; } // If the element is not at the root level, add it to its parent array of children. const parentIsRoot = !mappedArr[parentId]; if (!parentIsRoot) { if (mappedArr[parentId]) { mappedArr[parentId].children.push(mappedElem); } else { mappedArr[parentId] = { children: [mappedElem] } as any; } } else { topLevelNodes.push(mappedElem); } } } const rootId = topLevelNodes.length ? topLevelNodes[0].parentId : undefined; return { id: rootId, children: topLevelNodes }; } ``` ## Live example Here's a live demo of the above code in action: <Stackblitz id='vendure-docs-collection-tree' />
--- title: "Product Detail Page" --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import Stackblitz from '@site/src/components/Stackblitz'; The product detail page (often abbreviated to PDP) is the page that shows the details of a product and allows the user to add it to their cart. Typically, the PDP should include: - Product name - Product description - Available product variants - Images of the product and its variants - Price information - Stock information - Add to cart button ## Fetching product data Let's create a query to fetch the required data. You should have either the product's `slug` or `id` available from the url. We'll use the `slug` in this example. <Tabs> <TabItem value="Query" label="Query" default> ```graphql query GetProductDetail($slug: String!) { product(slug: $slug) { id name description featuredAsset { id preview } assets { id preview } variants { id name sku stockLevel currencyCode price priceWithTax featuredAsset { id preview } assets { id preview } } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "slug": "laptop" } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "product": { "id": "1", "name": "Laptop", "description": "Now equipped with seventh-generation Intel Core processors, Laptop is snappier than ever. From daily tasks like launching apps and opening files to more advanced computing, you can power through your day thanks to faster SSDs and Turbo Boost processing up to 3.6GHz.", "featuredAsset": { "id": "1", "preview": "https://demo.vendure.io/assets/preview/71/derick-david-409858-unsplash__preview.jpg" }, "assets": [ { "id": "1", "preview": "https://demo.vendure.io/assets/preview/71/derick-david-409858-unsplash__preview.jpg" } ], "variants": [ { "id": "1", "name": "Laptop 13 inch 8GB", "sku": "L2201308", "stockLevel": "IN_STOCK", "currencyCode": "USD", "price": 129900, "priceWithTax": 155880, "featuredAsset": null, "assets": [] }, { "id": "2", "name": "Laptop 15 inch 8GB", "sku": "L2201508", "stockLevel": "IN_STOCK", "currencyCode": "USD", "price": 139900, "priceWithTax": 167880, "featuredAsset": null, "assets": [] }, { "id": "3", "name": "Laptop 13 inch 16GB", "sku": "L2201316", "stockLevel": "IN_STOCK", "currencyCode": "USD", "price": 219900, "priceWithTax": 263880, "featuredAsset": null, "assets": [] }, { "id": "4", "name": "Laptop 15 inch 16GB", "sku": "L2201516", "stockLevel": "IN_STOCK", "currencyCode": "USD", "price": 229900, "priceWithTax": 275880, "featuredAsset": null, "assets": [] } ] } } } ``` </TabItem> </Tabs> This single query provides all the data we need to display our PDP. ## Formatting prices As explained in the [Money & Currency guide](/guides/core-concepts/money/), the prices are returned as integers in the smallest unit of the currency (e.g. cents for USD). Therefore, when we display the price, we need to divide by 100 and format it according to the currency's formatting rules. In the demo at the end of this guide, we'll use the [`formatCurrency` function](/guides/core-concepts/money/#displaying-monetary-values) which makes use of the browser's `Intl` API to format the price according to the user's locale. ## Displaying images If we are using the [`AssetServerPlugin`](/reference/core-plugins/asset-server-plugin/) to serve our product images (as is the default), then we can take advantage of the dynamic image transformation abilities in order to display the product images in the correct size and in and optimized format such as WebP. This is done by appending a query string to the image URL. For example, if we want to use the `'large'` size preset (800 x 800) and convert the format to WebP, we'd use a url like this: ```tsx <img src={product.featuredAsset.preview + '?preset=large&format=webp'} /> ``` An even more sophisticated approach would be to make use of the HTML [`<picture>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) to provide multiple image sources so that the browser can select the optimal format. This can be wrapped in a component to make it easier to use. For example: ```tsx title="src/components/VendureAsset.tsx" interface VendureAssetProps { preview: string; preset: 'tiny' | 'thumb' | 'small' | 'medium' | 'large'; alt: string; } export function VendureAsset({ preview, preset, alt }: VendureAssetProps) { return ( <picture> <source type="image/avif" srcSet={preview + `?preset=${preset}&format=avif`} /> <source type="image/webp" srcSet={preview + `?preset=${preset}&format=webp`} /> <img src={preview + `?preset=${preset}&format=jpg`} alt={alt} /> </picture> ); } ``` ## Adding to the order To add a particular product variant to the order, we need to call the [`addItemToOrder`](/reference/graphql-api/shop/mutations/#additemtoorder) mutation. This mutation takes the `productVariantId` and the `quantity` as arguments. <Tabs> <TabItem value="Mutation" label="Mutation" default> ```graphql mutation AddItemToOrder($variantId: ID!, $quantity: Int!) { addItemToOrder(productVariantId: $variantId, quantity: $quantity) { __typename ...UpdatedOrder ... on ErrorResult { errorCode message } ... on InsufficientStockError { quantityAvailable order { ...UpdatedOrder } } } } fragment UpdatedOrder on Order { id code state totalQuantity totalWithTax currencyCode lines { id unitPriceWithTax quantity linePriceWithTax productVariant { id name } } } ``` </TabItem> <TabItem value="Variables" label="Variables"> ```json { "variantId": "4", "quantity": 1 } ``` </TabItem> <TabItem value="Response" label="Response" > ```json { "data": { "addItemToOrder": { "__typename": "Order", "id": "5", "code": "KE5FJPVV3Y3LX134", "state": "AddingItems", "totalQuantity": 1, "totalWithTax": 275880, "lines": [ { "id": "14", "unitPriceWithTax": 275880, "quantity": 1, "linePriceWithTax": 275880 } ] } } } ``` </TabItem> </Tabs> There are some important things to note about this mutation: - Because the `addItemToOrder` mutation returns a union type, we need to use a [fragment](/guides/getting-started/graphql-intro/#fragments) to specify the fields we want to return. In this case we have defined a fragment called `UpdatedOrder` which contains the fields we are interested in. - If any [expected errors](/guides/developer-guide/error-handling/) occur, the mutation will return an `ErrorResult` object. We'll be able to see the `errorCode` and `message` fields in the response, so that we can display a meaningful error message to the user. - In the special case of the `InsufficientStockError`, in addition to the `errorCode` and `message` fields, we also get the `quantityAvailable` field which tells us how many of the requested quantity are available (and have been added to the order). This is useful information to display to the user. The `InsufficientStockError` object also embeds the updated `Order` object, which we can use to update the UI. - The `__typename` field can be used by the client to determine which type of object has been returned. Its value will equal the name of the returned type. This means that we can check whether `__typename === 'Order'` in order to determine whether the mutation was successful. ## Live example Here's an example that brings together all of the above concepts: <Stackblitz id="vendure-docs-product-detail" />
--- title: "Storefront Starters" --- Since building an entire Storefront from scratch can be a daunting task, we have prepared a few starter projects that you can use as a base for your own storefront. These starters provide basic functionality including: - Product listing - Product details - Search with facets - Cart functionality - Checkout flow - Account management - Styling with Tailwind The idea is that you clone the starter project and then customize it to your needs. :::note Prefer to build your own solution? Follow the rest of the guides in this section to learn how to build a Storefront from scratch. ::: ## Remix Storefront - πŸ”— [remix-storefront.vendure.io](https://remix-storefront.vendure.io/) - πŸ’» [github.com/vendure-ecommerce/storefront-remix-starter](https://github.com/vendure-ecommerce/storefront-remix-starter) [Remix](https://remix.run/) is a React-based full-stack JavaScript framework which focuses on web standards, modern web app UX, and which helps you build better websites. Our official Remix Storefront starter provides you with a lightning-fast, modern storefront solution which can be deployed to any of the popular cloud providers like Vercel, Netlify, or Cloudflare Pages. ![Remix Storefront](./remix-storefront.webp) ## Qwik Storefront - πŸ”— [qwik-storefront.vendure.io](https://qwik-storefront.vendure.io/) - πŸ’» [github.com/vendure-ecommerce/storefront-qwik-starter](https://github.com/vendure-ecommerce/storefront-qwik-starter) [Qwik](https://qwik.builder.io/) is a cutting-edge web framework that offers unmatched performance. Our official Qwik Storefront starter provides you with a lightning-fast, modern storefront solution which can be deployed to any of the popular cloud providers like Vercel, Netlify, or Cloudflare Pages. ![Qwik Storefront](./qwik-storefront.webp) ## Angular Storefront - πŸ”— [angular-storefront.vendure.io](https://angular-storefront.vendure.io/) - πŸ’» [github.com/vendure-ecommerce/storefront-angular-starter](https://github.com/vendure-ecommerce/storefront-angular-starter) [Angular](https://angular.io/) is a popular, stable, enterprise-grade framework made by Google. Our official Angular Storefront starter is a modern Progressive Web App that uses Angular Universal server-side rendering. ![Angular Storefront](./angular-storefront.webp)
--- title: "Vendure API Reference" --- This section contains reference documentation for the various APIs exposed by Vendure. :::info All of the information in this section is generated directly from the Vendure source code. You can jump directly to the source file using the links below each heading. ![Source links](./links.webp) ::: ### TypeScript API These are the classes, interfaces and other TypeScript object which are used when **writing plugins** or custom business logic. ### Core Plugins These are the TypeScript APIs for the core Vendure plugins. ### GraphQL API These are the GraphQL APIs you will use to build your storefront (Shop API) or admin integrations (Admin API). ### Admin UI API These are the Angular components and services you can use when building Admin UI extensions.