content
stringlengths
29
370k
--- title: "ErrorHandlerStrategy" 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'; ## ErrorHandlerStrategy <GenerationInfo sourceFile="packages/core/src/config/system/error-handler-strategy.ts" sourceLine="60" packageName="@vendure/core" since="2.2.0" /> This strategy defines logic for handling errors thrown during on both the server and the worker. It can be used for additional logging & monitoring, or for sending error reports to external services. :::info This is configured via the `systemOptions.errorHandlers` property of your VendureConfig. ::: *Example* ```ts import { ArgumentsHost, ExecutionContext } from '@nestjs/common'; import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql'; import { ErrorHandlerStrategy, I18nError, Injector, Job, LogLevel } from '@vendure/core'; import { MonitoringService } from './monitoring.service'; export class CustomErrorHandlerStrategy implements ErrorHandlerStrategy { private monitoringService: MonitoringService; init(injector: Injector) { this.monitoringService = injector.get(MonitoringService); } handleServerError(error: Error, { host }: { host: ArgumentsHost }) { const errorContext: any = {}; if (host?.getType<GqlContextType>() === 'graphql') { const gqlContext = GqlExecutionContext.create(host as ExecutionContext); const info = gqlContext.getInfo(); errorContext.graphQlInfo = { fieldName: info.fieldName, path: info.path, }; } this.monitoringService.captureException(error, errorContext); } handleWorkerError(error: Error, { job }: { job: Job }) { const errorContext = { queueName: job.queueName, jobId: job.id, }; this.monitoringService.captureException(error, errorContext); } } ``` ```ts title="Signature" interface ErrorHandlerStrategy extends InjectableStrategy { handleServerError(exception: Error, context: { host: ArgumentsHost }): void | Promise<void>; handleWorkerError(exception: Error, context: { job: Job }): void | Promise<void>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### handleServerError <MemberInfo kind="method" type={`(exception: Error, context: { host: ArgumentsHost }) => void | Promise&#60;void&#62;`} /> This method will be invoked for any error thrown during the execution of the server. ### handleWorkerError <MemberInfo kind="method" type={`(exception: Error, context: { job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a> }) => void | Promise&#60;void&#62;`} /> This method will be invoked for any error thrown during the execution of a job on the worker. </div>
--- title: "ErrorResultUnion" 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'; ## ErrorResultUnion <GenerationInfo sourceFile="packages/core/src/common/error/error-result.ts" sourceLine="44" packageName="@vendure/core" /> Used to construct a TypeScript return type for a query or mutation which, in the GraphQL schema, returns a union type composed of a success result (e.g. Order) plus one or more ErrorResult types. Since the TypeScript entities do not correspond 1-to-1 with their GraphQL type counterparts, we use this type to substitute them. *Example* ```ts type UpdateOrderItemsResult = Order | OrderModificationError | OrderLimitError | NegativeQuantityError; type T1 = ErrorResultUnion<UpdateOrderItemsResult, VendureEntityOrder>; // T1 = VendureEntityOrder | OrderModificationError | OrderLimitError | NegativeQuantityError; ``` ```ts title="Signature" type ErrorResultUnion<T extends GraphQLErrorResult | U, E extends VendureEntity, U = any> = | JustErrorResults<T> | E ```
--- title: "Error Types" 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'; ## InternalServerError <GenerationInfo sourceFile="packages/core/src/common/error/errors.ts" sourceLine="14" packageName="@vendure/core" /> This error should be thrown when some unexpected and exceptional case is encountered. ```ts title="Signature" class InternalServerError extends I18nError { constructor(message: string, variables: { [key: string]: string | number } = {}) } ``` * Extends: <code><a href='/reference/typescript-api/errors/i18n-error#i18nerror'>I18nError</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(message: string, variables: { [key: string]: string | number } = {}) => InternalServerError`} /> </div> ## UserInputError <GenerationInfo sourceFile="packages/core/src/common/error/errors.ts" sourceLine="27" packageName="@vendure/core" /> This error should be thrown when user input is not as expected. ```ts title="Signature" class UserInputError extends I18nError { constructor(message: string, variables: { [key: string]: string | number } = {}) } ``` * Extends: <code><a href='/reference/typescript-api/errors/i18n-error#i18nerror'>I18nError</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(message: string, variables: { [key: string]: string | number } = {}) => UserInputError`} /> </div> ## IllegalOperationError <GenerationInfo sourceFile="packages/core/src/common/error/errors.ts" sourceLine="40" packageName="@vendure/core" /> This error should be thrown when an operation is attempted which is not allowed. ```ts title="Signature" class IllegalOperationError extends I18nError { constructor(message: string, variables: { [key: string]: string | number } = {}) } ``` * Extends: <code><a href='/reference/typescript-api/errors/i18n-error#i18nerror'>I18nError</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(message: string, variables: { [key: string]: string | number } = {}) => IllegalOperationError`} /> </div> ## UnauthorizedError <GenerationInfo sourceFile="packages/core/src/common/error/errors.ts" sourceLine="53" packageName="@vendure/core" /> This error should be thrown when the user's authentication credentials do not match. ```ts title="Signature" class UnauthorizedError extends I18nError { constructor() } ``` * Extends: <code><a href='/reference/typescript-api/errors/i18n-error#i18nerror'>I18nError</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`() => UnauthorizedError`} /> </div> ## ForbiddenError <GenerationInfo sourceFile="packages/core/src/common/error/errors.ts" sourceLine="67" packageName="@vendure/core" /> This error should be thrown when a user attempts to access a resource which is outside of his or her privileges. ```ts title="Signature" class ForbiddenError extends I18nError { constructor(logLevel: LogLevel = LogLevel.Warn) } ``` * Extends: <code><a href='/reference/typescript-api/errors/i18n-error#i18nerror'>I18nError</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(logLevel: <a href='/reference/typescript-api/logger/log-level#loglevel'>LogLevel</a> = LogLevel.Warn) => ForbiddenError`} /> </div> ## ChannelNotFoundError <GenerationInfo sourceFile="packages/core/src/common/error/errors.ts" sourceLine="81" packageName="@vendure/core" /> This error should be thrown when a <a href='/reference/typescript-api/entities/channel#channel'>Channel</a> cannot be found based on the provided channel token. ```ts title="Signature" class ChannelNotFoundError extends I18nError { constructor(token: string) } ``` * Extends: <code><a href='/reference/typescript-api/errors/i18n-error#i18nerror'>I18nError</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(token: string) => ChannelNotFoundError`} /> </div> ## EntityNotFoundError <GenerationInfo sourceFile="packages/core/src/common/error/errors.ts" sourceLine="95" packageName="@vendure/core" /> This error should be thrown when an entity cannot be found in the database, i.e. no entity of the given entityName (Product, User etc.) exists with the provided id. ```ts title="Signature" class EntityNotFoundError extends I18nError { constructor(entityName: keyof typeof coreEntitiesMap | string, id: ID) } ``` * Extends: <code><a href='/reference/typescript-api/errors/i18n-error#i18nerror'>I18nError</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(entityName: keyof typeof coreEntitiesMap | string, id: <a href='/reference/typescript-api/common/id#id'>ID</a>) => EntityNotFoundError`} /> </div>
--- title: "I18nError" 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'; ## I18nError <GenerationInfo sourceFile="packages/core/src/i18n/i18n-error.ts" sourceLine="18" packageName="@vendure/core" /> All errors thrown in the Vendure server must use or extend this error class. This allows the error message to be translated before being served to the client. The error messages should be provided in the form of a string key which corresponds to a key defined in the `i18n/messages/<languageCode>.json` files. Note that this class should not be directly used in code, but should be extended by a more specific Error class. ```ts title="Signature" class I18nError extends GraphQLError { constructor(message: string, variables: { [key: string]: string | number } = {}, code?: string, logLevel: LogLevel = LogLevel.Warn) } ``` * Extends: <code>GraphQLError</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(message: string, variables: { [key: string]: string | number } = {}, code?: string, logLevel: <a href='/reference/typescript-api/logger/log-level#loglevel'>LogLevel</a> = LogLevel.Warn) => I18nError`} /> </div>
--- title: "Errors" 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: "IsGraphQlErrorResult" 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'; ## isGraphQlErrorResult <GenerationInfo sourceFile="packages/core/src/common/error/error-result.ts" sourceLine="71" packageName="@vendure/core" /> Returns true if the <a href='/reference/typescript-api/errors/error-result-union#errorresultunion'>ErrorResultUnion</a> is actually an ErrorResult type. This is useful when dealing with certain internal service method that return an ErrorResultUnion. *Example* ```ts import { isGraphQlErrorResult } from '@vendure/core'; // ... 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; } ``` ```ts title="Signature" function isGraphQlErrorResult<T extends GraphQLErrorResult | U, U = any>(input: T): input is JustErrorResults<T> ``` Parameters ### input <MemberInfo kind="parameter" type={`T`} />
--- title: "Events" weight: 10 date: 2023-07-14T16:57:50.050Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # events
--- title: "BlockingEventHandlerOptions" 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'; ## BlockingEventHandlerOptions <GenerationInfo sourceFile="packages/core/src/event-bus/event-bus.ts" sourceLine="22" packageName="@vendure/core" since="2.2.0" /> Options for registering a blocking event handler. ```ts title="Signature" type BlockingEventHandlerOptions<T extends VendureEvent> = { event: Type<T> | Array<Type<T>>; handler: (event: T) => void | Promise<void>; id: string; before?: string; after?: string; } ``` <div className="members-wrapper"> ### event <MemberInfo kind="property" type={`Type&#60;T&#62; | Array&#60;Type&#60;T&#62;&#62;`} /> The event type to which the handler should listen. Can be a single event type or an array of event types. ### handler <MemberInfo kind="property" type={`(event: T) =&#62; void | Promise&#60;void&#62;`} /> The handler function which will be executed when the event is published. If the handler returns a Promise, the event publishing code will wait for the Promise to resolve before continuing. Any errors thrown by the handler will cause the event publishing code to fail. ### id <MemberInfo kind="property" type={`string`} /> A unique identifier for the handler. This can then be used to specify the order in which handlers should be executed using the `before` and `after` options in other handlers. ### before <MemberInfo kind="property" type={`string`} /> The ID of another handler which this handler should execute before. ### after <MemberInfo kind="property" type={`string`} /> The ID of another handler which this handler should execute after. </div>
--- title: "EventBus" 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'; ## EventBus <GenerationInfo sourceFile="packages/core/src/event-bus/event-bus.ts" sourceLine="97" packageName="@vendure/core" /> The EventBus is used to globally publish events which can then be subscribed to. Events are published whenever certain actions take place within the Vendure server, for example: * when a Product is updated (<a href='/reference/typescript-api/events/event-types#productevent'>ProductEvent</a>) * when an Order transitions state (<a href='/reference/typescript-api/events/event-types#orderstatetransitionevent'>OrderStateTransitionEvent</a>) * when a Customer registers a new account (<a href='/reference/typescript-api/events/event-types#accountregistrationevent'>AccountRegistrationEvent</a>) Using the EventBus it is possible to subscribe to an take action when these events occur. This is done with the `.ofType()` method, which takes an event type and returns an rxjs observable stream of events: *Example* ```ts import { OnApplicationBootstrap } from '@nestjs/common'; import { EventBus, PluginCommonModule, VendurePlugin } from '@vendure/core'; import { filter } from 'rxjs/operators'; @VendurePlugin({ imports: [PluginCommonModule] }) export class MyPlugin implements OnApplicationBootstrap { constructor(private eventBus: EventBus) {} async onApplicationBootstrap() { this.eventBus .ofType(OrderStateTransitionEvent) .pipe( filter(event => event.toState === 'PaymentSettled'), ) .subscribe((event) => { // do some action when this event fires }); } } ``` ```ts title="Signature" class EventBus implements OnModuleDestroy { constructor(transactionSubscriber: TransactionSubscriber) publish(event: T) => Promise<void>; ofType(type: Type<T>) => Observable<T>; filter(predicate: (event: VendureEvent) => boolean) => Observable<T>; registerBlockingEventHandler(handlerOptions: BlockingEventHandlerOptions<T>) => ; } ``` * Implements: <code>OnModuleDestroy</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(transactionSubscriber: TransactionSubscriber) => EventBus`} /> ### publish <MemberInfo kind="method" type={`(event: T) => Promise&#60;void&#62;`} /> Publish an event which any subscribers can react to. *Example* ```ts await eventBus.publish(new SomeEvent()); ``` ### ofType <MemberInfo kind="method" type={`(type: Type&#60;T&#62;) => Observable&#60;T&#62;`} /> Returns an RxJS Observable stream of events of the given type. If the event contains a <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a> object, the subscriber will only get called after any active database transactions are complete. This means that the subscriber function can safely access all updated data related to the event. ### filter <MemberInfo kind="method" type={`(predicate: (event: <a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a>) =&#62; boolean) => Observable&#60;T&#62;`} /> Returns an RxJS Observable stream of events filtered by a custom predicate. If the event contains a <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a> object, the subscriber will only get called after any active database transactions are complete. This means that the subscriber function can safely access all updated data related to the event. ### registerBlockingEventHandler <MemberInfo kind="method" type={`(handlerOptions: <a href='/reference/typescript-api/events/blocking-event-handler-options#blockingeventhandleroptions'>BlockingEventHandlerOptions</a>&#60;T&#62;) => `} since="2.2.0" /> Register an event handler function which will be executed when an event of the given type is published, and will block execution of the code which published the event until the handler has completed. This is useful when you need assurance that the event handler has successfully completed, and you want the triggering code to fail if the handler fails. ::: warning This API should be used with caution, as errors or performance issues in the handler can cause the associated operation to be slow or fail entirely. For this reason, any handler which takes longer than 100ms to execute will log a warning. Any non-trivial task to be performed in a blocking event handler should be offloaded to a background job using the <a href='/reference/typescript-api/job-queue/job-queue-service#jobqueueservice'>JobQueueService</a>. Also, be aware that the handler will be executed in the _same database transaction_ as the code which published the event (as long as you pass the `ctx` object from the event to any TransactionalConnection calls). ::: *Example* ```ts eventBus.registerBlockingEventHandler({ event: OrderStateTransitionEvent, id: 'my-order-state-transition-handler', handler: async (event) => { // perform some synchronous task } }); ``` </div>
--- title: "Event Types" 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'; ## AccountRegistrationEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/account-registration-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired when a new user registers an account, either as a stand-alone signup or after placing an order. ```ts title="Signature" class AccountRegistrationEvent extends VendureEvent { constructor(ctx: RequestContext, user: User) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, user: <a href='/reference/typescript-api/entities/user#user'>User</a>) => AccountRegistrationEvent`} /> </div> ## AccountVerifiedEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/account-verified-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired when a users email address successfully gets verified after the `verifyCustomerAccount` mutation was executed. ```ts title="Signature" class AccountVerifiedEvent extends VendureEvent { constructor(ctx: RequestContext, customer: Customer) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, customer: <a href='/reference/typescript-api/entities/customer#customer'>Customer</a>) => AccountVerifiedEvent`} /> </div> ## AdministratorEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/administrator-event.ts" sourceLine="18" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/administrator#administrator'>Administrator</a> is added, updated or deleted. ```ts title="Signature" class AdministratorEvent extends VendureEntityEvent<Administrator, AdministratorInputTypes> { constructor(ctx: RequestContext, entity: Administrator, type: 'created' | 'updated' | 'deleted', input?: AdministratorInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/administrator#administrator'>Administrator</a>, AdministratorInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/administrator#administrator'>Administrator</a>, type: 'created' | 'updated' | 'deleted', input?: AdministratorInputTypes) => AdministratorEvent`} /> </div> ## AssetChannelEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/asset-channel-event.ts" sourceLine="15" packageName="@vendure/core" /> This event is fired whenever an <a href='/reference/typescript-api/entities/asset#asset'>Asset</a> is assigned or removed From a channel. ```ts title="Signature" class AssetChannelEvent extends VendureEvent { constructor(ctx: RequestContext, asset: Asset, channelId: ID, type: 'assigned' | 'removed') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, asset: <a href='/reference/typescript-api/entities/asset#asset'>Asset</a>, channelId: <a href='/reference/typescript-api/common/id#id'>ID</a>, type: 'assigned' | 'removed') => AssetChannelEvent`} /> </div> ## AssetEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/asset-event.ts" sourceLine="18" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/asset#asset'>Asset</a> is added, updated or deleted. ```ts title="Signature" class AssetEvent extends VendureEntityEvent<Asset, AssetInputTypes> { constructor(ctx: RequestContext, entity: Asset, type: 'created' | 'updated' | 'deleted', input?: AssetInputTypes) asset: Asset } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/asset#asset'>Asset</a>, AssetInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/asset#asset'>Asset</a>, type: 'created' | 'updated' | 'deleted', input?: AssetInputTypes) => AssetEvent`} /> ### asset <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/asset#asset'>Asset</a>`} since="1.4" /> </div> ## AttemptedLoginEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/attempted-login-event.ts" sourceLine="14" packageName="@vendure/core" /> This event is fired when an attempt is made to log in via the shop or admin API `login` mutation. The `strategy` represents the name of the AuthenticationStrategy used in the login attempt. If the "native" strategy is used, the additional `identifier` property will be available. ```ts title="Signature" class AttemptedLoginEvent extends VendureEvent { constructor(ctx: RequestContext, strategy: string, identifier?: string) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, strategy: string, identifier?: string) => AttemptedLoginEvent`} /> </div> ## ChangeChannelEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/change-channel-event.ts" sourceLine="17" packageName="@vendure/core" since="1.4" /> This event is fired whenever an <a href='/reference/typescript-api/entities/interfaces#channelaware'>ChannelAware</a> entity is assigned or removed from a channel. The entity property contains the value before updating the channels. ```ts title="Signature" class ChangeChannelEvent<T extends ChannelAware & VendureEntity> extends VendureEvent { constructor(ctx: RequestContext, entity: T, channelIds: ID[], type: 'assigned' | 'removed', entityType?: Type<T>) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: T, channelIds: <a href='/reference/typescript-api/common/id#id'>ID</a>[], type: 'assigned' | 'removed', entityType?: Type&#60;T&#62;) => ChangeChannelEvent`} /> </div> ## ChannelEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/channel-event.ts" sourceLine="18" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/channel#channel'>Channel</a> is added, updated or deleted. ```ts title="Signature" class ChannelEvent extends VendureEntityEvent<Channel, ChannelInputTypes> { constructor(ctx: RequestContext, entity: Channel, type: 'created' | 'updated' | 'deleted', input?: ChannelInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/channel#channel'>Channel</a>, ChannelInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/channel#channel'>Channel</a>, type: 'created' | 'updated' | 'deleted', input?: ChannelInputTypes) => ChannelEvent`} /> </div> ## CollectionEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/collection-event.ts" sourceLine="18" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/collection#collection'>Collection</a> is added, updated or deleted. ```ts title="Signature" class CollectionEvent extends VendureEntityEvent<Collection, CollectionInputTypes> { constructor(ctx: RequestContext, entity: Collection, type: 'created' | 'updated' | 'deleted', input?: CollectionInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/collection#collection'>Collection</a>, CollectionInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/collection#collection'>Collection</a>, type: 'created' | 'updated' | 'deleted', input?: CollectionInputTypes) => CollectionEvent`} /> </div> ## CollectionModificationEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/collection-modification-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a Collection is modified in some way. The `productVariantIds` argument is an array of ids of all ProductVariants which: 1. were part of this collection prior to modification and are no longer 2. are now part of this collection after modification but were not before ```ts title="Signature" class CollectionModificationEvent extends VendureEvent { constructor(ctx: RequestContext, collection: Collection, productVariantIds: ID[]) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, collection: <a href='/reference/typescript-api/entities/collection#collection'>Collection</a>, productVariantIds: <a href='/reference/typescript-api/common/id#id'>ID</a>[]) => CollectionModificationEvent`} /> </div> ## CountryEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/country-event.ts" sourceLine="18" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/country#country'>Country</a> is added, updated or deleted. ```ts title="Signature" class CountryEvent extends VendureEntityEvent<Country, CountryInputTypes> { constructor(ctx: RequestContext, entity: Country, type: 'created' | 'updated' | 'deleted', input?: CountryInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/country#country'>Country</a>, CountryInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/country#country'>Country</a>, type: 'created' | 'updated' | 'deleted', input?: CountryInputTypes) => CountryEvent`} /> </div> ## CouponCodeEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/coupon-code-event.ts" sourceLine="15" packageName="@vendure/core" since="1.4" /> This event is fired whenever an coupon code of an active <a href='/reference/typescript-api/entities/promotion#promotion'>Promotion</a> is assigned or removed to an <a href='/reference/typescript-api/entities/order#order'>Order</a>. ```ts title="Signature" class CouponCodeEvent extends VendureEvent { constructor(ctx: RequestContext, couponCode: string, orderId: ID, type: 'assigned' | 'removed') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, couponCode: string, orderId: <a href='/reference/typescript-api/common/id#id'>ID</a>, type: 'assigned' | 'removed') => CouponCodeEvent`} /> </div> ## CustomerAddressEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/customer-address-event.ts" sourceLine="22" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/address#address'>Address</a> is added, updated or deleted. ```ts title="Signature" class CustomerAddressEvent extends VendureEntityEvent<Address, CustomerAddressInputTypes> { constructor(ctx: RequestContext, entity: Address, type: 'created' | 'updated' | 'deleted', input?: CustomerAddressInputTypes) address: Address } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/address#address'>Address</a>, CustomerAddressInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/address#address'>Address</a>, type: 'created' | 'updated' | 'deleted', input?: CustomerAddressInputTypes) => CustomerAddressEvent`} /> ### address <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/address#address'>Address</a>`} /> </div> ## CustomerEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/customer-event.ts" sourceLine="22" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/customer#customer'>Customer</a> is added, updated or deleted. ```ts title="Signature" class CustomerEvent extends VendureEntityEvent<Customer, CustomerInputTypes> { constructor(ctx: RequestContext, entity: Customer, type: 'created' | 'updated' | 'deleted', input?: CustomerInputTypes) customer: Customer } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/customer#customer'>Customer</a>, CustomerInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/customer#customer'>Customer</a>, type: 'created' | 'updated' | 'deleted', input?: CustomerInputTypes) => CustomerEvent`} /> ### customer <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/customer#customer'>Customer</a>`} since="1.4" /> </div> ## CustomerGroupChangeEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/customer-group-change-event.ts" sourceLine="15" packageName="@vendure/core" since="1.4" /> This event is fired whenever one or more <a href='/reference/typescript-api/entities/customer#customer'>Customer</a> is assigned to or removed from a <a href='/reference/typescript-api/entities/customer-group#customergroup'>CustomerGroup</a>. ```ts title="Signature" class CustomerGroupChangeEvent extends VendureEvent { constructor(ctx: RequestContext, customers: Customer[], customGroup: CustomerGroup, type: 'assigned' | 'removed') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, customers: <a href='/reference/typescript-api/entities/customer#customer'>Customer</a>[], customGroup: <a href='/reference/typescript-api/entities/customer-group#customergroup'>CustomerGroup</a>, type: 'assigned' | 'removed') => CustomerGroupChangeEvent`} /> </div> ## CustomerGroupEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/customer-group-event.ts" sourceLine="18" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/customer-group#customergroup'>CustomerGroup</a> is added, updated or deleted. ```ts title="Signature" class CustomerGroupEvent extends VendureEntityEvent<CustomerGroup, CustomerGroupInputTypes> { constructor(ctx: RequestContext, entity: CustomerGroup, type: 'created' | 'updated' | 'deleted', input?: CustomerGroupInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/customer-group#customergroup'>CustomerGroup</a>, CustomerGroupInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/customer-group#customergroup'>CustomerGroup</a>, type: 'created' | 'updated' | 'deleted', input?: CustomerGroupInputTypes) => CustomerGroupEvent`} /> </div> ## FacetEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/facet-event.ts" sourceLine="18" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/facet#facet'>Facet</a> is added, updated or deleted. ```ts title="Signature" class FacetEvent extends VendureEntityEvent<Facet, FacetInputTypes> { constructor(ctx: RequestContext, entity: Facet, type: 'created' | 'updated' | 'deleted', input?: FacetInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/facet#facet'>Facet</a>, FacetInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/facet#facet'>Facet</a>, type: 'created' | 'updated' | 'deleted', input?: FacetInputTypes) => FacetEvent`} /> </div> ## FacetValueEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/facet-value-event.ts" sourceLine="26" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/facet-value#facetvalue'>FacetValue</a> is added, updated or deleted. ```ts title="Signature" class FacetValueEvent extends VendureEntityEvent<FacetValue, FacetValueInputTypes> { constructor(ctx: RequestContext, entity: FacetValue, type: 'created' | 'updated' | 'deleted', input?: FacetValueInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/facet-value#facetvalue'>FacetValue</a>, FacetValueInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/facet-value#facetvalue'>FacetValue</a>, type: 'created' | 'updated' | 'deleted', input?: FacetValueInputTypes) => FacetValueEvent`} /> </div> ## FulfillmentEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/fulfillment-event.ts" sourceLine="27" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/fulfillment#fulfillment'>Fulfillment</a> is added. The type is always `created`. ```ts title="Signature" class FulfillmentEvent extends VendureEntityEvent<Fulfillment, CreateFulfillmentInput> { constructor(ctx: RequestContext, entity: Fulfillment, input?: CreateFulfillmentInput) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/fulfillment#fulfillment'>Fulfillment</a>, CreateFulfillmentInput&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/fulfillment#fulfillment'>Fulfillment</a>, input?: CreateFulfillmentInput) => FulfillmentEvent`} /> </div> ## FulfillmentStateTransitionEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/fulfillment-state-transition-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired whenever an <a href='/reference/typescript-api/entities/fulfillment#fulfillment'>Fulfillment</a> transitions from one <a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a> to another. ```ts title="Signature" class FulfillmentStateTransitionEvent extends VendureEvent { constructor(fromState: FulfillmentState, toState: FulfillmentState, ctx: RequestContext, fulfillment: Fulfillment) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(fromState: <a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a>, toState: <a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a>, ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, fulfillment: <a href='/reference/typescript-api/entities/fulfillment#fulfillment'>Fulfillment</a>) => FulfillmentStateTransitionEvent`} /> </div> ## GlobalSettingsEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/global-settings-event.ts" sourceLine="16" packageName="@vendure/core" since="1.4" /> This event is fired whenever a {@link GlobalSettings} is added. The type is always `updated`, because it's only created once and never deleted. ```ts title="Signature" class GlobalSettingsEvent extends VendureEntityEvent<GlobalSettings, UpdateGlobalSettingsInput> { constructor(ctx: RequestContext, entity: GlobalSettings, input?: UpdateGlobalSettingsInput) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;GlobalSettings, UpdateGlobalSettingsInput&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: GlobalSettings, input?: UpdateGlobalSettingsInput) => GlobalSettingsEvent`} /> </div> ## HistoryEntryEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/history-entry-event.ts" sourceLine="23" packageName="@vendure/core" since="1.4" /> This event is fired whenever one <a href='/reference/typescript-api/entities/history-entry#historyentry'>HistoryEntry</a> is added, updated or deleted. ```ts title="Signature" class HistoryEntryEvent extends VendureEntityEvent<HistoryEntry, HistoryInput> { public readonly historyType: 'order' | 'customer' | string; constructor(ctx: RequestContext, entity: HistoryEntry, type: 'created' | 'updated' | 'deleted', historyType: 'order' | 'customer' | string, input?: HistoryInput) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/history-entry#historyentry'>HistoryEntry</a>, HistoryInput&#62;</code> <div className="members-wrapper"> ### historyType <MemberInfo kind="property" type={`'order' | 'customer' | string`} /> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/history-entry#historyentry'>HistoryEntry</a>, type: 'created' | 'updated' | 'deleted', historyType: 'order' | 'customer' | string, input?: HistoryInput) => HistoryEntryEvent`} /> </div> ## IdentifierChangeEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/identifier-change-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired when a registered user successfully changes the identifier (ie email address) associated with their account. ```ts title="Signature" class IdentifierChangeEvent extends VendureEvent { constructor(ctx: RequestContext, user: User, oldIdentifier: string) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, user: <a href='/reference/typescript-api/entities/user#user'>User</a>, oldIdentifier: string) => IdentifierChangeEvent`} /> </div> ## IdentifierChangeRequestEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/identifier-change-request-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired when a registered user requests to update the identifier (ie email address) associated with the account. ```ts title="Signature" class IdentifierChangeRequestEvent extends VendureEvent { constructor(ctx: RequestContext, user: User) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, user: <a href='/reference/typescript-api/entities/user#user'>User</a>) => IdentifierChangeRequestEvent`} /> </div> ## InitializerEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/initializer-event.ts" sourceLine="11" packageName="@vendure/core" since="1.7.0" /> This event is fired when vendure finished initializing its services inside the {@code InitializerService} ```ts title="Signature" class InitializerEvent extends VendureEvent { constructor() } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`() => InitializerEvent`} /> </div> ## LoginEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/login-event.ts" sourceLine="12" packageName="@vendure/core" /> This event is fired when a user successfully logs in via the shop or admin API `login` mutation. ```ts title="Signature" class LoginEvent extends VendureEvent { constructor(ctx: RequestContext, user: User) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, user: <a href='/reference/typescript-api/entities/user#user'>User</a>) => LoginEvent`} /> </div> ## LogoutEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/logout-event.ts" sourceLine="12" packageName="@vendure/core" /> This event is fired when a user logs out via the shop or admin API `logout` mutation. ```ts title="Signature" class LogoutEvent extends VendureEvent { constructor(ctx: RequestContext) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>) => LogoutEvent`} /> </div> ## OrderEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/order-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired whenever an <a href='/reference/typescript-api/entities/order#order'>Order</a> is added, updated or deleted. ```ts title="Signature" class OrderEvent extends VendureEvent { constructor(ctx: RequestContext, order: Order, type: 'created' | 'updated' | 'deleted') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>, type: 'created' | 'updated' | 'deleted') => OrderEvent`} /> </div> ## OrderLineEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/order-line-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired whenever an <a href='/reference/typescript-api/entities/order-line#orderline'>OrderLine</a> is added, updated or deleted. ```ts title="Signature" class OrderLineEvent extends VendureEvent { constructor(ctx: RequestContext, order: Order, orderLine: OrderLine, type: 'created' | 'updated' | 'deleted') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>, orderLine: <a href='/reference/typescript-api/entities/order-line#orderline'>OrderLine</a>, type: 'created' | 'updated' | 'deleted') => OrderLineEvent`} /> </div> ## OrderPlacedEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/order-placed-event.ts" sourceLine="17" packageName="@vendure/core" /> This event is fired whenever an <a href='/reference/typescript-api/entities/order#order'>Order</a> is set as "placed", which by default is when it transitions from 'ArrangingPayment' to either 'PaymentAuthorized' or 'PaymentSettled'. Note that the exact point that it is set as "placed" can be configured according to the <a href='/reference/typescript-api/orders/order-placed-strategy#orderplacedstrategy'>OrderPlacedStrategy</a>. ```ts title="Signature" class OrderPlacedEvent extends VendureEvent { constructor(fromState: OrderState, toState: OrderState, ctx: RequestContext, order: Order) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(fromState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, toState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => OrderPlacedEvent`} /> </div> ## OrderStateTransitionEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/order-state-transition-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired whenever an <a href='/reference/typescript-api/entities/order#order'>Order</a> transitions from one <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a> to another. ```ts title="Signature" class OrderStateTransitionEvent extends VendureEvent { constructor(fromState: OrderState, toState: OrderState, ctx: RequestContext, order: Order) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(fromState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, toState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => OrderStateTransitionEvent`} /> </div> ## PasswordResetEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/password-reset-event.ts" sourceLine="12" packageName="@vendure/core" /> This event is fired when a Customer requests a password reset email. ```ts title="Signature" class PasswordResetEvent extends VendureEvent { constructor(ctx: RequestContext, user: User) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, user: <a href='/reference/typescript-api/entities/user#user'>User</a>) => PasswordResetEvent`} /> </div> ## PasswordResetVerifiedEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/password-reset-verified-event.ts" sourceLine="13" packageName="@vendure/core" since="1.4" /> This event is fired when a password reset is executed with a verified token. ```ts title="Signature" class PasswordResetVerifiedEvent extends VendureEvent { constructor(ctx: RequestContext, user: User) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, user: <a href='/reference/typescript-api/entities/user#user'>User</a>) => PasswordResetVerifiedEvent`} /> </div> ## PaymentMethodEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/payment-method-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/payment-method#paymentmethod'>PaymentMethod</a> is added, updated or deleted. ```ts title="Signature" class PaymentMethodEvent extends VendureEntityEvent<PaymentMethod, PaymentMethodInputTypes> { constructor(ctx: RequestContext, entity: PaymentMethod, type: 'created' | 'updated' | 'deleted', input?: PaymentMethodInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/payment-method#paymentmethod'>PaymentMethod</a>, PaymentMethodInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/payment-method#paymentmethod'>PaymentMethod</a>, type: 'created' | 'updated' | 'deleted', input?: PaymentMethodInputTypes) => PaymentMethodEvent`} /> </div> ## PaymentStateTransitionEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/payment-state-transition-event.ts" sourceLine="15" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/payment#payment'>Payment</a> transitions from one <a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a> to another, e.g. a Payment is authorized by the payment provider. ```ts title="Signature" class PaymentStateTransitionEvent extends VendureEvent { constructor(fromState: PaymentState, toState: PaymentState, ctx: RequestContext, payment: Payment, order: Order) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(fromState: <a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a>, toState: <a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a>, ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, payment: <a href='/reference/typescript-api/entities/payment#payment'>Payment</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => PaymentStateTransitionEvent`} /> </div> ## ProductChannelEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/product-channel-event.ts" sourceLine="15" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/product#product'>Product</a> is added, updated or deleted. ```ts title="Signature" class ProductChannelEvent extends VendureEvent { constructor(ctx: RequestContext, product: Product, channelId: ID, type: 'assigned' | 'removed') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, product: <a href='/reference/typescript-api/entities/product#product'>Product</a>, channelId: <a href='/reference/typescript-api/common/id#id'>ID</a>, type: 'assigned' | 'removed') => ProductChannelEvent`} /> </div> ## ProductEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/product-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/product#product'>Product</a> is added, updated or deleted. ```ts title="Signature" class ProductEvent extends VendureEntityEvent<Product, ProductInputTypes> { constructor(ctx: RequestContext, entity: Product, type: 'created' | 'updated' | 'deleted', input?: ProductInputTypes) product: Product } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/product#product'>Product</a>, ProductInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/product#product'>Product</a>, type: 'created' | 'updated' | 'deleted', input?: ProductInputTypes) => ProductEvent`} /> ### product <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/product#product'>Product</a>`} since="1.4" /> </div> ## ProductOptionEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/product-option-event.ts" sourceLine="26" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/product-option#productoption'>ProductOption</a> is added or updated. ```ts title="Signature" class ProductOptionEvent extends VendureEntityEvent<ProductOption, ProductOptionInputTypes> { constructor(ctx: RequestContext, entity: ProductOption, type: 'created' | 'updated' | 'deleted', input?: ProductOptionInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/product-option#productoption'>ProductOption</a>, ProductOptionInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/product-option#productoption'>ProductOption</a>, type: 'created' | 'updated' | 'deleted', input?: ProductOptionInputTypes) => ProductOptionEvent`} /> </div> ## ProductOptionGroupChangeEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/product-option-group-change-event.ts" sourceLine="15" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/product-option-group#productoptiongroup'>ProductOptionGroup</a> is assigned or removed from a <a href='/reference/typescript-api/entities/product#product'>Product</a>. ```ts title="Signature" class ProductOptionGroupChangeEvent extends VendureEvent { constructor(ctx: RequestContext, product: Product, optionGroupId: ID, type: 'assigned' | 'removed') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, product: <a href='/reference/typescript-api/entities/product#product'>Product</a>, optionGroupId: <a href='/reference/typescript-api/common/id#id'>ID</a>, type: 'assigned' | 'removed') => ProductOptionGroupChangeEvent`} /> </div> ## ProductOptionGroupEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/product-option-group-event.ts" sourceLine="24" packageName="@vendure/core" since="1.4" /> This event is fired whenever a <a href='/reference/typescript-api/entities/product-option-group#productoptiongroup'>ProductOptionGroup</a> is added or updated. ```ts title="Signature" class ProductOptionGroupEvent extends VendureEntityEvent< ProductOptionGroup, ProductOptionGroupInputTypes > { constructor(ctx: RequestContext, entity: ProductOptionGroup, type: 'created' | 'updated' | 'deleted', input?: ProductOptionGroupInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60; <a href='/reference/typescript-api/entities/product-option-group#productoptiongroup'>ProductOptionGroup</a>, ProductOptionGroupInputTypes &#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/product-option-group#productoptiongroup'>ProductOptionGroup</a>, type: 'created' | 'updated' | 'deleted', input?: ProductOptionGroupInputTypes) => ProductOptionGroupEvent`} /> </div> ## ProductVariantChannelEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/product-variant-channel-event.ts" sourceLine="14" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/product-variant#productvariant'>ProductVariant</a> is assigned or removed from a <a href='/reference/typescript-api/entities/channel#channel'>Channel</a>. ```ts title="Signature" class ProductVariantChannelEvent extends VendureEvent { constructor(ctx: RequestContext, productVariant: ProductVariant, channelId: ID, type: 'assigned' | 'removed') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, productVariant: <a href='/reference/typescript-api/entities/product-variant#productvariant'>ProductVariant</a>, channelId: <a href='/reference/typescript-api/common/id#id'>ID</a>, type: 'assigned' | 'removed') => ProductVariantChannelEvent`} /> </div> ## ProductVariantEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/product-variant-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/product-variant#productvariant'>ProductVariant</a> is added, updated or deleted. ```ts title="Signature" class ProductVariantEvent extends VendureEntityEvent<ProductVariant[], ProductVariantInputTypes> { constructor(ctx: RequestContext, entity: ProductVariant[], type: 'created' | 'updated' | 'deleted', input?: ProductVariantInputTypes) variants: ProductVariant[] } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/product-variant#productvariant'>ProductVariant</a>[], ProductVariantInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/product-variant#productvariant'>ProductVariant</a>[], type: 'created' | 'updated' | 'deleted', input?: ProductVariantInputTypes) => ProductVariantEvent`} /> ### variants <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/product-variant#productvariant'>ProductVariant</a>[]`} since="1.4" /> </div> ## ProductVariantPriceEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/product-variant-price-event.ts" sourceLine="17" packageName="@vendure/core" since="2.2.0" /> This event is fired whenever a <a href='/reference/typescript-api/entities/product-variant-price#productvariantprice'>ProductVariantPrice</a> is added, updated or deleted. ```ts title="Signature" class ProductVariantPriceEvent extends VendureEntityEvent< ProductVariantPrice[], ProductVariantInputTypes > { constructor(ctx: RequestContext, entity: ProductVariantPrice[], type: 'created' | 'updated' | 'deleted', input?: ProductVariantInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60; <a href='/reference/typescript-api/entities/product-variant-price#productvariantprice'>ProductVariantPrice</a>[], ProductVariantInputTypes &#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/product-variant-price#productvariantprice'>ProductVariantPrice</a>[], type: 'created' | 'updated' | 'deleted', input?: ProductVariantInputTypes) => ProductVariantPriceEvent`} /> </div> ## PromotionEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/promotion-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/promotion#promotion'>Promotion</a> is added, updated or deleted. ```ts title="Signature" class PromotionEvent extends VendureEntityEvent<Promotion, PromotionInputTypes> { constructor(ctx: RequestContext, entity: Promotion, type: 'created' | 'updated' | 'deleted', input?: PromotionInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/promotion#promotion'>Promotion</a>, PromotionInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/promotion#promotion'>Promotion</a>, type: 'created' | 'updated' | 'deleted', input?: PromotionInputTypes) => PromotionEvent`} /> </div> ## ProvinceEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/province-event.ts" sourceLine="18" packageName="@vendure/core" since="2.0" /> This event is fired whenever a <a href='/reference/typescript-api/entities/province#province'>Province</a> is added, updated or deleted. ```ts title="Signature" class ProvinceEvent extends VendureEntityEvent<Province, ProvinceInputTypes> { constructor(ctx: RequestContext, entity: Province, type: 'created' | 'updated' | 'deleted', input?: ProvinceInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/province#province'>Province</a>, ProvinceInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/province#province'>Province</a>, type: 'created' | 'updated' | 'deleted', input?: ProvinceInputTypes) => ProvinceEvent`} /> </div> ## RefundStateTransitionEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/refund-state-transition-event.ts" sourceLine="14" packageName="@vendure/core" /> This event is fired whenever a {@link Refund} transitions from one <a href='/reference/typescript-api/payment/refund-state#refundstate'>RefundState</a> to another. ```ts title="Signature" class RefundStateTransitionEvent extends VendureEvent { constructor(fromState: RefundState, toState: RefundState, ctx: RequestContext, refund: Refund, order: Order) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(fromState: <a href='/reference/typescript-api/payment/refund-state#refundstate'>RefundState</a>, toState: <a href='/reference/typescript-api/payment/refund-state#refundstate'>RefundState</a>, ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, refund: Refund, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => RefundStateTransitionEvent`} /> </div> ## RoleChangeEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/role-change-event.ts" sourceLine="16" packageName="@vendure/core" since="1.4" /> This event is fired whenever one <a href='/reference/typescript-api/entities/role#role'>Role</a> is assigned or removed from a user. The property `roleIds` only contains the removed or assigned role ids. ```ts title="Signature" class RoleChangeEvent extends VendureEvent { constructor(ctx: RequestContext, admin: Administrator, roleIds: ID[], type: 'assigned' | 'removed') } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, admin: <a href='/reference/typescript-api/entities/administrator#administrator'>Administrator</a>, roleIds: <a href='/reference/typescript-api/common/id#id'>ID</a>[], type: 'assigned' | 'removed') => RoleChangeEvent`} /> </div> ## RoleEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/role-event.ts" sourceLine="18" packageName="@vendure/core" since="1.4" /> This event is fired whenever one <a href='/reference/typescript-api/entities/role#role'>Role</a> is added, updated or deleted. ```ts title="Signature" class RoleEvent extends VendureEntityEvent<Role, RoleInputTypes> { constructor(ctx: RequestContext, entity: Role, type: 'created' | 'updated' | 'deleted', input?: RoleInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/role#role'>Role</a>, RoleInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/role#role'>Role</a>, type: 'created' | 'updated' | 'deleted', input?: RoleInputTypes) => RoleEvent`} /> </div> ## SearchEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/search-event.ts" sourceLine="18" packageName="@vendure/core" since="1.6.0" /> This event is fired whenever a search query is executed. ```ts title="Signature" class SearchEvent extends VendureEvent { constructor(ctx: RequestContext, input: ExtendedSearchInput) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, input: ExtendedSearchInput) => SearchEvent`} /> </div> ## SellerEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/seller-event.ts" sourceLine="19" packageName="@vendure/core" since="2.0.1" /> This event is fired whenever one <a href='/reference/typescript-api/entities/seller#seller'>Seller</a> is added, updated or deleted. ```ts title="Signature" class SellerEvent extends VendureEntityEvent<Seller, SellerInputTypes> { constructor(ctx: RequestContext, entity: Seller, type: 'created' | 'updated' | 'deleted', input?: SellerInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/seller#seller'>Seller</a>, SellerInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/seller#seller'>Seller</a>, type: 'created' | 'updated' | 'deleted', input?: SellerInputTypes) => SellerEvent`} /> </div> ## ShippingMethodEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/shipping-method-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/shipping-method#shippingmethod'>ShippingMethod</a> is added, updated or deleted. ```ts title="Signature" class ShippingMethodEvent extends VendureEntityEvent<ShippingMethod, ShippingMethodInputTypes> { constructor(ctx: RequestContext, entity: ShippingMethod, type: 'created' | 'updated' | 'deleted', input?: ShippingMethodInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/shipping-method#shippingmethod'>ShippingMethod</a>, ShippingMethodInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/shipping-method#shippingmethod'>ShippingMethod</a>, type: 'created' | 'updated' | 'deleted', input?: ShippingMethodInputTypes) => ShippingMethodEvent`} /> </div> ## StockMovementEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/stock-movement-event.ts" sourceLine="16" packageName="@vendure/core" since="1.1.0" /> This event is fired whenever a <a href='/reference/typescript-api/entities/stock-movement#stockmovement'>StockMovement</a> entity is created, which occurs when the saleable stock level of a ProductVariant is altered due to things like sales, manual adjustments, and cancellations. ```ts title="Signature" class StockMovementEvent extends VendureEvent { public readonly type: StockMovementType; constructor(ctx: RequestContext, stockMovements: StockMovement[]) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### type <MemberInfo kind="property" type={`StockMovementType`} /> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, stockMovements: <a href='/reference/typescript-api/entities/stock-movement#stockmovement'>StockMovement</a>[]) => StockMovementEvent`} /> </div> ## TaxCategoryEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/tax-category-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/tax-category#taxcategory'>TaxCategory</a> is added, updated or deleted. ```ts title="Signature" class TaxCategoryEvent extends VendureEntityEvent<TaxCategory, TaxCategoryInputTypes> { constructor(ctx: RequestContext, entity: TaxCategory, type: 'created' | 'updated' | 'deleted', input?: TaxCategoryInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/tax-category#taxcategory'>TaxCategory</a>, TaxCategoryInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/tax-category#taxcategory'>TaxCategory</a>, type: 'created' | 'updated' | 'deleted', input?: TaxCategoryInputTypes) => TaxCategoryEvent`} /> </div> ## TaxRateEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/tax-rate-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/tax-rate#taxrate'>TaxRate</a> is added, updated or deleted. ```ts title="Signature" class TaxRateEvent extends VendureEntityEvent<TaxRate, TaxRateInputTypes> { constructor(ctx: RequestContext, entity: TaxRate, type: 'created' | 'updated' | 'deleted', input?: TaxRateInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/tax-rate#taxrate'>TaxRate</a>, TaxRateInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/tax-rate#taxrate'>TaxRate</a>, type: 'created' | 'updated' | 'deleted', input?: TaxRateInputTypes) => TaxRateEvent`} /> </div> ## TaxRateModificationEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/tax-rate-modification-event.ts" sourceLine="13" packageName="@vendure/core" /> This event is fired whenever a TaxRate is changed ```ts title="Signature" class TaxRateModificationEvent extends VendureEvent { constructor(ctx: RequestContext, taxRate: TaxRate) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, taxRate: <a href='/reference/typescript-api/entities/tax-rate#taxrate'>TaxRate</a>) => TaxRateModificationEvent`} /> </div> ## ZoneEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/zone-event.ts" sourceLine="18" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/zone#zone'>Zone</a> is added, updated or deleted. ```ts title="Signature" class ZoneEvent extends VendureEntityEvent<Zone, ZoneInputTypes> { constructor(ctx: RequestContext, entity: Zone, type: 'created' | 'updated' | 'deleted', input?: ZoneInputTypes) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-entity-event#vendureentityevent'>VendureEntityEvent</a>&#60;<a href='/reference/typescript-api/entities/zone#zone'>Zone</a>, ZoneInputTypes&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/zone#zone'>Zone</a>, type: 'created' | 'updated' | 'deleted', input?: ZoneInputTypes) => ZoneEvent`} /> </div> ## ZoneMembersEvent <GenerationInfo sourceFile="packages/core/src/event-bus/events/zone-members-event.ts" sourceLine="15" packageName="@vendure/core" /> This event is fired whenever a <a href='/reference/typescript-api/entities/zone#zone'>Zone</a> gets <a href='/reference/typescript-api/entities/country#country'>Country</a> members assigned or removed The `entity` property contains the zone with the already updated member field. ```ts title="Signature" class ZoneMembersEvent extends VendureEvent { constructor(ctx: RequestContext, entity: Zone, type: 'assigned' | 'removed', memberIds: ID[]) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, entity: <a href='/reference/typescript-api/entities/zone#zone'>Zone</a>, type: 'assigned' | 'removed', memberIds: <a href='/reference/typescript-api/common/id#id'>ID</a>[]) => ZoneMembersEvent`} /> </div>
--- title: "Events" 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: "VendureEntityEvent" 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'; ## VendureEntityEvent <GenerationInfo sourceFile="packages/core/src/event-bus/vendure-entity-event.ts" sourceLine="12" packageName="@vendure/core" /> The base class for all entity events used by the EventBus system. * For event type `'deleted'` the input will most likely be an `id: ID` ```ts title="Signature" class VendureEntityEvent<Entity, Input = any> extends VendureEvent { public readonly entity: Entity; public readonly type: 'created' | 'updated' | 'deleted'; public readonly ctx: RequestContext; public readonly input?: Input; constructor(entity: Entity, type: 'created' | 'updated' | 'deleted', ctx: RequestContext, input?: Input) } ``` * Extends: <code><a href='/reference/typescript-api/events/vendure-event#vendureevent'>VendureEvent</a></code> <div className="members-wrapper"> ### entity <MemberInfo kind="property" type={`Entity`} /> ### type <MemberInfo kind="property" type={`'created' | 'updated' | 'deleted'`} /> ### ctx <MemberInfo kind="property" type={`<a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>`} /> ### input <MemberInfo kind="property" type={`Input`} /> ### constructor <MemberInfo kind="method" type={`(entity: Entity, type: 'created' | 'updated' | 'deleted', ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, input?: Input) => VendureEntityEvent`} /> </div>
--- title: "VendureEvent" 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'; ## VendureEvent <GenerationInfo sourceFile="packages/core/src/event-bus/vendure-event.ts" sourceLine="7" packageName="@vendure/core" /> The base class for all events used by the EventBus system. ```ts title="Signature" class VendureEvent { public readonly createdAt: Date; constructor() } ``` <div className="members-wrapper"> ### createdAt <MemberInfo kind="property" type={`Date`} /> ### constructor <MemberInfo kind="method" type={`() => VendureEvent`} /> </div>
--- title: "Fulfillment" weight: 10 date: 2023-07-14T16:57:49.549Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # fulfillment
--- title: "FulfillmentHandler" 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'; ## FulfillmentHandler <GenerationInfo sourceFile="packages/core/src/config/fulfillment/fulfillment-handler.ts" sourceLine="149" packageName="@vendure/core" /> A FulfillmentHandler is used when creating a new <a href='/reference/typescript-api/entities/fulfillment#fulfillment'>Fulfillment</a>. When the `addFulfillmentToOrder` mutation is executed, the specified handler will be used and it's `createFulfillment` method is called. This method may perform async tasks such as calling a 3rd-party shipping API to register a new shipment and receive a tracking code. This data can then be returned and will be incorporated into the created Fulfillment. If the `args` property is defined, this means that arguments passed to the `addFulfillmentToOrder` mutation will be passed through to the `createFulfillment` method as the last argument. *Example* ```ts let shipomatic; export const shipomaticFulfillmentHandler = new FulfillmentHandler({ code: 'ship-o-matic', description: [{ languageCode: LanguageCode.en, value: 'Generate tracking codes via the Ship-o-matic API' }], args: { preferredService: { type: 'string', ui: { component: 'select-form-input', options: [ { value: 'first_class' }, { value: 'priority'}, { value: 'standard' }, ], }, } }, init: () => { // some imaginary shipping service shipomatic = new ShipomaticClient(API_KEY); }, createFulfillment: async (ctx, orders, lines, args) => { const shipment = getShipmentFromOrders(orders, lines); try { const transaction = await shipomatic.transaction.create({ shipment, service_level: args.preferredService, label_file_type: 'png', }) return { method: `Ship-o-matic ${args.preferredService}`, trackingCode: transaction.tracking_code, customFields: { shippingTransactionId: transaction.id, } }; } catch (e: any) { // Errors thrown from within this function will // result in a CreateFulfillmentError being returned throw e; } }, onFulfillmentTransition: async (fromState, toState, { fulfillment }) => { if (toState === 'Cancelled') { await shipomatic.transaction.cancel({ transaction_id: fulfillment.customFields.shippingTransactionId, }); } } }); ``` ```ts title="Signature" class FulfillmentHandler<T extends ConfigArgs = ConfigArgs> extends ConfigurableOperationDef<T> { constructor(config: FulfillmentHandlerConfig<T>) } ``` * Extends: <code><a href='/reference/typescript-api/configurable-operation-def/#configurableoperationdef'>ConfigurableOperationDef</a>&#60;T&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(config: <a href='/reference/typescript-api/fulfillment/fulfillment-handler#fulfillmenthandlerconfig'>FulfillmentHandlerConfig</a>&#60;T&#62;) => FulfillmentHandler`} /> </div> ## FulfillmentHandlerConfig <GenerationInfo sourceFile="packages/core/src/config/fulfillment/fulfillment-handler.ts" sourceLine="48" packageName="@vendure/core" /> The configuration object used to instantiate a <a href='/reference/typescript-api/fulfillment/fulfillment-handler#fulfillmenthandler'>FulfillmentHandler</a>. ```ts title="Signature" interface FulfillmentHandlerConfig<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { createFulfillment: CreateFulfillmentFn<T>; onFulfillmentTransition?: OnTransitionStartFn<FulfillmentState, FulfillmentTransitionData>; } ``` * Extends: <code><a href='/reference/typescript-api/configurable-operation-def/configurable-operation-def-options#configurableoperationdefoptions'>ConfigurableOperationDefOptions</a>&#60;T&#62;</code> <div className="members-wrapper"> ### createFulfillment <MemberInfo kind="property" type={`<a href='/reference/typescript-api/fulfillment/fulfillment-handler#createfulfillmentfn'>CreateFulfillmentFn</a>&#60;T&#62;`} /> Invoked when the `addFulfillmentToOrder` mutation is executed with this handler selected. If an Error is thrown from within this function, no Fulfillment is created and the `CreateFulfillmentError` result will be returned. ### onFulfillmentTransition <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/state-machine-config#ontransitionstartfn'>OnTransitionStartFn</a>&#60;<a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a>, <a href='/reference/typescript-api/fulfillment/fulfillment-transition-data#fulfillmenttransitiondata'>FulfillmentTransitionData</a>&#62;`} /> This allows the handler to intercept state transitions of the created Fulfillment. This works much in the same way as the {@link CustomFulfillmentProcess} `onTransitionStart` method (i.e. returning `false` or `string` will be interpreted as an error and prevent the state transition), except that it is only invoked on Fulfillments which were created with this particular FulfillmentHandler. It can be useful e.g. to intercept Fulfillment cancellations and relay that information to a 3rd-party shipping API. </div> ## CreateFulfillmentFn <GenerationInfo sourceFile="packages/core/src/config/fulfillment/fulfillment-handler.ts" sourceLine="33" packageName="@vendure/core" /> The function called when creating a new Fulfillment ```ts title="Signature" type CreateFulfillmentFn<T extends ConfigArgs> = ( ctx: RequestContext, orders: Order[], lines: OrderLineInput[], args: ConfigArgValues<T>, ) => CreateFulfillmentResult | Promise<CreateFulfillmentResult> ``` ## CreateFulfillmentResult <GenerationInfo sourceFile="packages/core/src/config/fulfillment/fulfillment-handler.ts" sourceLine="23" packageName="@vendure/core" /> ```ts title="Signature" type CreateFulfillmentResult = Partial<Pick<Fulfillment, 'trackingCode' | 'method' | 'customFields'>> ```
--- title: "FulfillmentProcess" 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'; ## defaultFulfillmentProcess <GenerationInfo sourceFile="packages/core/src/config/fulfillment/default-fulfillment-process.ts" sourceLine="45" packageName="@vendure/core" since="2.0.0" /> The default <a href='/reference/typescript-api/fulfillment/fulfillment-process#fulfillmentprocess'>FulfillmentProcess</a>. This process includes the following actions: - Executes the configured `FulfillmentHandler.onFulfillmentTransition()` before any state transition. - On cancellation of a Fulfillment, creates the necessary <a href='/reference/typescript-api/entities/stock-movement#cancellation'>Cancellation</a> & <a href='/reference/typescript-api/entities/stock-movement#allocation'>Allocation</a> stock movement records. - When a Fulfillment transitions from the `Created` to `Pending` state, the necessary <a href='/reference/typescript-api/entities/stock-movement#sale'>Sale</a> stock movements are created. ## FulfillmentProcess <GenerationInfo sourceFile="packages/core/src/config/fulfillment/fulfillment-process.ts" sourceLine="26" packageName="@vendure/core" since="2.0.0" /> A FulfillmentProcess is used to define the way the fulfillment process works as in: what states a Fulfillment can be in, and how it may transition from one state to another. Using the `onTransitionStart()` hook, a FulfillmentProcess can perform checks before allowing a state transition to occur, and the `onTransitionEnd()` hook allows logic to be executed after a state change. For detailed description of the interface members, see the <a href='/reference/typescript-api/state-machine/state-machine-config#statemachineconfig'>StateMachineConfig</a> docs. ```ts title="Signature" interface FulfillmentProcess<State extends keyof CustomFulfillmentStates | string> extends InjectableStrategy { transitions?: Transitions<State, State | FulfillmentState> & Partial<Transitions<FulfillmentState | State>>; onTransitionStart?: OnTransitionStartFn<State | FulfillmentState, FulfillmentTransitionData>; onTransitionEnd?: OnTransitionEndFn<State | FulfillmentState, FulfillmentTransitionData>; onTransitionError?: OnTransitionErrorFn<State | FulfillmentState>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### transitions <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/transitions#transitions'>Transitions</a>&#60;State, State | <a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a>&#62; &#38; Partial&#60;<a href='/reference/typescript-api/state-machine/transitions#transitions'>Transitions</a>&#60;<a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a> | State&#62;&#62;`} /> ### onTransitionStart <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/state-machine-config#ontransitionstartfn'>OnTransitionStartFn</a>&#60;State | <a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a>, <a href='/reference/typescript-api/fulfillment/fulfillment-transition-data#fulfillmenttransitiondata'>FulfillmentTransitionData</a>&#62;`} /> ### onTransitionEnd <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/state-machine-config#ontransitionendfn'>OnTransitionEndFn</a>&#60;State | <a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a>, <a href='/reference/typescript-api/fulfillment/fulfillment-transition-data#fulfillmenttransitiondata'>FulfillmentTransitionData</a>&#62;`} /> ### onTransitionError <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/state-machine-config#ontransitionerrorfn'>OnTransitionErrorFn</a>&#60;State | <a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a>&#62;`} /> </div>
--- title: "FulfillmentState" 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'; ## FulfillmentState <GenerationInfo sourceFile="packages/core/src/service/helpers/fulfillment-state-machine/fulfillment-state.ts" sourceLine="29" packageName="@vendure/core" /> These are the default states of the fulfillment process. By default, they will be extended by the <a href='/reference/typescript-api/fulfillment/fulfillment-process#defaultfulfillmentprocess'>defaultFulfillmentProcess</a> to also include `Shipped` and `Delivered`. ```ts title="Signature" type FulfillmentState = | 'Created' | 'Pending' | 'Cancelled' | keyof CustomFulfillmentStates | keyof FulfillmentStates ```
--- title: "FulfillmentStates" 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'; ## FulfillmentStates <GenerationInfo sourceFile="packages/core/src/service/helpers/fulfillment-state-machine/fulfillment-state.ts" sourceLine="19" packageName="@vendure/core" /> An interface to extend standard <a href='/reference/typescript-api/fulfillment/fulfillment-state#fulfillmentstate'>FulfillmentState</a>. ```ts title="Signature" interface FulfillmentStates { } ```
--- title: "FulfillmentTransitionData" 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'; ## FulfillmentTransitionData <GenerationInfo sourceFile="packages/core/src/service/helpers/fulfillment-state-machine/fulfillment-state.ts" sourceLine="42" packageName="@vendure/core" /> The data which is passed to the state transition handler of the FulfillmentStateMachine. ```ts title="Signature" interface FulfillmentTransitionData { ctx: RequestContext; orders: Order[]; fulfillment: Fulfillment; } ``` <div className="members-wrapper"> ### ctx <MemberInfo kind="property" type={`<a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>`} /> ### orders <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/order#order'>Order</a>[]`} /> ### fulfillment <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/fulfillment#fulfillment'>Fulfillment</a>`} /> </div>
--- title: "Fulfillment" 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: "Health Check" weight: 10 date: 2023-07-14T16:57:49.709Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # health-check
--- title: "HealthCheckRegistryService" 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'; ## HealthCheckRegistryService <GenerationInfo sourceFile="packages/core/src/health-check/health-check-registry.service.ts" sourceLine="47" packageName="@vendure/core" /> This service is used to register health indicator functions to be included in the health check. Health checks can be used by automated services such as Kubernetes to determine the state of applications it is running. They are also useful for administrators to get an overview of the health of all the parts of the Vendure stack. It wraps the [Nestjs Terminus module](https://docs.nestjs.com/recipes/terminus), so see those docs for information on creating custom health checks. Plugins which rely on external services (web services, databases etc.) can make use of this service to add a check for that dependency to the Vendure health check. Since v1.6.0, the preferred way to implement a custom health check is by creating a new <a href='/reference/typescript-api/health-check/health-check-strategy#healthcheckstrategy'>HealthCheckStrategy</a> and then passing it to the `systemOptions.healthChecks` array. See the <a href='/reference/typescript-api/health-check/health-check-strategy#healthcheckstrategy'>HealthCheckStrategy</a> docs for an example configuration. The alternative way to register a health check is by injecting this service directly into your plugin module. To use it in your plugin, you'll need to import the <a href='/reference/typescript-api/plugin/plugin-common-module#plugincommonmodule'>PluginCommonModule</a>: *Example* ```ts import { HealthCheckRegistryService, PluginCommonModule, VendurePlugin } from '@vendure/core'; import { TerminusModule } from '@nestjs/terminus'; @VendurePlugin({ imports: [PluginCommonModule, TerminusModule], }) export class MyPlugin { constructor( private registry: HealthCheckRegistryService private httpIndicator: HttpHealthIndicator ) { registry.registerIndicatorFunction( () => this.httpIndicator.pingCheck('vendure-docs', 'https://www.vendure.io/docs/'), ) } } ``` ```ts title="Signature" class HealthCheckRegistryService { registerIndicatorFunction(fn: HealthIndicatorFunction | HealthIndicatorFunction[]) => ; } ``` <div className="members-wrapper"> ### registerIndicatorFunction <MemberInfo kind="method" type={`(fn: HealthIndicatorFunction | HealthIndicatorFunction[]) => `} /> Registers one or more `HealthIndicatorFunctions` (see [Nestjs docs](https://docs.nestjs.com/recipes/terminus#setting-up-a-healthcheck)) to be added to the health check endpoint. The indicator will also appear in the Admin UI's "system status" view. </div>
--- title: "HealthCheckStrategy" 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'; ## HealthCheckStrategy <GenerationInfo sourceFile="packages/core/src/config/system/health-check-strategy.ts" sourceLine="48" packageName="@vendure/core" /> This strategy defines health checks which are included as part of the `/health` endpoint. They should only be used to monitor _critical_ systems on which proper functioning of the Vendure server depends. For more information on the underlying mechanism, see the [NestJS Terminus module docs](https://docs.nestjs.com/recipes/terminus). Custom strategies should be added to the `systemOptions.healthChecks` array. By default, Vendure includes the `TypeORMHealthCheckStrategy`, so if you set the value of the `healthChecks` array, be sure to include it manually. Vendure also ships with the <a href='/reference/typescript-api/health-check/http-health-check-strategy#httphealthcheckstrategy'>HttpHealthCheckStrategy</a>, which is convenient for adding a health check dependent on an HTTP ping. :::info This is configured via the `systemOptions.healthChecks` property of your VendureConfig. ::: *Example* ```ts import { HttpHealthCheckStrategy, TypeORMHealthCheckStrategy } from '@vendure/core'; import { MyCustomHealthCheckStrategy } from './config/custom-health-check-strategy'; export const config = { // ... systemOptions: { healthChecks: [ new TypeORMHealthCheckStrategy(), new HttpHealthCheckStrategy({ key: 'my-service', url: 'https://my-service.com' }), new MyCustomHealthCheckStrategy(), ], }, }; ``` ```ts title="Signature" interface HealthCheckStrategy extends InjectableStrategy { getHealthIndicator(): HealthIndicatorFunction; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### getHealthIndicator <MemberInfo kind="method" type={`() => HealthIndicatorFunction`} /> Should return a `HealthIndicatorFunction`, as defined by the [NestJS Terminus module](https://docs.nestjs.com/recipes/terminus). </div>
--- title: "HttpHealthCheckStrategy" 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'; ## HttpHealthCheckStrategy <GenerationInfo sourceFile="packages/core/src/health-check/http-health-check-strategy.ts" sourceLine="37" packageName="@vendure/core" /> A <a href='/reference/typescript-api/health-check/health-check-strategy#healthcheckstrategy'>HealthCheckStrategy</a> used to check health by pinging a url. Internally it uses the [NestJS HttpHealthIndicator](https://docs.nestjs.com/recipes/terminus#http-healthcheck). *Example* ```ts import { HttpHealthCheckStrategy, TypeORMHealthCheckStrategy } from '@vendure/core'; export const config = { // ... systemOptions: { healthChecks: [ new TypeORMHealthCheckStrategy(), new HttpHealthCheckStrategy({ key: 'my-service', url: 'https://my-service.com' }), ] }, }; ``` ```ts title="Signature" class HttpHealthCheckStrategy implements HealthCheckStrategy { constructor(options: HttpHealthCheckOptions) init(injector: Injector) => ; getHealthIndicator() => HealthIndicatorFunction; } ``` * Implements: <code><a href='/reference/typescript-api/health-check/health-check-strategy#healthcheckstrategy'>HealthCheckStrategy</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(options: HttpHealthCheckOptions) => HttpHealthCheckStrategy`} /> ### init <MemberInfo kind="method" type={`(injector: <a href='/reference/typescript-api/common/injector#injector'>Injector</a>) => `} /> ### getHealthIndicator <MemberInfo kind="method" type={`() => HealthIndicatorFunction`} /> </div>
--- title: "Health Check" 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: "TypeORMHealthCheckStrategy" 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'; ## TypeORMHealthCheckStrategy <GenerationInfo sourceFile="packages/core/src/health-check/typeorm-health-check-strategy.ts" sourceLine="36" packageName="@vendure/core" /> A <a href='/reference/typescript-api/health-check/health-check-strategy#healthcheckstrategy'>HealthCheckStrategy</a> used to check the health of the database. This health check is included by default, but can be customized by explicitly adding it to the `systemOptions.healthChecks` array: *Example* ```ts import { TypeORMHealthCheckStrategy } from '@vendure/core'; export const config = { // ... systemOptions: [ // The default key is "database" and the default timeout is 1000ms // Sometimes this is too short and leads to false negatives in the // /health endpoint. new TypeORMHealthCheckStrategy({ key: 'postgres-db', timeout: 5000 }), ] } ``` ```ts title="Signature" class TypeORMHealthCheckStrategy implements HealthCheckStrategy { constructor(options?: TypeORMHealthCheckOptions) init(injector: Injector) => ; getHealthIndicator() => HealthIndicatorFunction; } ``` * Implements: <code><a href='/reference/typescript-api/health-check/health-check-strategy#healthcheckstrategy'>HealthCheckStrategy</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(options?: TypeORMHealthCheckOptions) => TypeORMHealthCheckStrategy`} /> ### init <MemberInfo kind="method" type={`(injector: <a href='/reference/typescript-api/common/injector#injector'>Injector</a>) => `} /> ### getHealthIndicator <MemberInfo kind="method" type={`() => HealthIndicatorFunction`} /> </div>
--- title: "Import Export" weight: 10 date: 2023-07-14T16:57:49.415Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # import-export
--- title: "AssetImportStrategy" 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'; ## AssetImportStrategy <GenerationInfo sourceFile="packages/core/src/config/asset-import-strategy/asset-import-strategy.ts" sourceLine="25" packageName="@vendure/core" since="1.7.0" /> The AssetImportStrategy determines how asset files get imported based on the path given in the import CSV or via the <a href='/reference/typescript-api/import-export/asset-importer#assetimporter'>AssetImporter</a> `getAssets()` method. The <a href='/reference/typescript-api/import-export/default-asset-import-strategy#defaultassetimportstrategy'>DefaultAssetImportStrategy</a> is able to load files from either the local filesystem or from a remote URL. A custom strategy could be created which could e.g. get the asset file from an S3 bucket. :::info This is configured via the `importExportOptions.assetImportStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface AssetImportStrategy extends InjectableStrategy { getStreamFromPath(assetPath: string): Readable | Promise<Readable>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### getStreamFromPath <MemberInfo kind="method" type={`(assetPath: string) => Readable | Promise&#60;Readable&#62;`} /> Given an asset path, this method should return a Stream of file data. This could e.g. be read from a file system or fetch from a remote location. </div>
--- title: "AssetImporter" 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'; ## AssetImporter <GenerationInfo sourceFile="packages/core/src/data-import/providers/asset-importer/asset-importer.ts" sourceLine="17" packageName="@vendure/core" /> This service creates new <a href='/reference/typescript-api/entities/asset#asset'>Asset</a> entities based on string paths provided in the CSV import format. The source files are resolved by joining the value of `importExportOptions.importAssetsDir` with the asset path. This service is used internally by the <a href='/reference/typescript-api/import-export/importer#importer'>Importer</a> service. ```ts title="Signature" class AssetImporter { getAssets(assetPaths: string[], ctx?: RequestContext) => Promise<{ assets: Asset[]; errors: string[] }>; } ``` <div className="members-wrapper"> ### getAssets <MemberInfo kind="method" type={`(assetPaths: string[], ctx?: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>) => Promise&#60;{ assets: <a href='/reference/typescript-api/entities/asset#asset'>Asset</a>[]; errors: string[] }&#62;`} /> Creates Asset entities for the given paths, using the assetMap cache to prevent the creation of duplicates. </div>
--- title: "DefaultAssetImportStrategy" 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'; ## DefaultAssetImportStrategy <GenerationInfo sourceFile="packages/core/src/config/asset-import-strategy/default-asset-import-strategy.ts" sourceLine="50" packageName="@vendure/core" since="1.7.0" /> The DefaultAssetImportStrategy is able to import paths from the local filesystem (taking into account the `importExportOptions.importAssetsDir` setting) as well as remote http/https urls. ```ts title="Signature" class DefaultAssetImportStrategy implements AssetImportStrategy { constructor(options?: { retryDelayMs: number; retryCount: number; }) init(injector: Injector) => ; getStreamFromPath(assetPath: string) => ; } ``` * Implements: <code><a href='/reference/typescript-api/import-export/asset-import-strategy#assetimportstrategy'>AssetImportStrategy</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(options?: { retryDelayMs: number; retryCount: number; }) => DefaultAssetImportStrategy`} /> ### init <MemberInfo kind="method" type={`(injector: <a href='/reference/typescript-api/common/injector#injector'>Injector</a>) => `} /> ### getStreamFromPath <MemberInfo kind="method" type={`(assetPath: string) => `} /> </div>
--- title: "FastImporterService" 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'; ## FastImporterService <GenerationInfo sourceFile="packages/core/src/data-import/providers/importer/fast-importer.service.ts" sourceLine="41" packageName="@vendure/core" /> A service to import entities into the database. This replaces the regular `create` methods of the service layer with faster versions which skip much of the defensive checks and other DB calls which are not needed when running an import. It also does not publish any events, so e.g. will not trigger search index jobs. In testing, the use of the FastImporterService approximately doubled the speed of bulk imports. ```ts title="Signature" class FastImporterService { initialize(channel?: Channel) => ; createProduct(input: CreateProductInput) => Promise<ID>; createProductOptionGroup(input: CreateProductOptionGroupInput) => Promise<ID>; createProductOption(input: CreateProductOptionInput) => Promise<ID>; addOptionGroupToProduct(productId: ID, optionGroupId: ID) => ; createProductVariant(input: CreateProductVariantInput) => Promise<ID>; } ``` <div className="members-wrapper"> ### initialize <MemberInfo kind="method" type={`(channel?: <a href='/reference/typescript-api/entities/channel#channel'>Channel</a>) => `} /> This should be called prior to any of the import methods, as it establishes the default Channel as well as the context in which the new entities will be created. Passing a `channel` argument means that Products and ProductVariants will be assigned to that Channel. ### createProduct <MemberInfo kind="method" type={`(input: CreateProductInput) => Promise&#60;<a href='/reference/typescript-api/common/id#id'>ID</a>&#62;`} /> ### createProductOptionGroup <MemberInfo kind="method" type={`(input: CreateProductOptionGroupInput) => Promise&#60;<a href='/reference/typescript-api/common/id#id'>ID</a>&#62;`} /> ### createProductOption <MemberInfo kind="method" type={`(input: CreateProductOptionInput) => Promise&#60;<a href='/reference/typescript-api/common/id#id'>ID</a>&#62;`} /> ### addOptionGroupToProduct <MemberInfo kind="method" type={`(productId: <a href='/reference/typescript-api/common/id#id'>ID</a>, optionGroupId: <a href='/reference/typescript-api/common/id#id'>ID</a>) => `} /> ### createProductVariant <MemberInfo kind="method" type={`(input: CreateProductVariantInput) => Promise&#60;<a href='/reference/typescript-api/common/id#id'>ID</a>&#62;`} /> </div>
--- title: "ImportExportOptions" 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'; ## ImportExportOptions <GenerationInfo sourceFile="packages/core/src/config/vendure-config.ts" sourceLine="880" packageName="@vendure/core" /> Options related to importing & exporting data. ```ts title="Signature" interface ImportExportOptions { importAssetsDir?: string; assetImportStrategy?: AssetImportStrategy; } ``` <div className="members-wrapper"> ### importAssetsDir <MemberInfo kind="property" type={`string`} default="__dirname" /> The directory in which assets to be imported are located. ### assetImportStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/import-export/asset-import-strategy#assetimportstrategy'>AssetImportStrategy</a>`} since="1.7.0" /> This strategy determines how asset files get imported based on the path given in the import CSV or via the <a href='/reference/typescript-api/import-export/asset-importer#assetimporter'>AssetImporter</a> `getAssets()` method. </div>
--- title: "ImportParser" 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'; ## ImportParser <GenerationInfo sourceFile="packages/core/src/data-import/providers/import-parser/import-parser.ts" sourceLine="152" packageName="@vendure/core" /> Validates and parses CSV files into a data structure which can then be used to created new entities. This is used internally by the <a href='/reference/typescript-api/import-export/importer#importer'>Importer</a>. ```ts title="Signature" class ImportParser { parseProducts(input: string | Stream, mainLanguage: LanguageCode = this.configService.defaultLanguageCode) => Promise<ParseResult<ParsedProductWithVariants>>; } ``` <div className="members-wrapper"> ### parseProducts <MemberInfo kind="method" type={`(input: string | Stream, mainLanguage: <a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a> = this.configService.defaultLanguageCode) => Promise&#60;<a href='/reference/typescript-api/import-export/import-parser#parseresult'>ParseResult</a>&#60;<a href='/reference/typescript-api/import-export/import-parser#parsedproductwithvariants'>ParsedProductWithVariants</a>&#62;&#62;`} /> Parses the contents of the [product import CSV file](/guides/developer-guide/importing-data/#product-import-format) and returns a data structure which can then be used to populate Vendure using the <a href='/reference/typescript-api/import-export/fast-importer-service#fastimporterservice'>FastImporterService</a>. </div> ## ParsedOptionGroup <GenerationInfo sourceFile="packages/core/src/data-import/providers/import-parser/import-parser.ts" sourceLine="45" packageName="@vendure/core" /> The intermediate representation of an OptionGroup after it has been parsed by the <a href='/reference/typescript-api/import-export/import-parser#importparser'>ImportParser</a>. ```ts title="Signature" interface ParsedOptionGroup { translations: Array<{ languageCode: LanguageCode; name: string; values: string[]; }>; } ``` <div className="members-wrapper"> ### translations <MemberInfo kind="property" type={`Array&#60;{ languageCode: <a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>; name: string; values: string[]; }&#62;`} /> </div> ## ParsedFacet <GenerationInfo sourceFile="packages/core/src/data-import/providers/import-parser/import-parser.ts" sourceLine="61" packageName="@vendure/core" /> The intermediate representation of a Facet after it has been parsed by the <a href='/reference/typescript-api/import-export/import-parser#importparser'>ImportParser</a>. ```ts title="Signature" interface ParsedFacet { translations: Array<{ languageCode: LanguageCode; facet: string; value: string; }>; } ``` <div className="members-wrapper"> ### translations <MemberInfo kind="property" type={`Array&#60;{ languageCode: <a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>; facet: string; value: string; }&#62;`} /> </div> ## ParsedProductVariant <GenerationInfo sourceFile="packages/core/src/data-import/providers/import-parser/import-parser.ts" sourceLine="77" packageName="@vendure/core" /> The intermediate representation of a ProductVariant after it has been parsed by the <a href='/reference/typescript-api/import-export/import-parser#importparser'>ImportParser</a>. ```ts title="Signature" interface ParsedProductVariant { sku: string; price: number; taxCategory: string; stockOnHand: number; trackInventory: GlobalFlag; assetPaths: string[]; facets: ParsedFacet[]; translations: Array<{ languageCode: LanguageCode; optionValues: string[]; customFields: { [name: string]: string; }; }>; } ``` <div className="members-wrapper"> ### sku <MemberInfo kind="property" type={`string`} /> ### price <MemberInfo kind="property" type={`number`} /> ### taxCategory <MemberInfo kind="property" type={`string`} /> ### stockOnHand <MemberInfo kind="property" type={`number`} /> ### trackInventory <MemberInfo kind="property" type={`GlobalFlag`} /> ### assetPaths <MemberInfo kind="property" type={`string[]`} /> ### facets <MemberInfo kind="property" type={`<a href='/reference/typescript-api/import-export/import-parser#parsedfacet'>ParsedFacet</a>[]`} /> ### translations <MemberInfo kind="property" type={`Array&#60;{ languageCode: <a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>; optionValues: string[]; customFields: { [name: string]: string; }; }&#62;`} /> </div> ## ParsedProduct <GenerationInfo sourceFile="packages/core/src/data-import/providers/import-parser/import-parser.ts" sourceLine="102" packageName="@vendure/core" /> The intermediate representation of a Product after it has been parsed by the <a href='/reference/typescript-api/import-export/import-parser#importparser'>ImportParser</a>. ```ts title="Signature" interface ParsedProduct { assetPaths: string[]; optionGroups: ParsedOptionGroup[]; facets: ParsedFacet[]; translations: Array<{ languageCode: LanguageCode; name: string; slug: string; description: string; customFields: { [name: string]: string; }; }>; } ``` <div className="members-wrapper"> ### assetPaths <MemberInfo kind="property" type={`string[]`} /> ### optionGroups <MemberInfo kind="property" type={`<a href='/reference/typescript-api/import-export/import-parser#parsedoptiongroup'>ParsedOptionGroup</a>[]`} /> ### facets <MemberInfo kind="property" type={`<a href='/reference/typescript-api/import-export/import-parser#parsedfacet'>ParsedFacet</a>[]`} /> ### translations <MemberInfo kind="property" type={`Array&#60;{ languageCode: <a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>; name: string; slug: string; description: string; customFields: { [name: string]: string; }; }&#62;`} /> </div> ## ParsedProductWithVariants <GenerationInfo sourceFile="packages/core/src/data-import/providers/import-parser/import-parser.ts" sourceLine="125" packageName="@vendure/core" /> The data structure into which an import CSV file is parsed by the <a href='/reference/typescript-api/import-export/import-parser#importparser'>ImportParser</a> `parseProducts()` method. ```ts title="Signature" interface ParsedProductWithVariants { product: ParsedProduct; variants: ParsedProductVariant[]; } ``` <div className="members-wrapper"> ### product <MemberInfo kind="property" type={`<a href='/reference/typescript-api/import-export/import-parser#parsedproduct'>ParsedProduct</a>`} /> ### variants <MemberInfo kind="property" type={`<a href='/reference/typescript-api/import-export/import-parser#parsedproductvariant'>ParsedProductVariant</a>[]`} /> </div> ## ParseResult <GenerationInfo sourceFile="packages/core/src/data-import/providers/import-parser/import-parser.ts" sourceLine="137" packageName="@vendure/core" /> The result returned by the <a href='/reference/typescript-api/import-export/import-parser#importparser'>ImportParser</a> `parseProducts()` method. ```ts title="Signature" interface ParseResult<T> { results: T[]; errors: string[]; processed: number; } ``` <div className="members-wrapper"> ### results <MemberInfo kind="property" type={`T[]`} /> ### errors <MemberInfo kind="property" type={`string[]`} /> ### processed <MemberInfo kind="property" type={`number`} /> </div>
--- title: "Importer" 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'; ## Importer <GenerationInfo sourceFile="packages/core/src/data-import/providers/importer/importer.ts" sourceLine="41" packageName="@vendure/core" /> Parses and imports Products using the CSV import format. Internally it is using the <a href='/reference/typescript-api/import-export/import-parser#importparser'>ImportParser</a> to parse the CSV file, and then the <a href='/reference/typescript-api/import-export/fast-importer-service#fastimporterservice'>FastImporterService</a> and the <a href='/reference/typescript-api/import-export/asset-importer#assetimporter'>AssetImporter</a> to actually create the resulting entities in the Vendure database. ```ts title="Signature" class Importer { parseAndImport(input: string | Stream, ctxOrLanguageCode: RequestContext | LanguageCode, reportProgress: boolean = false) => Observable<ImportProgress>; importProducts(ctx: RequestContext, rows: ParsedProductWithVariants[], onProgress: OnProgressFn) => Promise<string[]>; } ``` <div className="members-wrapper"> ### parseAndImport <MemberInfo kind="method" type={`(input: string | Stream, ctxOrLanguageCode: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a> | <a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>, reportProgress: boolean = false) => Observable&#60;ImportProgress&#62;`} /> Parses the contents of the [product import CSV file](/guides/developer-guide/importing-data/#product-import-format) and imports the resulting Product & ProductVariants, as well as any associated Assets, Facets & FacetValues. The `ctxOrLanguageCode` argument is used to specify the languageCode to be used when creating the Products. ### importProducts <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, rows: <a href='/reference/typescript-api/import-export/import-parser#parsedproductwithvariants'>ParsedProductWithVariants</a>[], onProgress: OnProgressFn) => Promise&#60;string[]&#62;`} /> Imports the products specified in the rows object. Return an array of error messages. </div>
--- title: "Import Export" 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: "InitialData" 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'; ## InitialData <GenerationInfo sourceFile="packages/core/src/data-import/types.ts" sourceLine="47" packageName="@vendure/core" /> An object defining initial settings for a new Vendure installation. ```ts title="Signature" interface InitialData { defaultLanguage: LanguageCode; defaultZone: string; roles?: RoleDefinition[]; countries: CountryDefinition[]; taxRates: Array<{ name: string; percentage: number }>; shippingMethods: Array<{ name: string; price: number }>; paymentMethods: Array<{ name: string; handler: ConfigurableOperationInput }>; collections: CollectionDefinition[]; } ``` <div className="members-wrapper"> ### defaultLanguage <MemberInfo kind="property" type={`<a href='/reference/typescript-api/common/language-code#languagecode'>LanguageCode</a>`} /> ### defaultZone <MemberInfo kind="property" type={`string`} /> ### roles <MemberInfo kind="property" type={`RoleDefinition[]`} /> ### countries <MemberInfo kind="property" type={`CountryDefinition[]`} /> ### taxRates <MemberInfo kind="property" type={`Array&#60;{ name: string; percentage: number }&#62;`} /> ### shippingMethods <MemberInfo kind="property" type={`Array&#60;{ name: string; price: number }&#62;`} /> ### paymentMethods <MemberInfo kind="property" type={`Array&#60;{ name: string; handler: ConfigurableOperationInput }&#62;`} /> ### collections <MemberInfo kind="property" type={`CollectionDefinition[]`} /> </div>
--- title: "Populate" 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'; ## populate <GenerationInfo sourceFile="packages/core/src/cli/populate.ts" sourceLine="51" packageName="@vendure/core" /> Populates the Vendure server with some initial data and (optionally) product data from a supplied CSV file. The format of the CSV file is described in the section [Importing Product Data](/guides/developer-guide/importing-data/). If the `channelOrToken` argument is provided, all ChannelAware entities (Products, ProductVariants, Assets, ShippingMethods, PaymentMethods etc.) will be assigned to the specified Channel. The argument can be either a Channel object or a valid channel `token`. Internally the `populate()` function does the following: 1. Uses the <a href='/reference/typescript-api/import-export/populator#populator'>Populator</a> to populate the <a href='/reference/typescript-api/import-export/initial-data#initialdata'>InitialData</a>. 2. If `productsCsvPath` is provided, uses <a href='/reference/typescript-api/import-export/importer#importer'>Importer</a> to populate Product data. 3. Uses <a href='/reference/typescript-api/import-export/populator#populator'>Populator</a> to populate collections specified in the <a href='/reference/typescript-api/import-export/initial-data#initialdata'>InitialData</a>. *Example* ```ts import { bootstrap } from '@vendure/core'; import { populate } from '@vendure/core/cli'; import { config } from './vendure-config.ts' import { initialData } from './my-initial-data.ts'; const productsCsvFile = path.join(__dirname, 'path/to/products.csv') populate( () => bootstrap(config), initialData, productsCsvFile, ) .then(app => app.close()) .then( () => process.exit(0), err => { console.log(err); process.exit(1); }, ); ``` ```ts title="Signature" function populate<T extends INestApplicationContext>(bootstrapFn: () => Promise<T | undefined>, initialDataPathOrObject: string | object, productsCsvPath?: string, channelOrToken?: string | import('@vendure/core').Channel): Promise<T> ``` Parameters ### bootstrapFn <MemberInfo kind="parameter" type={`() =&#62; Promise&#60;T | undefined&#62;`} /> ### initialDataPathOrObject <MemberInfo kind="parameter" type={`string | object`} /> ### productsCsvPath <MemberInfo kind="parameter" type={`string`} /> ### channelOrToken <MemberInfo kind="parameter" type={`string | import('@vendure/core').<a href='/reference/typescript-api/entities/channel#channel'>Channel</a>`} />
--- title: "Populator" 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'; ## Populator <GenerationInfo sourceFile="packages/core/src/data-import/providers/populator/populator.ts" sourceLine="46" packageName="@vendure/core" /> Responsible for populating the database with <a href='/reference/typescript-api/import-export/initial-data#initialdata'>InitialData</a>, i.e. non-product data such as countries, tax rates, shipping methods, payment methods & roles. ```ts title="Signature" class Populator { populateInitialData(data: InitialData, channel?: Channel) => ; populateCollections(data: InitialData, channel?: Channel) => ; } ``` <div className="members-wrapper"> ### populateInitialData <MemberInfo kind="method" type={`(data: <a href='/reference/typescript-api/import-export/initial-data#initialdata'>InitialData</a>, channel?: <a href='/reference/typescript-api/entities/channel#channel'>Channel</a>) => `} /> Should be run *before* populating the products, so that there are TaxRates by which product prices can be set. If the `channel` argument is set, then any <a href='/reference/typescript-api/entities/interfaces#channelaware'>ChannelAware</a> entities will be assigned to that Channel. ### populateCollections <MemberInfo kind="method" type={`(data: <a href='/reference/typescript-api/import-export/initial-data#initialdata'>InitialData</a>, channel?: <a href='/reference/typescript-api/entities/channel#channel'>Channel</a>) => `} /> Should be run *after* the products have been populated, otherwise the expected FacetValues will not yet exist. </div>
--- title: "DefaultJobQueuePlugin" 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'; ## DefaultJobQueuePlugin <GenerationInfo sourceFile="packages/core/src/plugin/default-job-queue-plugin/default-job-queue-plugin.ts" sourceLine="183" packageName="@vendure/core" /> A plugin which configures Vendure to use the SQL database to persist the JobQueue jobs using the <a href='/reference/typescript-api/job-queue/sql-job-queue-strategy#sqljobqueuestrategy'>SqlJobQueueStrategy</a>. If you add this plugin to an existing Vendure installation, you'll need to run a [database migration](/guides/developer-guide/migrations), since this plugin will add a new "job_record" table to the database. *Example* ```ts import { DefaultJobQueuePlugin, VendureConfig } from '@vendure/core'; export const config: VendureConfig = { // Add an instance of the plugin to the plugins array plugins: [ DefaultJobQueuePlugin, ], }; ``` ## Configuration It is possible to configure the behaviour of the <a href='/reference/typescript-api/job-queue/sql-job-queue-strategy#sqljobqueuestrategy'>SqlJobQueueStrategy</a> by passing options to the static `init()` function: ### pollInterval The interval in ms between polling for new jobs. The default is 200ms. Using a longer interval reduces load on the database but results in a slight delay in processing jobs. For more control, it is possible to supply a function which can specify a pollInterval based on the queue name: *Example* ```ts export const config: VendureConfig = { plugins: [ DefaultJobQueuePlugin.init({ pollInterval: queueName => { if (queueName === 'cart-recovery-email') { // This queue does not need to be polled so frequently, // so we set a longer interval in order to reduce load // on the database. return 10000; } return 200; }, }), ], }; ``` ### concurrency The number of jobs to process concurrently per worker. Defaults to 1. ### backoffStrategy Defines the backoff strategy used when retrying failed jobs. In other words, if a job fails and is configured to be re-tried, how long should we wait before the next attempt? By default, a job will be retried as soon as possible, but in some cases this is not desirable. For example, a job may interact with an unreliable 3rd-party API which is sensitive to too many requests. In this case, an exponential backoff may be used which progressively increases the delay between each subsequent retry. *Example* ```ts export const config: VendureConfig = { plugins: [ DefaultJobQueuePlugin.init({ pollInterval: 5000, concurrency: 2 backoffStrategy: (queueName, attemptsMade, job) => { if (queueName === 'transcode-video') { // exponential backoff example return (attemptsMade ** 2) * 1000; } // A default delay for all other queues return 1000; }, setRetries: (queueName, job) => { if (queueName === 'send-email') { // Override the default number of retries // for the 'send-email' job because we have // a very unreliable email service. return 10; } return job.retries; } }), ], }; ``` ```ts title="Signature" class DefaultJobQueuePlugin { init(options: DefaultJobQueueOptions) => Type<DefaultJobQueuePlugin>; } ``` <div className="members-wrapper"> ### init <MemberInfo kind="method" type={`(options: <a href='/reference/typescript-api/job-queue/default-job-queue-plugin#defaultjobqueueoptions'>DefaultJobQueueOptions</a>) => Type&#60;<a href='/reference/typescript-api/job-queue/default-job-queue-plugin#defaultjobqueueplugin'>DefaultJobQueuePlugin</a>&#62;`} /> </div> ## DefaultJobQueueOptions <GenerationInfo sourceFile="packages/core/src/plugin/default-job-queue-plugin/default-job-queue-plugin.ts" sourceLine="21" packageName="@vendure/core" /> Configuration options for the DefaultJobQueuePlugin. These values get passed into the <a href='/reference/typescript-api/job-queue/sql-job-queue-strategy#sqljobqueuestrategy'>SqlJobQueueStrategy</a>. ```ts title="Signature" interface DefaultJobQueueOptions { pollInterval?: number | ((queueName: string) => number); concurrency?: number; backoffStrategy?: BackoffStrategy; setRetries?: (queueName: string, job: Job) => number; useDatabaseForBuffer?: boolean; gracefulShutdownTimeout?: number; } ``` <div className="members-wrapper"> ### pollInterval <MemberInfo kind="property" type={`number | ((queueName: string) =&#62; number)`} default="200" /> The interval in ms between polling the database for new jobs. If many job queues are active, the polling may cause undue load on the database, in which case this value should be increased to e.g. 1000. ### concurrency <MemberInfo kind="property" type={`number`} default="1" /> How many jobs from a given queue to process concurrently. ### backoffStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/job-queue/types#backoffstrategy'>BackoffStrategy</a>`} default="() =&#62; 1000" /> The strategy used to decide how long to wait before retrying a failed job. ### setRetries <MemberInfo kind="property" type={`(queueName: string, job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>) =&#62; number`} /> When a job is added to the JobQueue using `JobQueue.add()`, the calling code may specify the number of retries in case of failure. This option allows you to override that number and specify your own number of retries based on the job being added. *Example* ```ts setRetries: (queueName, job) => { if (queueName === 'send-email') { // Override the default number of retries // for the 'send-email' job because we have // a very unreliable email service. return 10; } return job.retries; } ``` ### useDatabaseForBuffer <MemberInfo kind="property" type={`boolean`} since="1.3.0" /> If set to `true`, the database will be used to store buffered jobs. This is recommended for production. When enabled, a new `JobRecordBuffer` database entity will be defined which will require a migration when first enabling this option. ### gracefulShutdownTimeout <MemberInfo kind="property" type={`number`} default="20_000" since="2.2.0" /> The timeout in ms which the queue will use when attempting a graceful shutdown. That means when the server is shut down but a job is running, the job queue will wait for the job to complete before allowing the server to shut down. If the job does not complete within this timeout window, the job will be forced to stop and the server will shut down anyway. </div>
--- title: "InMemoryJobBufferStorageStrategy" 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'; ## InMemoryJobBufferStorageStrategy <GenerationInfo sourceFile="packages/core/src/job-queue/job-buffer/in-memory-job-buffer-storage-strategy.ts" sourceLine="17" packageName="@vendure/core" since="1.3.0" /> A <a href='/reference/typescript-api/job-queue/job-buffer-storage-strategy#jobbufferstoragestrategy'>JobBufferStorageStrategy</a> which keeps the buffered jobs in memory. Should _not_ be used in production, since it will lose data in the event of the server stopping. Instead, use the <a href='/reference/typescript-api/job-queue/default-job-queue-plugin#defaultjobqueueplugin'>DefaultJobQueuePlugin</a> with the `useDatabaseForBuffer: true` option set, or the {@link BullMQJobQueuePlugin} or another custom strategy with persistent storage. ```ts title="Signature" class InMemoryJobBufferStorageStrategy implements JobBufferStorageStrategy { protected bufferStorage = new Map<string, Set<Job>>(); add(bufferId: string, job: Job) => Promise<Job>; bufferSize(bufferIds?: string[]) => Promise<{ [bufferId: string]: number }>; flush(bufferIds?: string[]) => Promise<{ [bufferId: string]: Job[] }>; } ``` * Implements: <code><a href='/reference/typescript-api/job-queue/job-buffer-storage-strategy#jobbufferstoragestrategy'>JobBufferStorageStrategy</a></code> <div className="members-wrapper"> ### bufferStorage <MemberInfo kind="property" type={``} /> ### add <MemberInfo kind="method" type={`(bufferId: string, job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#62;`} /> ### bufferSize <MemberInfo kind="method" type={`(bufferIds?: string[]) => Promise&#60;{ [bufferId: string]: number }&#62;`} /> ### flush <MemberInfo kind="method" type={`(bufferIds?: string[]) => Promise&#60;{ [bufferId: string]: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>[] }&#62;`} /> </div>
--- title: "InMemoryJobQueueStrategy" 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'; ## InMemoryJobQueueStrategy <GenerationInfo sourceFile="packages/core/src/job-queue/in-memory-job-queue-strategy.ts" sourceLine="42" packageName="@vendure/core" /> An in-memory <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a>. This is the default strategy if not using a dedicated JobQueue plugin (e.g. <a href='/reference/typescript-api/job-queue/default-job-queue-plugin#defaultjobqueueplugin'>DefaultJobQueuePlugin</a>). Not recommended for production, since the queue will be cleared when the server stops, and can only be used when the JobQueueService is started from the main server process: *Example* ```ts bootstrap(config) .then(app => app.get(JobQueueService).start()); ``` Attempting to use this strategy when running the worker in a separate process (using `bootstrapWorker()`) will result in an error on startup. Completed jobs will be evicted from the store every 2 hours to prevent a memory leak. ```ts title="Signature" class InMemoryJobQueueStrategy extends PollingJobQueueStrategy implements InspectableJobQueueStrategy { protected jobs = new Map<ID, Job>(); protected unsettledJobs: { [queueName: string]: Array<{ job: Job; updatedAt: Date }> } = {}; init(injector: Injector) => ; destroy() => ; add(job: Job<Data>) => Promise<Job<Data>>; findOne(id: ID) => Promise<Job | undefined>; findMany(options?: JobListOptions) => Promise<PaginatedList<Job>>; findManyById(ids: ID[]) => Promise<Job[]>; next(queueName: string, waitingJobs: Job[] = []) => Promise<Job | undefined>; update(job: Job) => Promise<void>; removeSettledJobs(queueNames: string[] = [], olderThan?: Date) => Promise<number>; } ``` * Extends: <code><a href='/reference/typescript-api/job-queue/polling-job-queue-strategy#pollingjobqueuestrategy'>PollingJobQueueStrategy</a></code> * Implements: <code><a href='/reference/typescript-api/job-queue/inspectable-job-queue-strategy#inspectablejobqueuestrategy'>InspectableJobQueueStrategy</a></code> <div className="members-wrapper"> ### jobs <MemberInfo kind="property" type={``} /> ### unsettledJobs <MemberInfo kind="property" type={`{ [queueName: string]: Array&#60;{ job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>; updatedAt: Date }&#62; }`} /> ### init <MemberInfo kind="method" type={`(injector: <a href='/reference/typescript-api/common/injector#injector'>Injector</a>) => `} /> ### destroy <MemberInfo kind="method" type={`() => `} /> ### add <MemberInfo kind="method" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;&#62;`} /> ### findOne <MemberInfo kind="method" type={`(id: <a href='/reference/typescript-api/common/id#id'>ID</a>) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> ### findMany <MemberInfo kind="method" type={`(options?: JobListOptions) => Promise&#60;<a href='/reference/typescript-api/common/paginated-list#paginatedlist'>PaginatedList</a>&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#62;&#62;`} /> ### findManyById <MemberInfo kind="method" type={`(ids: <a href='/reference/typescript-api/common/id#id'>ID</a>[]) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>[]&#62;`} /> ### next <MemberInfo kind="method" type={`(queueName: string, waitingJobs: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>[] = []) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> ### update <MemberInfo kind="method" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>) => Promise&#60;void&#62;`} /> ### removeSettledJobs <MemberInfo kind="method" type={`(queueNames: string[] = [], olderThan?: Date) => Promise&#60;number&#62;`} /> </div>
--- title: "JobQueue" 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'; ## JobQueue <GenerationInfo sourceFile="packages/core/src/job-queue/job-queue.ts" sourceLine="25" packageName="@vendure/core" /> A JobQueue is used to process <a href='/reference/typescript-api/job-queue/job#job'>Job</a>s. A job is added to the queue via the `.add()` method, and the configured <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a> will check for new jobs and process each according to the defined `process` function. *Note*: JobQueue instances should not be directly instantiated. Rather, the <a href='/reference/typescript-api/job-queue/job-queue-service#jobqueueservice'>JobQueueService</a> `createQueue()` method should be used (see that service for example usage). ```ts title="Signature" class JobQueue<Data extends JobData<Data> = object> { name: string started: boolean constructor(options: CreateQueueOptions<Data>, jobQueueStrategy: JobQueueStrategy, jobBufferService: JobBufferService) add(data: Data, options?: JobOptions<Data>) => Promise<SubscribableJob<Data>>; } ``` <div className="members-wrapper"> ### name <MemberInfo kind="property" type={`string`} /> ### started <MemberInfo kind="property" type={`boolean`} /> ### constructor <MemberInfo kind="method" type={`(options: <a href='/reference/typescript-api/job-queue/types#createqueueoptions'>CreateQueueOptions</a>&#60;Data&#62;, jobQueueStrategy: <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a>, jobBufferService: JobBufferService) => JobQueue`} /> ### add <MemberInfo kind="method" type={`(data: Data, options?: JobOptions&#60;Data&#62;) => Promise&#60;<a href='/reference/typescript-api/job-queue/subscribable-job#subscribablejob'>SubscribableJob</a>&#60;Data&#62;&#62;`} /> Adds a new <a href='/reference/typescript-api/job-queue/job#job'>Job</a> to the queue. The resolved <a href='/reference/typescript-api/job-queue/subscribable-job#subscribablejob'>SubscribableJob</a> allows the calling code to subscribe to updates to the Job: *Example* ```ts const job = await this.myQueue.add({ intervalMs, shouldFail }, { 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)), ); ``` Alternatively, if you aren't interested in the intermediate `progress` changes, you can convert to a Promise like this: *Example* ```ts const job = await this.myQueue.add({ intervalMs, shouldFail }, { retries: 2 }); return job.updates().toPromise() .then(update => update.result), .catch(err => err.message); ``` </div>
--- title: "InspectableJobQueueStrategy" 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'; ## InspectableJobQueueStrategy <GenerationInfo sourceFile="packages/core/src/config/job-queue/inspectable-job-queue-strategy.ts" sourceLine="14" packageName="@vendure/core" /> Defines a job queue strategy that can be inspected using the default admin ui ```ts title="Signature" interface InspectableJobQueueStrategy extends JobQueueStrategy { findOne(id: ID): Promise<Job | undefined>; findMany(options?: JobListOptions): Promise<PaginatedList<Job>>; findManyById(ids: ID[]): Promise<Job[]>; removeSettledJobs(queueNames?: string[], olderThan?: Date): Promise<number>; cancelJob(jobId: ID): Promise<Job | undefined>; } ``` * Extends: <code><a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a></code> <div className="members-wrapper"> ### findOne <MemberInfo kind="method" type={`(id: <a href='/reference/typescript-api/common/id#id'>ID</a>) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> Returns a job by its id. ### findMany <MemberInfo kind="method" type={`(options?: JobListOptions) => Promise&#60;<a href='/reference/typescript-api/common/paginated-list#paginatedlist'>PaginatedList</a>&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#62;&#62;`} /> Returns a list of jobs according to the specified options. ### findManyById <MemberInfo kind="method" type={`(ids: <a href='/reference/typescript-api/common/id#id'>ID</a>[]) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>[]&#62;`} /> Returns an array of jobs for the given ids. ### removeSettledJobs <MemberInfo kind="method" type={`(queueNames?: string[], olderThan?: Date) => Promise&#60;number&#62;`} /> Remove all settled jobs in the specified queues older than the given date. If no queueName is passed, all queues will be considered. If no olderThan date is passed, all jobs older than the current time will be removed. Returns a promise of the number of jobs removed. ### cancelJob <MemberInfo kind="method" type={`(jobId: <a href='/reference/typescript-api/common/id#id'>ID</a>) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> </div>
--- title: "JobBufferStorageStrategy" 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'; ## JobBufferStorageStrategy <GenerationInfo sourceFile="packages/core/src/job-queue/job-buffer/job-buffer-storage-strategy.ts" sourceLine="19" packageName="@vendure/core" since="1.3.0" /> This strategy defines where to store jobs that have been collected by a <a href='/reference/typescript-api/job-queue/job-buffer#jobbuffer'>JobBuffer</a>. :::info This is configured via the `jobQueueOptions.jobBufferStorageStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface JobBufferStorageStrategy extends InjectableStrategy { add(bufferId: string, job: Job): Promise<Job>; bufferSize(bufferIds?: string[]): Promise<{ [bufferId: string]: number }>; flush(bufferIds?: string[]): Promise<{ [bufferId: string]: Job[] }>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### add <MemberInfo kind="method" type={`(bufferId: string, job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#62;`} /> Persist a job to the storage medium. The storage format should take into account the `bufferId` argument, as it is necessary to be able to later retrieve jobs by that id. ### bufferSize <MemberInfo kind="method" type={`(bufferIds?: string[]) => Promise&#60;{ [bufferId: string]: number }&#62;`} /> Returns an object containing the number of buffered jobs arranged by bufferId. Passing bufferIds limits the results to the specified bufferIds. If the array is empty, sizes will be returned for _all_ bufferIds. *Example* ```ts const sizes = await myJobBufferStrategy.bufferSize(['buffer-1', 'buffer-2']); // sizes = { 'buffer-1': 12, 'buffer-2': 3 } ``` ### flush <MemberInfo kind="method" type={`(bufferIds?: string[]) => Promise&#60;{ [bufferId: string]: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>[] }&#62;`} /> Clears all jobs from the storage medium which match the specified bufferIds (if the array is empty, clear for _all_ bufferIds), and returns those jobs in an object arranged by bufferId *Example* ```ts const result = await myJobBufferStrategy.flush(['buffer-1', 'buffer-2']); // result = { // 'buffer-1': [Job, Job, Job, ...], // 'buffer-2': [Job, Job, Job, ...], // }; ``` </div>
--- title: "JobBuffer" 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'; ## JobBuffer <GenerationInfo sourceFile="packages/core/src/job-queue/job-buffer/job-buffer.ts" sourceLine="83" packageName="@vendure/core" since="1.3.0" /> A JobBuffer is used to temporarily prevent jobs from being sent to the job queue for processing. Instead, it collects certain jobs (as specified by the `collect()` method), and stores them. How these buffered jobs are stored is determined by the configured <a href='/reference/typescript-api/job-queue/job-buffer-storage-strategy#jobbufferstoragestrategy'>JobBufferStorageStrategy</a>. The JobBuffer can be thought of as a kind of "interceptor" of jobs. That is, when a JobBuffer is active, it sits in between calls to `JobQueue.add()` and the actual adding of the job to the queue. At some later point, the buffer can be flushed (by calling `JobQueue.flush()`), at which point all the jobs that were collected into the buffer will be removed from the buffer and passed to the `JobBuffer.reduce()` method. This method is able to perform additional logic to e.g. aggregate many jobs into a single job in order to de-duplicate work. *Example* ```ts // This is a buffer which will collect all the // 'apply-collection-filters' jobs and buffer them. export class CollectionJobBuffer implements JobBuffer<ApplyCollectionFiltersJobData> { readonly id = 'apply-collection-filters-buffer'; collect(job: Job): boolean { return job.queueName === 'apply-collection-filters'; } // When the buffer gets flushed, this function will be passed all the collected jobs // and will reduce them down to a single job that has aggregated all of the collectionIds. reduce(collectedJobs: Array<Job<ApplyCollectionFiltersJobData>>): Array<Job<any>> { // Concatenate all the collectionIds from all the events that were buffered const collectionIdsToUpdate = collectedJobs.reduce((result, job) => { return [...result, ...job.data.collectionIds]; }, [] as ID[]); const referenceJob = collectedJobs[0]; // Create a new Job containing all the concatenated collectionIds, // de-duplicated to include each collectionId only once. const batchedCollectionJob = new Job<ApplyCollectionFiltersJobData>({ ...referenceJob, id: undefined, data: { collectionIds: unique(collectionIdsToUpdate), ctx: referenceJob.data.ctx, applyToChangedVariantsOnly: referenceJob.data.applyToChangedVariantsOnly, }, }); // Only this single job will get added to the job queue return [batchedCollectionJob]; } } ``` A JobBuffer is used by adding it to the <a href='/reference/typescript-api/job-queue/job-queue-service#jobqueueservice'>JobQueueService</a>, at which point it will become active and start collecting jobs. At some later point, the buffer can be flushed, causing the buffered jobs to be passed through the `reduce()` method and sent to the job queue. *Example* ```ts const collectionBuffer = new CollectionJobBuffer(); await this.jobQueueService.addBuffer(collectionBuffer); // Here you can perform some work which would ordinarily // trigger the 'apply-collection-filters' job, such as updating // collection filters or changing ProductVariant prices. await this.jobQueueService.flush(collectionBuffer); await this.jobQueueService.removeBuffer(collectionBuffer); ``` ```ts title="Signature" interface JobBuffer<Data extends JobData<Data> = object> { readonly id: string; collect(job: Job<Data>): boolean | Promise<boolean>; reduce(collectedJobs: Array<Job<Data>>): Array<Job<Data>> | Promise<Array<Job<Data>>>; } ``` <div className="members-wrapper"> ### id <MemberInfo kind="property" type={`string`} /> ### collect <MemberInfo kind="method" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;) => boolean | Promise&#60;boolean&#62;`} /> This method is called whenever a job is added to the job queue. If it returns `true`, then the job will be _buffered_ and _not_ added to the job queue. If it returns `false`, the job will be added to the job queue as normal. ### reduce <MemberInfo kind="method" type={`(collectedJobs: Array&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;&#62;) => Array&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;&#62; | Promise&#60;Array&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;&#62;&#62;`} /> This method is called whenever the buffer gets flushed via a call to `JobQueueService.flush()`. It allows logic to be run on the buffered jobs which enables optimizations such as aggregating and de-duplicating the work of many jobs into one job. </div>
--- title: "JobQueueOptions" 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'; ## JobQueueOptions <GenerationInfo sourceFile="packages/core/src/config/vendure-config.ts" sourceLine="904" packageName="@vendure/core" /> Options related to the built-in job queue. ```ts title="Signature" interface JobQueueOptions { jobQueueStrategy?: JobQueueStrategy; jobBufferStorageStrategy?: JobBufferStorageStrategy; activeQueues?: string[]; prefix?: string; } ``` <div className="members-wrapper"> ### jobQueueStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a>`} default="<a href='/reference/typescript-api/job-queue/in-memory-job-queue-strategy#inmemoryjobqueuestrategy'>InMemoryJobQueueStrategy</a>" /> Defines how the jobs in the queue are persisted and accessed. ### jobBufferStorageStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/job-queue/job-buffer-storage-strategy#jobbufferstoragestrategy'>JobBufferStorageStrategy</a>`} /> ### activeQueues <MemberInfo kind="property" type={`string[]`} /> Defines the queues that will run in this process. This can be used to configure only certain queues to run in this process. If its empty all queues will be run. Note: this option is primarily intended to apply to the Worker process. Jobs will _always_ get published to the queue regardless of this setting, but this setting determines whether they get _processed_ or not. ### prefix <MemberInfo kind="property" type={`string`} since="1.5.0" /> Prefixes all job queue names with the passed string. This is useful with multiple deployments in cloud environments using services such as Amazon SQS or Google Cloud Tasks. For example, we might have a staging and a production deployment in the same account/project and each one will need its own task queue. We can achieve this with a prefix. </div>
--- title: "JobQueueService" 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'; ## JobQueueService <GenerationInfo sourceFile="packages/core/src/job-queue/job-queue.service.ts" sourceLine="48" packageName="@vendure/core" /> The JobQueueService is used to create new <a href='/reference/typescript-api/job-queue/#jobqueue'>JobQueue</a> instances and access existing jobs. *Example* ```ts // A service which transcodes video files class VideoTranscoderService { private jobQueue: JobQueue<{ videoId: string; }>; async onModuleInit() { // The JobQueue is created on initialization this.jobQueue = await this.jobQueueService.createQueue({ name: 'transcode-video', process: async job => { return await this.transcodeVideo(job.data.videoId); }, }); } addToTranscodeQueue(videoId: string) { this.jobQueue.add({ videoId, }) } private async transcodeVideo(videoId: string) { // e.g. call some external transcoding service } } ``` ```ts title="Signature" class JobQueueService implements OnModuleDestroy { constructor(configService: ConfigService, jobBufferService: JobBufferService) createQueue(options: CreateQueueOptions<Data>) => Promise<JobQueue<Data>>; start() => Promise<void>; addBuffer(buffer: JobBuffer<any>) => ; removeBuffer(buffer: JobBuffer<any>) => ; bufferSize(forBuffers: Array<JobBuffer<any> | string>) => Promise<{ [bufferId: string]: number }>; flush(forBuffers: Array<JobBuffer<any> | string>) => Promise<Job[]>; getJobQueues() => GraphQlJobQueue[]; } ``` * Implements: <code>OnModuleDestroy</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(configService: ConfigService, jobBufferService: JobBufferService) => JobQueueService`} /> ### createQueue <MemberInfo kind="method" type={`(options: <a href='/reference/typescript-api/job-queue/types#createqueueoptions'>CreateQueueOptions</a>&#60;Data&#62;) => Promise&#60;<a href='/reference/typescript-api/job-queue/#jobqueue'>JobQueue</a>&#60;Data&#62;&#62;`} /> Configures and creates a new <a href='/reference/typescript-api/job-queue/#jobqueue'>JobQueue</a> instance. ### start <MemberInfo kind="method" type={`() => Promise&#60;void&#62;`} /> ### addBuffer <MemberInfo kind="method" type={`(buffer: <a href='/reference/typescript-api/job-queue/job-buffer#jobbuffer'>JobBuffer</a>&#60;any&#62;) => `} since="1.3.0" /> Adds a <a href='/reference/typescript-api/job-queue/job-buffer#jobbuffer'>JobBuffer</a>, which will make it active and begin collecting jobs to buffer. ### removeBuffer <MemberInfo kind="method" type={`(buffer: <a href='/reference/typescript-api/job-queue/job-buffer#jobbuffer'>JobBuffer</a>&#60;any&#62;) => `} since="1.3.0" /> Removes a <a href='/reference/typescript-api/job-queue/job-buffer#jobbuffer'>JobBuffer</a>, prevent it from collecting and buffering any subsequent jobs. ### bufferSize <MemberInfo kind="method" type={`(forBuffers: Array&#60;<a href='/reference/typescript-api/job-queue/job-buffer#jobbuffer'>JobBuffer</a>&#60;any&#62; | string&#62;) => Promise&#60;{ [bufferId: string]: number }&#62;`} since="1.3.0" /> Returns an object containing the number of buffered jobs arranged by bufferId. This can be used to decide whether a particular buffer has any jobs to flush. Passing in JobBuffer instances _or_ ids limits the results to the specified JobBuffers. If no argument is passed, sizes will be returned for _all_ JobBuffers. *Example* ```ts const sizes = await this.jobQueueService.bufferSize('buffer-1', 'buffer-2'); // sizes = { 'buffer-1': 12, 'buffer-2': 3 } ``` ### flush <MemberInfo kind="method" type={`(forBuffers: Array&#60;<a href='/reference/typescript-api/job-queue/job-buffer#jobbuffer'>JobBuffer</a>&#60;any&#62; | string&#62;) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>[]&#62;`} since="1.3.0" /> Flushes the specified buffers, which means that the buffer is cleared and the jobs get sent to the job queue for processing. Before sending the jobs to the job queue, they will be passed through each JobBuffer's `reduce()` method, which is can be used to optimize the amount of work to be done by e.g. de-duplicating identical jobs or aggregating data over the collected jobs. Passing in JobBuffer instances _or_ ids limits the action to the specified JobBuffers. If no argument is passed, _all_ JobBuffers will be flushed. Returns an array of all Jobs which were added to the job queue. ### getJobQueues <MemberInfo kind="method" type={`() => GraphQlJobQueue[]`} /> Returns an array of `{ name: string; running: boolean; }` for each registered JobQueue. </div>
--- title: "JobQueueStrategy" 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'; ## JobQueueStrategy <GenerationInfo sourceFile="packages/core/src/config/job-queue/job-queue-strategy.ts" sourceLine="24" packageName="@vendure/core" /> Defines how the jobs in the <a href='/reference/typescript-api/job-queue/job-queue-service#jobqueueservice'>JobQueueService</a> are persisted and accessed. Custom strategies can be defined to make use of external services such as Redis. :::info This is configured via the `jobQueueOptions.jobQueueStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface JobQueueStrategy extends InjectableStrategy { add<Data extends JobData<Data> = object>(job: Job<Data>, jobOptions?: JobQueueStrategyJobOptions<Data>): Promise<Job<Data>>; start<Data extends JobData<Data> = object>( queueName: string, process: (job: Job<Data>) => Promise<any>, ): Promise<void>; stop<Data extends JobData<Data> = object>( queueName: string, process: (job: Job<Data>) => Promise<any>, ): Promise<void>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### add <MemberInfo kind="method" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;, jobOptions?: JobQueueStrategyJobOptions&#60;Data&#62;) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;&#62;`} /> Add a new job to the queue. ### start <MemberInfo kind="method" type={`(queueName: string, process: (job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;) =&#62; Promise&#60;any&#62;) => Promise&#60;void&#62;`} /> Start the job queue ### stop <MemberInfo kind="method" type={`(queueName: string, process: (job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;) =&#62; Promise&#60;any&#62;) => Promise&#60;void&#62;`} /> Stops a queue from running. Its not guaranteed to stop immediately. </div>
--- title: "Job" 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'; ## Job <GenerationInfo sourceFile="packages/core/src/job-queue/job.ts" sourceLine="37" packageName="@vendure/core" /> A Job represents a piece of work to be run in the background, i.e. outside the request-response cycle. It is intended to be used for long-running work triggered by API requests. Jobs should now generally be directly instantiated. Rather, the <a href='/reference/typescript-api/job-queue/#jobqueue'>JobQueue</a> `add()` method should be used to create and add a new Job to a queue. ```ts title="Signature" class Job<T extends JobData<T> = any> { readonly id: number | string | null; readonly queueName: string; readonly retries: number; readonly createdAt: Date; name: string data: T state: JobState progress: number result: any error: any isSettled: boolean startedAt: Date | undefined settledAt: Date | undefined duration: number attempts: number constructor(config: JobConfig<T>) start() => ; setProgress(percent: number) => ; complete(result?: any) => ; fail(err?: any) => ; cancel() => ; defer() => ; on(eventType: JobEventType, listener: JobEventListener<T>) => ; off(eventType: JobEventType, listener: JobEventListener<T>) => ; } ``` <div className="members-wrapper"> ### id <MemberInfo kind="property" type={`number | string | null`} /> ### queueName <MemberInfo kind="property" type={`string`} /> ### retries <MemberInfo kind="property" type={`number`} /> ### createdAt <MemberInfo kind="property" type={`Date`} /> ### name <MemberInfo kind="property" type={`string`} /> ### data <MemberInfo kind="property" type={`T`} /> ### state <MemberInfo kind="property" type={`<a href='/reference/typescript-api/common/job-state#jobstate'>JobState</a>`} /> ### progress <MemberInfo kind="property" type={`number`} /> ### result <MemberInfo kind="property" type={`any`} /> ### error <MemberInfo kind="property" type={`any`} /> ### isSettled <MemberInfo kind="property" type={`boolean`} /> ### startedAt <MemberInfo kind="property" type={`Date | undefined`} /> ### settledAt <MemberInfo kind="property" type={`Date | undefined`} /> ### duration <MemberInfo kind="property" type={`number`} /> ### attempts <MemberInfo kind="property" type={`number`} /> ### constructor <MemberInfo kind="method" type={`(config: <a href='/reference/typescript-api/job-queue/types#jobconfig'>JobConfig</a>&#60;T&#62;) => Job`} /> ### start <MemberInfo kind="method" type={`() => `} /> Calling this signifies that the job work has started. This method should be called in the <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a> `next()` method. ### setProgress <MemberInfo kind="method" type={`(percent: number) => `} /> Sets the progress (0 - 100) of the job. ### complete <MemberInfo kind="method" type={`(result?: any) => `} /> Calling this method signifies that the job succeeded. The result will be stored in the `Job.result` property. ### fail <MemberInfo kind="method" type={`(err?: any) => `} /> Calling this method signifies that the job failed. ### cancel <MemberInfo kind="method" type={`() => `} /> ### defer <MemberInfo kind="method" type={`() => `} /> Sets a RUNNING job back to PENDING. Should be used when the JobQueue is being destroyed before the job has been completed. ### on <MemberInfo kind="method" type={`(eventType: <a href='/reference/typescript-api/job-queue/job#jobeventtype'>JobEventType</a>, listener: <a href='/reference/typescript-api/job-queue/job#jobeventlistener'>JobEventListener</a>&#60;T&#62;) => `} /> Used to register event handler for job events ### off <MemberInfo kind="method" type={`(eventType: <a href='/reference/typescript-api/job-queue/job#jobeventtype'>JobEventType</a>, listener: <a href='/reference/typescript-api/job-queue/job#jobeventlistener'>JobEventListener</a>&#60;T&#62;) => `} /> </div> ## JobEventType <GenerationInfo sourceFile="packages/core/src/job-queue/job.ts" sourceLine="15" packageName="@vendure/core" /> An event raised by a Job. ```ts title="Signature" type JobEventType = 'progress' ``` ## JobEventListener <GenerationInfo sourceFile="packages/core/src/job-queue/job.ts" sourceLine="24" packageName="@vendure/core" /> The signature of the event handler expected by the `Job.on()` method. ```ts title="Signature" type JobEventListener<T extends JobData<T>> = (job: Job<T>) => void ```
--- title: "PollingJobQueueStrategy" 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'; ## PollingJobQueueStrategy <GenerationInfo sourceFile="packages/core/src/job-queue/polling-job-queue-strategy.ts" sourceLine="242" packageName="@vendure/core" /> This class allows easier implementation of <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a> in a polling style. Instead of providing <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a> `start()` you should provide a `next` method. This class should be extended by any strategy which does not support a push-based system to notify on new jobs. It is used by the <a href='/reference/typescript-api/job-queue/sql-job-queue-strategy#sqljobqueuestrategy'>SqlJobQueueStrategy</a> and <a href='/reference/typescript-api/job-queue/in-memory-job-queue-strategy#inmemoryjobqueuestrategy'>InMemoryJobQueueStrategy</a>. ```ts title="Signature" class PollingJobQueueStrategy extends InjectableJobQueueStrategy { public concurrency: number; public pollInterval: number | ((queueName: string) => number); public setRetries: (queueName: string, job: Job) => number; public backOffStrategy?: BackoffStrategy; public gracefulShutdownTimeout: number; protected activeQueues = new QueueNameProcessStorage<ActiveQueue<any>>(); constructor(config?: PollingJobQueueStrategyConfig) constructor(concurrency?: number, pollInterval?: number) constructor(concurrencyOrConfig?: number | PollingJobQueueStrategyConfig, maybePollInterval?: number) start(queueName: string, process: (job: Job<Data>) => Promise<any>) => ; stop(queueName: string, process: (job: Job<Data>) => Promise<any>) => ; cancelJob(jobId: ID) => Promise<Job | undefined>; next(queueName: string) => Promise<Job | undefined>; update(job: Job) => Promise<void>; findOne(id: ID) => Promise<Job | undefined>; } ``` * Extends: <code>InjectableJobQueueStrategy</code> <div className="members-wrapper"> ### concurrency <MemberInfo kind="property" type={`number`} /> ### pollInterval <MemberInfo kind="property" type={`number | ((queueName: string) =&#62; number)`} /> ### setRetries <MemberInfo kind="property" type={`(queueName: string, job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>) =&#62; number`} /> ### backOffStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/job-queue/types#backoffstrategy'>BackoffStrategy</a>`} /> ### gracefulShutdownTimeout <MemberInfo kind="property" type={`number`} /> ### activeQueues <MemberInfo kind="property" type={``} /> ### constructor <MemberInfo kind="method" type={`(config?: PollingJobQueueStrategyConfig) => PollingJobQueueStrategy`} /> ### constructor <MemberInfo kind="method" type={`(concurrency?: number, pollInterval?: number) => PollingJobQueueStrategy`} /> ### constructor <MemberInfo kind="method" type={`(concurrencyOrConfig?: number | PollingJobQueueStrategyConfig, maybePollInterval?: number) => PollingJobQueueStrategy`} /> ### start <MemberInfo kind="method" type={`(queueName: string, process: (job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;) =&#62; Promise&#60;any&#62;) => `} /> ### stop <MemberInfo kind="method" type={`(queueName: string, process: (job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;) =&#62; Promise&#60;any&#62;) => `} /> ### cancelJob <MemberInfo kind="method" type={`(jobId: <a href='/reference/typescript-api/common/id#id'>ID</a>) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> ### next <MemberInfo kind="method" type={`(queueName: string) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> Should return the next job in the given queue. The implementation is responsible for returning the correct job according to the time of creation. ### update <MemberInfo kind="method" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>) => Promise&#60;void&#62;`} /> Update the job details in the store. ### findOne <MemberInfo kind="method" type={`(id: <a href='/reference/typescript-api/common/id#id'>ID</a>) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> Returns a job by its id. </div>
--- title: "SqlJobQueueStrategy" 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'; ## SqlJobQueueStrategy <GenerationInfo sourceFile="packages/core/src/plugin/default-job-queue-plugin/sql-job-queue-strategy.ts" sourceLine="22" packageName="@vendure/core" /> A <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a> which uses the configured SQL database to persist jobs in the queue. This strategy is used by the <a href='/reference/typescript-api/job-queue/default-job-queue-plugin#defaultjobqueueplugin'>DefaultJobQueuePlugin</a>. ```ts title="Signature" class SqlJobQueueStrategy extends PollingJobQueueStrategy implements InspectableJobQueueStrategy { init(injector: Injector) => ; destroy() => ; add(job: Job<Data>, jobOptions?: JobQueueStrategyJobOptions<Data>) => Promise<Job<Data>>; next(queueName: string) => Promise<Job | undefined>; update(job: Job<any>) => Promise<void>; findMany(options?: JobListOptions) => Promise<PaginatedList<Job>>; findOne(id: ID) => Promise<Job | undefined>; findManyById(ids: ID[]) => Promise<Job[]>; removeSettledJobs(queueNames: string[] = [], olderThan?: Date) => ; } ``` * Extends: <code><a href='/reference/typescript-api/job-queue/polling-job-queue-strategy#pollingjobqueuestrategy'>PollingJobQueueStrategy</a></code> * Implements: <code><a href='/reference/typescript-api/job-queue/inspectable-job-queue-strategy#inspectablejobqueuestrategy'>InspectableJobQueueStrategy</a></code> <div className="members-wrapper"> ### init <MemberInfo kind="method" type={`(injector: <a href='/reference/typescript-api/common/injector#injector'>Injector</a>) => `} /> ### destroy <MemberInfo kind="method" type={`() => `} /> ### add <MemberInfo kind="method" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;, jobOptions?: JobQueueStrategyJobOptions&#60;Data&#62;) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;Data&#62;&#62;`} /> ### next <MemberInfo kind="method" type={`(queueName: string) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> ### update <MemberInfo kind="method" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;any&#62;) => Promise&#60;void&#62;`} /> ### findMany <MemberInfo kind="method" type={`(options?: JobListOptions) => Promise&#60;<a href='/reference/typescript-api/common/paginated-list#paginatedlist'>PaginatedList</a>&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#62;&#62;`} /> ### findOne <MemberInfo kind="method" type={`(id: <a href='/reference/typescript-api/common/id#id'>ID</a>) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a> | undefined&#62;`} /> ### findManyById <MemberInfo kind="method" type={`(ids: <a href='/reference/typescript-api/common/id#id'>ID</a>[]) => Promise&#60;<a href='/reference/typescript-api/job-queue/job#job'>Job</a>[]&#62;`} /> ### removeSettledJobs <MemberInfo kind="method" type={`(queueNames: string[] = [], olderThan?: Date) => `} /> </div>
--- title: "SubscribableJob" 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'; ## SubscribableJob <GenerationInfo sourceFile="packages/core/src/job-queue/subscribable-job.ts" sourceLine="58" packageName="@vendure/core" /> This is a type of Job object that allows you to subscribe to updates to the Job. It is returned by the <a href='/reference/typescript-api/job-queue/#jobqueue'>JobQueue</a>'s `add()` method. Note that the subscription capability is only supported if the <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a> implements the <a href='/reference/typescript-api/job-queue/inspectable-job-queue-strategy#inspectablejobqueuestrategy'>InspectableJobQueueStrategy</a> interface (e.g. the <a href='/reference/typescript-api/job-queue/sql-job-queue-strategy#sqljobqueuestrategy'>SqlJobQueueStrategy</a> does support this). ```ts title="Signature" class SubscribableJob<T extends JobData<T> = any> extends Job<T> { constructor(job: Job<T>, jobQueueStrategy: JobQueueStrategy) updates(options?: JobUpdateOptions) => Observable<JobUpdate<T>>; } ``` * Extends: <code><a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;T&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;T&#62;, jobQueueStrategy: <a href='/reference/typescript-api/job-queue/job-queue-strategy#jobqueuestrategy'>JobQueueStrategy</a>) => SubscribableJob`} /> ### updates <MemberInfo kind="method" type={`(options?: <a href='/reference/typescript-api/job-queue/types#jobupdateoptions'>JobUpdateOptions</a>) => Observable&#60;<a href='/reference/typescript-api/job-queue/types#jobupdate'>JobUpdate</a>&#60;T&#62;&#62;`} /> Returns an Observable stream of updates to the Job. Works by polling the current JobQueueStrategy's `findOne()` method to obtain updates. If this updates are not subscribed to, then no polling occurs. Polling interval, timeout and other options may be configured with an options arguments <a href='/reference/typescript-api/job-queue/types#jobupdateoptions'>JobUpdateOptions</a>. </div>
--- title: "Types" 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'; ## BackoffStrategy <GenerationInfo sourceFile="packages/core/src/job-queue/polling-job-queue-strategy.ts" sourceLine="22" packageName="@vendure/core" /> Defines the backoff strategy used when retrying failed jobs. Returns the delay in ms that should pass before the failed job is retried. ```ts title="Signature" type BackoffStrategy = (queueName: string, attemptsMade: number, job: Job) => number ``` ## JobUpdate <GenerationInfo sourceFile="packages/core/src/job-queue/subscribable-job.ts" sourceLine="22" packageName="@vendure/core" /> Job update status as returned from the <a href='/reference/typescript-api/job-queue/subscribable-job#subscribablejob'>SubscribableJob</a>'s `update()` method. ```ts title="Signature" type JobUpdate<T extends JobData<T>> = Pick< Job<T>, 'id' | 'state' | 'progress' | 'result' | 'error' | 'data' > ``` ## JobUpdateOptions <GenerationInfo sourceFile="packages/core/src/job-queue/subscribable-job.ts" sourceLine="34" packageName="@vendure/core" /> Job update options, that you can specify by calling {@link SubscribableJob.updates updates()} method. ```ts title="Signature" type JobUpdateOptions = { pollInterval?: number; timeoutMs?: number; errorOnFail?: boolean; } ``` <div className="members-wrapper"> ### pollInterval <MemberInfo kind="property" type={`number`} /> ### timeoutMs <MemberInfo kind="property" type={`number`} /> ### errorOnFail <MemberInfo kind="property" type={`boolean`} /> </div> ## CreateQueueOptions <GenerationInfo sourceFile="packages/core/src/job-queue/types.ts" sourceLine="15" packageName="@vendure/core" /> Used to configure a new <a href='/reference/typescript-api/job-queue/#jobqueue'>JobQueue</a> instance. ```ts title="Signature" interface CreateQueueOptions<T extends JobData<T>> { name: string; process: (job: Job<T>) => Promise<any>; } ``` <div className="members-wrapper"> ### name <MemberInfo kind="property" type={`string`} /> The name of the queue, e.g. "image processing", "re-indexing" etc. ### process <MemberInfo kind="property" type={`(job: <a href='/reference/typescript-api/job-queue/job#job'>Job</a>&#60;T&#62;) =&#62; Promise&#60;any&#62;`} /> Defines the work to be done for each job in the queue. The returned promise should resolve when the job is complete, or be rejected in case of an error. </div> ## JobData <GenerationInfo sourceFile="packages/core/src/job-queue/types.ts" sourceLine="37" packageName="@vendure/core" /> A JSON-serializable data type which provides a <a href='/reference/typescript-api/job-queue/job#job'>Job</a> with the data it needs to be processed. ```ts title="Signature" type JobData<T> = JsonCompatible<T> ``` ## JobConfig <GenerationInfo sourceFile="packages/core/src/job-queue/types.ts" sourceLine="46" packageName="@vendure/core" /> Used to instantiate a new <a href='/reference/typescript-api/job-queue/job#job'>Job</a> ```ts title="Signature" interface JobConfig<T extends JobData<T>> { queueName: string; data: T; retries?: number; attempts?: number; id?: ID; state?: JobState; progress?: number; result?: any; error?: any; createdAt?: Date; startedAt?: Date; settledAt?: Date; } ``` <div className="members-wrapper"> ### queueName <MemberInfo kind="property" type={`string`} /> ### data <MemberInfo kind="property" type={`T`} /> ### retries <MemberInfo kind="property" type={`number`} /> ### attempts <MemberInfo kind="property" type={`number`} /> ### id <MemberInfo kind="property" type={`<a href='/reference/typescript-api/common/id#id'>ID</a>`} /> ### state <MemberInfo kind="property" type={`<a href='/reference/typescript-api/common/job-state#jobstate'>JobState</a>`} /> ### progress <MemberInfo kind="property" type={`number`} /> ### result <MemberInfo kind="property" type={`any`} /> ### error <MemberInfo kind="property" type={`any`} /> ### createdAt <MemberInfo kind="property" type={`Date`} /> ### startedAt <MemberInfo kind="property" type={`Date`} /> ### settledAt <MemberInfo kind="property" type={`Date`} /> </div>
--- title: "DefaultLogger" 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'; ## DefaultLogger <GenerationInfo sourceFile="packages/core/src/config/logger/default-logger.ts" sourceLine="25" packageName="@vendure/core" /> The default logger, which logs to the console (stdout) with optional timestamps. Since this logger is part of the default Vendure configuration, you do not need to specify it explicitly in your server config. You would only need to specify it if you wish to change the log level (which defaults to `LogLevel.Info`) or remove the timestamp. *Example* ```ts import { DefaultLogger, LogLevel, VendureConfig } from '@vendure/core'; export config: VendureConfig = { // ... logger: new DefaultLogger({ level: LogLevel.Debug, timestamp: false }), } ``` ```ts title="Signature" class DefaultLogger implements VendureLogger { constructor(options?: { level?: LogLevel; timestamp?: boolean }) setDefaultContext(defaultContext: string) => ; error(message: string, context?: string, trace?: string | undefined) => void; warn(message: string, context?: string) => void; info(message: string, context?: string) => void; verbose(message: string, context?: string) => void; debug(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={`(options?: { level?: <a href='/reference/typescript-api/logger/log-level#loglevel'>LogLevel</a>; timestamp?: boolean }) => DefaultLogger`} /> ### setDefaultContext <MemberInfo kind="method" type={`(defaultContext: string) => `} /> ### error <MemberInfo kind="method" type={`(message: string, context?: string, trace?: string | undefined) => void`} /> ### warn <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### info <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### verbose <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### debug <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> </div>
--- title: "Logger" 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'; ## Logger <GenerationInfo sourceFile="packages/core/src/config/logger/vendure-logger.ts" sourceLine="136" packageName="@vendure/core" /> The Logger is responsible for all logging in a Vendure application. It is intended to be used as a static class: *Example* ```ts import { Logger } from '@vendure/core'; Logger.info(`Some log message`, 'My Vendure Plugin'); ``` The actual implementation - where the logs are written to - is defined by the <a href='/reference/typescript-api/logger/vendure-logger#vendurelogger'>VendureLogger</a> instance configured in the <a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a>. By default, the <a href='/reference/typescript-api/logger/default-logger#defaultlogger'>DefaultLogger</a> is used, which logs to the console. ## Implementing a custom logger A custom logger can be passed to the `logger` config option by creating a class which implements the <a href='/reference/typescript-api/logger/vendure-logger#vendurelogger'>VendureLogger</a> interface. For example, here is how you might go about implementing a logger which logs to a file: *Example* ```ts import { VendureLogger } from '@vendure/core'; import fs from 'fs'; // A simple custom logger which writes all logs to a file. export class SimpleFileLogger implements VendureLogger { private logfile: fs.WriteStream; constructor(logfileLocation: string) { this.logfile = fs.createWriteStream(logfileLocation, { flags: 'w' }); } error(message: string, context?: string) { this.logfile.write(`ERROR: [${context}] ${message}\n`); } warn(message: string, context?: string) { this.logfile.write(`WARN: [${context}] ${message}\n`); } info(message: string, context?: string) { this.logfile.write(`INFO: [${context}] ${message}\n`); } verbose(message: string, context?: string) { this.logfile.write(`VERBOSE: [${context}] ${message}\n`); } debug(message: string, context?: string) { this.logfile.write(`DEBUG: [${context}] ${message}\n`); } } // in the VendureConfig export const config = { // ... logger: new SimpleFileLogger('server.log'), } ``` ```ts title="Signature" class Logger implements LoggerService { logger: VendureLogger error(message: string, context?: string, trace?: string) => void; warn(message: string, context?: string) => void; info(message: string, context?: string) => void; verbose(message: string, context?: string) => void; debug(message: string, context?: string) => void; } ``` * Implements: <code>LoggerService</code> <div className="members-wrapper"> ### logger <MemberInfo kind="property" type={`<a href='/reference/typescript-api/logger/vendure-logger#vendurelogger'>VendureLogger</a>`} /> ### error <MemberInfo kind="method" type={`(message: string, context?: string, trace?: string) => void`} /> ### warn <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### info <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### verbose <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### debug <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> </div>
--- title: "LogLevel" 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'; ## LogLevel <GenerationInfo sourceFile="packages/core/src/config/logger/vendure-logger.ts" sourceLine="9" packageName="@vendure/core" /> An enum of valid logging levels. ```ts title="Signature" enum LogLevel { // Log Errors only. These are usually indicative of some potentially serious issue, so should be acted upon. Error = 0 // Warnings indicate that some situation may require investigation and handling. But not as serious as an Error. Warn = 1 // Logs general information such as startup messages. Info = 2 // Logs additional information Verbose = 3 // Logs detailed info useful in debug scenarios, including stack traces for all errors. In production this would probably generate too much noise. Debug = 4 } ```
--- title: "VendureLogger" 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'; ## VendureLogger <GenerationInfo sourceFile="packages/core/src/config/logger/vendure-logger.ts" sourceLine="47" packageName="@vendure/core" /> The VendureLogger interface defines the shape of a logger service which may be provided in the config. ```ts title="Signature" interface VendureLogger { error(message: string, context?: string, trace?: string): void; warn(message: string, context?: string): void; info(message: string, context?: string): void; verbose(message: string, context?: string): void; debug(message: string, context?: string): void; setDefaultContext?(defaultContext: string): void; } ``` <div className="members-wrapper"> ### error <MemberInfo kind="method" type={`(message: string, context?: string, trace?: string) => void`} /> ### warn <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### info <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### verbose <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### debug <MemberInfo kind="method" type={`(message: string, context?: string) => void`} /> ### setDefaultContext <MemberInfo kind="method" type={`(defaultContext: string) => void`} /> </div>
--- title: "Migration" weight: 10 date: 2023-07-14T16:57:50.191Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # migration
--- title: "GenerateMigration" 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'; ## generateMigration <GenerationInfo sourceFile="packages/core/src/migrate.ts" sourceLine="118" packageName="@vendure/core" /> Generates a new migration file based on any schema changes (e.g. adding or removing CustomFields). See [TypeORM migration docs](https://typeorm.io/#/migrations) for more information about the underlying migration mechanism. ```ts title="Signature" function generateMigration(userConfig: Partial<VendureConfig>, options: MigrationOptions): Promise<string | undefined> ``` 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/migration/migration-options#migrationoptions'>MigrationOptions</a>`} />
--- title: "Migration" 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: "MigrationOptions" 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'; ## MigrationOptions <GenerationInfo sourceFile="packages/core/src/migrate.ts" sourceLine="19" packageName="@vendure/core" /> Configuration for generating a new migration script via <a href='/reference/typescript-api/migration/generate-migration#generatemigration'>generateMigration</a>. ```ts title="Signature" interface MigrationOptions { name: string; outputDir?: string; } ``` <div className="members-wrapper"> ### name <MemberInfo kind="property" type={`string`} /> The name of the migration. The resulting migration script will be named `{TIMESTAMP}-{name}.ts`. ### outputDir <MemberInfo kind="property" type={`string`} /> The output directory of the generated migration scripts. </div>
--- title: "RevertLastMigration" 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'; ## revertLastMigration <GenerationInfo sourceFile="packages/core/src/migrate.ts" sourceLine="89" packageName="@vendure/core" /> Reverts the last applied database migration. See [TypeORM migration docs](https://typeorm.io/#/migrations) for more information about the underlying migration mechanism. ```ts title="Signature" function revertLastMigration(userConfig: Partial<VendureConfig>): void ``` Parameters ### userConfig <MemberInfo kind="parameter" type={`Partial&#60;<a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a>&#62;`} />
--- title: "RunMigrations" 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'; ## runMigrations <GenerationInfo sourceFile="packages/core/src/migrate.ts" sourceLine="40" packageName="@vendure/core" /> Runs any pending database migrations. See [TypeORM migration docs](https://typeorm.io/#/migrations) for more information about the underlying migration mechanism. ```ts title="Signature" function runMigrations(userConfig: Partial<VendureConfig>): Promise<string[]> ``` Parameters ### userConfig <MemberInfo kind="parameter" type={`Partial&#60;<a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a>&#62;`} />
--- title: "BigIntMoneyStrategy" 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'; ## BigIntMoneyStrategy <GenerationInfo sourceFile="packages/core/src/config/entity/bigint-money-strategy.ts" sourceLine="18" packageName="@vendure/core" since="2.0.0" /> A <a href='/reference/typescript-api/money/money-strategy#moneystrategy'>MoneyStrategy</a> that stores monetary values as a `bigint` type in the database, which allows values up to ~9 quadrillion to be stored (limited by JavaScript's `MAX_SAFE_INTEGER` limit). This strategy also slightly differs in the way rounding is performed, with rounding being done _after_ multiplying the unit price, rather than before (as is the case with the <a href='/reference/typescript-api/money/default-money-strategy#defaultmoneystrategy'>DefaultMoneyStrategy</a>. ```ts title="Signature" class BigIntMoneyStrategy implements MoneyStrategy { readonly moneyColumnOptions: ColumnOptions = { type: 'bigint', transformer: { to: (entityValue: number) => { return entityValue; }, from: (databaseValue: string): number => { if (databaseValue == null) { return databaseValue; } const intVal = Number.parseInt(databaseValue, 10); if (!Number.isSafeInteger(intVal)) { Logger.warn(`Monetary value ${databaseValue} is not a safe integer!`); } if (Number.isNaN(intVal)) { Logger.warn(`Monetary value ${databaseValue} is not a number!`); } return intVal; }, }, }; precision = 2; round(value: number, quantity: = 1) => number; } ``` * Implements: <code><a href='/reference/typescript-api/money/money-strategy#moneystrategy'>MoneyStrategy</a></code> <div className="members-wrapper"> ### moneyColumnOptions <MemberInfo kind="property" type={`ColumnOptions`} /> ### precision <MemberInfo kind="property" type={``} /> ### round <MemberInfo kind="method" type={`(value: number, quantity: = 1) => number`} /> </div>
--- title: "DefaultMoneyStrategy" 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'; ## DefaultMoneyStrategy <GenerationInfo sourceFile="packages/core/src/config/entity/default-money-strategy.ts" sourceLine="15" packageName="@vendure/core" since="2.0.0" /> A <a href='/reference/typescript-api/money/money-strategy#moneystrategy'>MoneyStrategy</a> that stores monetary values as a `int` type in the database. The storage configuration and rounding logic replicates the behaviour of Vendure pre-2.0. ```ts title="Signature" class DefaultMoneyStrategy implements MoneyStrategy { readonly moneyColumnOptions: ColumnOptions = { type: 'int', }; readonly precision: number = 2; round(value: number, quantity: = 1) => number; } ``` * Implements: <code><a href='/reference/typescript-api/money/money-strategy#moneystrategy'>MoneyStrategy</a></code> <div className="members-wrapper"> ### moneyColumnOptions <MemberInfo kind="property" type={`ColumnOptions`} /> ### precision <MemberInfo kind="property" type={`number`} /> ### round <MemberInfo kind="method" type={`(value: number, quantity: = 1) => number`} /> </div>
--- title: "Money" 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: "Money Decorator" 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'; ## Money <GenerationInfo sourceFile="packages/core/src/entity/money.decorator.ts" sourceLine="26" packageName="@vendure/core" since="2.0.0" /> Use this decorator for any entity field that is storing a monetary value. This allows the column type to be defined by the configured <a href='/reference/typescript-api/money/money-strategy#moneystrategy'>MoneyStrategy</a>. ```ts title="Signature" function Money(options?: MoneyColumnOptions): void ``` Parameters ### options <MemberInfo kind="parameter" type={`MoneyColumnOptions`} />
--- title: "MoneyStrategy" 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'; ## MoneyStrategy <GenerationInfo sourceFile="packages/core/src/config/entity/money-strategy.ts" sourceLine="63" packageName="@vendure/core" since="2.0.0" /> The MoneyStrategy defines how monetary values are stored and manipulated. The MoneyStrategy is defined in <a href='/reference/typescript-api/configuration/entity-options#entityoptions'>EntityOptions</a>: *Example* ```ts const config: VendureConfig = { entityOptions: { moneyStrategy: new MyCustomMoneyStrategy(), } }; ``` ## Range The <a href='/reference/typescript-api/money/default-money-strategy#defaultmoneystrategy'>DefaultMoneyStrategy</a> uses an `int` field in the database, which puts an effective limit of ~21.4 million on any stored value. For certain use cases (e.g. business sales with very high amounts, or currencies with very large denominations), this may cause issues. In this case, you can use the <a href='/reference/typescript-api/money/big-int-money-strategy#bigintmoneystrategy'>BigIntMoneyStrategy</a> which will use the `bigint` type to store monetary values, giving an effective upper limit of over 9 quadrillion. ## Precision Both the `DefaultMoneyStrategy` and `BigIntMoneyStrategy` store monetary values as integers, representing the price in the minor units of the currency (i.e. _cents_ in USD or _pennies_ in GBP). Since v2.2.0, you can configure the precision of the stored values via the `precision` property of the strategy. Changing the precision has **no effect** on the stored value. It is merely a hint to the UI as to how many decimal places to display. *Example* ```ts import { DefaultMoneyStrategy, VendureConfig } from '@vendure/core'; export class ThreeDecimalPlacesMoneyStrategy extends DefaultMoneyStrategy { readonly precision = 3; } export const config: VendureConfig = { // ... entityOptions: { moneyStrategy: new ThreeDecimalPlacesMoneyStrategy(), } }; ``` :::info This is configured via the `entityOptions.moneyStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface MoneyStrategy extends InjectableStrategy { readonly moneyColumnOptions: ColumnOptions; readonly precision?: number; round(value: number, quantity?: number): number; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### moneyColumnOptions <MemberInfo kind="property" type={`ColumnOptions`} /> Defines the TypeORM column used to store monetary values. ### precision <MemberInfo kind="property" type={`number`} default="2" since="2.2.0" /> Defines the precision (i.e. number of decimal places) represented by the monetary values. For example, consider a product variant with a price value of `12345`. - If the precision is `2`, then the price is `123.45`. - If the precision is `3`, then the price is `12.345`. Changing the precision has **no effect** on the stored value. It is merely a hint to the UI as to how many decimal places to display. ### round <MemberInfo kind="method" type={`(value: number, quantity?: number) => number`} /> Defines the logic used to round monetary values. For instance, the default behavior in the <a href='/reference/typescript-api/money/default-money-strategy#defaultmoneystrategy'>DefaultMoneyStrategy</a> is to round the value, then multiply. ```ts return Math.round(value) * quantity; ``` However, it may be desirable to instead round only _after_ the unit amount has been multiplied. In this case you can define a custom strategy with logic like this: ```ts return Math.round(value * quantity); ``` </div>
--- title: "RoundMoney" 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'; ## roundMoney <GenerationInfo sourceFile="packages/core/src/common/round-money.ts" sourceLine="13" packageName="@vendure/core" since="2.0.0" /> Rounds a monetary value according to the configured <a href='/reference/typescript-api/money/money-strategy#moneystrategy'>MoneyStrategy</a>. ```ts title="Signature" function roundMoney(value: number, quantity: = 1): number ``` Parameters ### value <MemberInfo kind="parameter" type={`number`} /> ### quantity <MemberInfo kind="parameter" type={``} />
--- title: "Orders" weight: 10 date: 2023-07-14T16:57:49.580Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # orders
--- title: "ActiveOrderService" 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'; ## ActiveOrderService <GenerationInfo sourceFile="packages/core/src/service/helpers/active-order/active-order.service.ts" sourceLine="17" packageName="@vendure/core" /> This helper class is used to get a reference to the active Order from the current RequestContext. ```ts title="Signature" class ActiveOrderService { constructor(sessionService: SessionService, orderService: OrderService, connection: TransactionalConnection, configService: ConfigService) getOrderFromContext(ctx: RequestContext) => Promise<Order | undefined>; getOrderFromContext(ctx: RequestContext, createIfNotExists: true) => Promise<Order>; getOrderFromContext(ctx: RequestContext, createIfNotExists: = false) => Promise<Order | undefined>; getActiveOrder(ctx: RequestContext, input: { [strategyName: string]: any } | undefined) => Promise<Order | undefined>; getActiveOrder(ctx: RequestContext, input: { [strategyName: string]: any } | undefined, createIfNotExists: true) => Promise<Order>; getActiveOrder(ctx: RequestContext, input: { [strategyName: string]: Record<string, any> | undefined } | undefined, createIfNotExists: = false) => Promise<Order | undefined>; } ``` <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(sessionService: <a href='/reference/typescript-api/services/session-service#sessionservice'>SessionService</a>, orderService: <a href='/reference/typescript-api/services/order-service#orderservice'>OrderService</a>, connection: <a href='/reference/typescript-api/data-access/transactional-connection#transactionalconnection'>TransactionalConnection</a>, configService: ConfigService) => ActiveOrderService`} /> ### getOrderFromContext <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>) => Promise&#60;<a href='/reference/typescript-api/entities/order#order'>Order</a> | undefined&#62;`} /> Gets the active Order object from the current Session. Optionally can create a new Order if no active Order exists. Intended to be used at the Resolver layer for those resolvers that depend upon an active Order being present. ### getOrderFromContext <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, createIfNotExists: true) => Promise&#60;<a href='/reference/typescript-api/entities/order#order'>Order</a>&#62;`} /> ### getOrderFromContext <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, createIfNotExists: = false) => Promise&#60;<a href='/reference/typescript-api/entities/order#order'>Order</a> | undefined&#62;`} /> ### getActiveOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, input: { [strategyName: string]: any } | undefined) => Promise&#60;<a href='/reference/typescript-api/entities/order#order'>Order</a> | undefined&#62;`} since="1.9.0" /> Retrieves the active Order based on the configured <a href='/reference/typescript-api/orders/active-order-strategy#activeorderstrategy'>ActiveOrderStrategy</a>. ### getActiveOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, input: { [strategyName: string]: any } | undefined, createIfNotExists: true) => Promise&#60;<a href='/reference/typescript-api/entities/order#order'>Order</a>&#62;`} /> ### getActiveOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, input: { [strategyName: string]: Record&#60;string, any&#62; | undefined } | undefined, createIfNotExists: = false) => Promise&#60;<a href='/reference/typescript-api/entities/order#order'>Order</a> | undefined&#62;`} /> </div>
--- title: "ActiveOrderStrategy" 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'; ## ActiveOrderStrategy <GenerationInfo sourceFile="packages/core/src/config/order/active-order-strategy.ts" sourceLine="127" packageName="@vendure/core" since="1.9.0" /> This strategy is used to determine the active Order for all order-related operations in the Shop API. By default, all the Shop API operations that relate to the active Order (e.g. `activeOrder`, `addItemToOrder`, `applyCouponCode` etc.) will implicitly create a new Order and set it on the current Session, and then read the session to obtain the active Order. This behaviour is defined by the <a href='/reference/typescript-api/orders/default-active-order-strategy#defaultactiveorderstrategy'>DefaultActiveOrderStrategy</a>. The `InputType` generic argument should correspond to the input type defined by the `defineInputType()` method. When `defineInputType()` is used, then the following Shop API operations will receive an additional `activeOrderInput` argument allowing the active order input to be specified: - `activeOrder` - `eligibleShippingMethods` - `eligiblePaymentMethods` - `nextOrderStates` - `addItemToOrder` - `adjustOrderLine` - `removeOrderLine` - `removeAllOrderLines` - `applyCouponCode` - `removeCouponCode` - `addPaymentToOrder` - `setCustomerForOrder` - `setOrderShippingAddress` - `setOrderBillingAddress` - `setOrderShippingMethod` - `setOrderCustomFields` - `transitionOrderToState` *Example* ```GraphQL {hl_lines=[5]} mutation AddItemToOrder { addItemToOrder( productVariantId: 42, quantity: 1, activeOrderInput: { token: "123456" } ) { ...on Order { id # ...etc } } } ``` *Example* ```ts import { ID } from '@vendure/common/lib/shared-types'; import { ActiveOrderStrategy, CustomerService, idsAreEqual, Injector, Order, OrderService, RequestContext, TransactionalConnection, } from '@vendure/core'; import gql from 'graphql-tag'; // This strategy assumes a "orderToken" custom field is defined on the Order // entity, and uses that token to perform a lookup to determine the active Order. // // Additionally, it does _not_ define a `createActiveOrder()` method, which // means that a custom mutation would be required to create the initial Order in // the first place and set the "orderToken" custom field. class TokenActiveOrderStrategy implements ActiveOrderStrategy<{ token: string }> { readonly name = 'orderToken'; private connection: TransactionalConnection; private orderService: OrderService; init(injector: Injector) { this.connection = injector.get(TransactionalConnection); this.orderService = injector.get(OrderService); } defineInputType = () => gql` input OrderTokenActiveOrderInput { token: String } `; async determineActiveOrder(ctx: RequestContext, input: { token: string }) { const qb = this.connection .getRepository(ctx, Order) .createQueryBuilder('order') .leftJoinAndSelect('order.customer', 'customer') .leftJoinAndSelect('customer.user', 'user') .where('order.customFields.orderToken = :orderToken', { orderToken: input.token }); const order = await qb.getOne(); if (!order) { return; } // Ensure the active user is the owner of this Order const orderUserId = order.customer && order.customer.user && order.customer.user.id; if (order.customer && idsAreEqual(orderUserId, ctx.activeUserId)) { return order; } } } // in vendure-config.ts export const config = { // ... orderOptions: { activeOrderStrategy: new TokenActiveOrderStrategy(), }, } ``` ```ts title="Signature" interface ActiveOrderStrategy<InputType extends Record<string, any> | void = void> extends InjectableStrategy { readonly name: string; defineInputType?: () => DocumentNode; createActiveOrder?: (ctx: RequestContext, input: InputType) => Promise<Order>; determineActiveOrder(ctx: RequestContext, input: InputType): Promise<Order | undefined>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### name <MemberInfo kind="property" type={`string`} /> The name of the strategy, e.g. "orderByToken", which will also be used as the field name in the ActiveOrderInput type. ### defineInputType <MemberInfo kind="property" type={`() =&#62; DocumentNode`} /> Defines the type of the GraphQL Input object expected by the `activeOrderInput` input argument. *Example* For example, given the following: ```ts defineInputType() { return gql` input OrderTokenInput { token: String! } `; } ``` assuming the strategy name is "orderByToken", then the resulting call to `activeOrder` (or any of the other affected Shop API operations) would look like: ```GraphQL activeOrder(activeOrderInput: { orderByToken: { token: "foo" } }) { # ... } ``` **Note:** if more than one graphql `input` type is being defined (as in a nested input type), then the _first_ input will be assumed to be the top-level input. ### createActiveOrder <MemberInfo kind="property" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, input: InputType) =&#62; Promise&#60;<a href='/reference/typescript-api/entities/order#order'>Order</a>&#62;`} /> Certain mutations such as `addItemToOrder` can automatically create a new Order if one does not exist. In these cases, this method will be called to create the new Order. If automatic creation of an Order does not make sense in your strategy, then leave this method undefined. You'll then need to take care of creating an order manually by defining a custom mutation. ### determineActiveOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, input: InputType) => Promise&#60;<a href='/reference/typescript-api/entities/order#order'>Order</a> | undefined&#62;`} /> This method is used to determine the active Order based on the current RequestContext in addition to any input values provided, as defined by the `defineInputType` method of this strategy. Note that this method is invoked frequently, so you should aim to keep it efficient. The returned Order, for example, does not need to have its various relations joined. </div>
--- title: "ChangedPriceHandlingStrategy" 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'; ## ChangedPriceHandlingStrategy <GenerationInfo sourceFile="packages/core/src/config/order/changed-price-handling-strategy.ts" sourceLine="24" packageName="@vendure/core" /> This strategy defines how we handle the situation where an item exists in an Order, and then later on another is added but in the meantime the price of the ProductVariant has changed. By default, the latest price will be used. Any price changes resulting from using a newer price will be reflected in the GraphQL `OrderLine.unitPrice[WithTax]ChangeSinceAdded` field. :::info This is configured via the `orderOptions.changedPriceHandlingStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface ChangedPriceHandlingStrategy extends InjectableStrategy { handlePriceChange( ctx: RequestContext, current: PriceCalculationResult, orderLine: OrderLine, order: Order, ): PriceCalculationResult | Promise<PriceCalculationResult>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### handlePriceChange <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, current: <a href='/reference/typescript-api/common/price-calculation-result#pricecalculationresult'>PriceCalculationResult</a>, orderLine: <a href='/reference/typescript-api/entities/order-line#orderline'>OrderLine</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/common/price-calculation-result#pricecalculationresult'>PriceCalculationResult</a> | Promise&#60;<a href='/reference/typescript-api/common/price-calculation-result#pricecalculationresult'>PriceCalculationResult</a>&#62;`} /> This method is called when adding to or adjusting OrderLines, if the latest price (as determined by the ProductVariant price, potentially modified by the configured <a href='/reference/typescript-api/orders/order-item-price-calculation-strategy#orderitempricecalculationstrategy'>OrderItemPriceCalculationStrategy</a>) differs from the initial price at the time that the OrderLine was created. </div>
--- title: "CustomOrderStates" 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'; ## CustomOrderStates <GenerationInfo sourceFile="packages/core/src/service/helpers/order-state-machine/order-state.ts" sourceLine="11" packageName="@vendure/core" /> An interface to extend standard <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>. ```ts title="Signature" interface CustomOrderStates { } ```
--- title: "DefaultActiveOrderStrategy" 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'; ## DefaultActiveOrderStrategy <GenerationInfo sourceFile="packages/core/src/config/order/default-active-order-strategy.ts" sourceLine="18" packageName="@vendure/core" since="1.9.0" /> The default <a href='/reference/typescript-api/orders/active-order-strategy#activeorderstrategy'>ActiveOrderStrategy</a>, which uses the current <a href='/reference/typescript-api/entities/session#session'>Session</a> to determine the active Order, and requires no additional input in the Shop API since it is based on the session which is part of the RequestContext. ```ts title="Signature" class DefaultActiveOrderStrategy implements ActiveOrderStrategy { name: 'default-active-order-strategy'; init(injector: Injector) => ; createActiveOrder(ctx: RequestContext) => ; determineActiveOrder(ctx: RequestContext) => ; } ``` * Implements: <code><a href='/reference/typescript-api/orders/active-order-strategy#activeorderstrategy'>ActiveOrderStrategy</a></code> <div className="members-wrapper"> ### name <MemberInfo kind="property" type={`'default-active-order-strategy'`} /> ### init <MemberInfo kind="method" type={`(injector: <a href='/reference/typescript-api/common/injector#injector'>Injector</a>) => `} /> ### createActiveOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>) => `} /> ### determineActiveOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>) => `} /> </div>
--- title: "DefaultGuestCheckoutStrategy" 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'; ## DefaultGuestCheckoutStrategy <GenerationInfo sourceFile="packages/core/src/config/order/default-guest-checkout-strategy.ts" sourceLine="64" packageName="@vendure/core" since="2.0.0" /> The default implementation of the <a href='/reference/typescript-api/orders/guest-checkout-strategy#guestcheckoutstrategy'>GuestCheckoutStrategy</a>. This strategy allows guest checkouts by default, but can be configured to disallow them. *Example* ```ts import { DefaultGuestCheckoutStrategy, VendureConfig } from '@vendure/core'; export const config: VendureConfig = { orderOptions: { guestCheckoutStrategy: new DefaultGuestCheckoutStrategy({ allowGuestCheckouts: false, allowGuestCheckoutForRegisteredCustomers: false, }), }, // ... }; ``` ```ts title="Signature" class DefaultGuestCheckoutStrategy implements GuestCheckoutStrategy { init(injector: Injector) => ; constructor(options?: DefaultGuestCheckoutStrategyOptions) setCustomerForOrder(ctx: RequestContext, order: Order, input: CreateCustomerInput) => Promise<ErrorResultUnion<SetCustomerForOrderResult, Customer>>; } ``` * Implements: <code><a href='/reference/typescript-api/orders/guest-checkout-strategy#guestcheckoutstrategy'>GuestCheckoutStrategy</a></code> <div className="members-wrapper"> ### init <MemberInfo kind="method" type={`(injector: <a href='/reference/typescript-api/common/injector#injector'>Injector</a>) => `} /> ### constructor <MemberInfo kind="method" type={`(options?: <a href='/reference/typescript-api/orders/default-guest-checkout-strategy#defaultguestcheckoutstrategyoptions'>DefaultGuestCheckoutStrategyOptions</a>) => DefaultGuestCheckoutStrategy`} /> ### setCustomerForOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>, input: CreateCustomerInput) => Promise&#60;<a href='/reference/typescript-api/errors/error-result-union#errorresultunion'>ErrorResultUnion</a>&#60;SetCustomerForOrderResult, <a href='/reference/typescript-api/entities/customer#customer'>Customer</a>&#62;&#62;`} /> </div> ## DefaultGuestCheckoutStrategyOptions <GenerationInfo sourceFile="packages/core/src/config/order/default-guest-checkout-strategy.ts" sourceLine="20" packageName="@vendure/core" since="2.0.0" /> Options available for the <a href='/reference/typescript-api/orders/default-guest-checkout-strategy#defaultguestcheckoutstrategy'>DefaultGuestCheckoutStrategy</a>. ```ts title="Signature" interface DefaultGuestCheckoutStrategyOptions { allowGuestCheckouts?: boolean; allowGuestCheckoutForRegisteredCustomers?: boolean; } ``` <div className="members-wrapper"> ### allowGuestCheckouts <MemberInfo kind="property" type={`boolean`} default="true" /> Whether to allow guest checkouts. ### allowGuestCheckoutForRegisteredCustomers <MemberInfo kind="property" type={`boolean`} default="false" /> Whether to allow guest checkouts for customers who already have an account. Note that when this is enabled, the details provided in the `CreateCustomerInput` will overwrite the existing customer details of the registered customer. </div>
--- title: "DefaultOrderItemPriceCalculationStrategy" 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'; ## DefaultOrderItemPriceCalculationStrategy <GenerationInfo sourceFile="packages/core/src/config/order/default-order-item-price-calculation-strategy.ts" sourceLine="14" packageName="@vendure/core" /> The default <a href='/reference/typescript-api/orders/order-item-price-calculation-strategy#orderitempricecalculationstrategy'>OrderItemPriceCalculationStrategy</a>, which simply passes through the price of the ProductVariant without performing any calculations ```ts title="Signature" class DefaultOrderItemPriceCalculationStrategy implements OrderItemPriceCalculationStrategy { calculateUnitPrice(ctx: RequestContext, productVariant: ProductVariant) => PriceCalculationResult | Promise<PriceCalculationResult>; } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-item-price-calculation-strategy#orderitempricecalculationstrategy'>OrderItemPriceCalculationStrategy</a></code> <div className="members-wrapper"> ### calculateUnitPrice <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, productVariant: <a href='/reference/typescript-api/entities/product-variant#productvariant'>ProductVariant</a>) => <a href='/reference/typescript-api/common/price-calculation-result#pricecalculationresult'>PriceCalculationResult</a> | Promise&#60;<a href='/reference/typescript-api/common/price-calculation-result#pricecalculationresult'>PriceCalculationResult</a>&#62;`} /> </div>
--- title: "DefaultOrderPlacedStrategy" 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'; ## DefaultOrderPlacedStrategy <GenerationInfo sourceFile="packages/core/src/config/order/default-order-placed-strategy.ts" sourceLine="14" packageName="@vendure/core" /> The default <a href='/reference/typescript-api/orders/order-placed-strategy#orderplacedstrategy'>OrderPlacedStrategy</a>. The order is set as "placed" when it transitions from 'ArrangingPayment' to either 'PaymentAuthorized' or 'PaymentSettled'. ```ts title="Signature" class DefaultOrderPlacedStrategy implements OrderPlacedStrategy { shouldSetAsPlaced(ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order) => boolean; } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-placed-strategy#orderplacedstrategy'>OrderPlacedStrategy</a></code> <div className="members-wrapper"> ### shouldSetAsPlaced <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, fromState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, toState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => boolean`} /> </div>
--- title: "DefaultStockAllocationStrategy" 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'; ## DefaultStockAllocationStrategy <GenerationInfo sourceFile="packages/core/src/config/order/default-stock-allocation-strategy.ts" sourceLine="14" packageName="@vendure/core" /> Allocates stock when the Order transitions from `ArrangingPayment` to either `PaymentAuthorized` or `PaymentSettled`. ```ts title="Signature" class DefaultStockAllocationStrategy implements StockAllocationStrategy { shouldAllocateStock(ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order) => boolean | Promise<boolean>; } ``` * Implements: <code><a href='/reference/typescript-api/orders/stock-allocation-strategy#stockallocationstrategy'>StockAllocationStrategy</a></code> <div className="members-wrapper"> ### shouldAllocateStock <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, fromState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, toState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => boolean | Promise&#60;boolean&#62;`} /> </div>
--- title: "GuestCheckoutStrategy" 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'; ## GuestCheckoutStrategy <GenerationInfo sourceFile="packages/core/src/config/order/guest-checkout-strategy.ts" sourceLine="33" packageName="@vendure/core" since="2.0.0" /> A strategy that determines how to deal with guest checkouts - i.e. when a customer checks out without being logged in. For example, a strategy could be used to implement business rules such as: - No guest checkouts allowed - No guest checkouts allowed for customers who already have an account - No guest checkouts allowed for customers who have previously placed an order - Allow guest checkouts, but create a new Customer entity if the email address is already in use - Allow guest checkouts, but update the existing Customer entity if the email address is already in use :::info This is configured via the `orderOptions.guestCheckoutStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface GuestCheckoutStrategy extends InjectableStrategy { setCustomerForOrder( ctx: RequestContext, order: Order, input: CreateCustomerInput, ): | ErrorResultUnion<SetCustomerForOrderResult, Customer> | Promise<ErrorResultUnion<SetCustomerForOrderResult, Customer>>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### setCustomerForOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>, input: CreateCustomerInput) => | <a href='/reference/typescript-api/errors/error-result-union#errorresultunion'>ErrorResultUnion</a>&#60;SetCustomerForOrderResult, <a href='/reference/typescript-api/entities/customer#customer'>Customer</a>&#62; | Promise&#60;<a href='/reference/typescript-api/errors/error-result-union#errorresultunion'>ErrorResultUnion</a>&#60;SetCustomerForOrderResult, <a href='/reference/typescript-api/entities/customer#customer'>Customer</a>&#62;&#62;`} /> This method is called when the `setCustomerForOrder` mutation is executed. It should return either a Customer object or an ErrorResult. </div>
--- title: "Orders" 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: "Merge Strategies" 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'; ## MergeOrdersStrategy <GenerationInfo sourceFile="packages/core/src/config/order/merge-orders-strategy.ts" sourceLine="15" packageName="@vendure/core" /> Merges both Orders. If the guest order contains items which are already in the existing Order, the guest Order quantity will replace that of the existing Order. ```ts title="Signature" class MergeOrdersStrategy implements OrderMergeStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order) => MergedOrderLine[]; } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-merge-strategy#ordermergestrategy'>OrderMergeStrategy</a></code> <div className="members-wrapper"> ### merge <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, guestOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>, existingOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/orders/order-merge-strategy#mergedorderline'>MergedOrderLine</a>[]`} /> </div> ## UseExistingStrategy <GenerationInfo sourceFile="packages/core/src/config/order/use-existing-strategy.ts" sourceLine="13" packageName="@vendure/core" /> The guest order is discarded and the existing order is used as the active order. ```ts title="Signature" class UseExistingStrategy implements OrderMergeStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order) => MergedOrderLine[]; } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-merge-strategy#ordermergestrategy'>OrderMergeStrategy</a></code> <div className="members-wrapper"> ### merge <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, guestOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>, existingOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/orders/order-merge-strategy#mergedorderline'>MergedOrderLine</a>[]`} /> </div> ## UseGuestIfExistingEmptyStrategy <GenerationInfo sourceFile="packages/core/src/config/order/use-guest-if-existing-empty-strategy.ts" sourceLine="13" packageName="@vendure/core" /> If the existing order is empty, then the guest order is used. Otherwise the existing order is used. ```ts title="Signature" class UseGuestIfExistingEmptyStrategy implements OrderMergeStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order) => MergedOrderLine[]; } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-merge-strategy#ordermergestrategy'>OrderMergeStrategy</a></code> <div className="members-wrapper"> ### merge <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, guestOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>, existingOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/orders/order-merge-strategy#mergedorderline'>MergedOrderLine</a>[]`} /> </div> ## UseGuestStrategy <GenerationInfo sourceFile="packages/core/src/config/order/use-guest-strategy.ts" sourceLine="13" packageName="@vendure/core" /> Any existing order is discarded and the guest order is set as the active order. ```ts title="Signature" class UseGuestStrategy implements OrderMergeStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order) => MergedOrderLine[]; } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-merge-strategy#ordermergestrategy'>OrderMergeStrategy</a></code> <div className="members-wrapper"> ### merge <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, guestOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>, existingOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/orders/order-merge-strategy#mergedorderline'>MergedOrderLine</a>[]`} /> </div>
--- title: "OrderByCodeAccessStrategy" 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'; ## OrderByCodeAccessStrategy <GenerationInfo sourceFile="packages/core/src/config/order/order-by-code-access-strategy.ts" sourceLine="38" packageName="@vendure/core" since="1.1.0" /> The OrderByCodeAccessStrategy determines how access to a placed Order via the orderByCode query is granted. With a custom strategy anonymous access could be made permanent or tied to specific conditions like IP range or an Order status. *Example* This example grants access to the requested Order to anyone – unless it's Monday. ```ts export class NotMondayOrderByCodeAccessStrategy implements OrderByCodeAccessStrategy { canAccessOrder(ctx: RequestContext, order: Order): boolean { const MONDAY = 1; const today = (new Date()).getDay(); return today !== MONDAY; } } ``` :::info This is configured via the `orderOptions.orderByCodeAccessStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface OrderByCodeAccessStrategy extends InjectableStrategy { canAccessOrder(ctx: RequestContext, order: Order): boolean | Promise<boolean>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### canAccessOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => boolean | Promise&#60;boolean&#62;`} /> Gives or denies permission to access the requested Order </div> ## DefaultOrderByCodeAccessStrategy <GenerationInfo sourceFile="packages/core/src/config/order/order-by-code-access-strategy.ts" sourceLine="57" packageName="@vendure/core" /> The default OrderByCodeAccessStrategy used by Vendure. It permitts permanent access to the Customer owning the Order and anyone within a given time period after placing the Order (defaults to 2h). ```ts title="Signature" class DefaultOrderByCodeAccessStrategy implements OrderByCodeAccessStrategy { constructor(anonymousAccessDuration: string) canAccessOrder(ctx: RequestContext, order: Order) => boolean; } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-by-code-access-strategy#orderbycodeaccessstrategy'>OrderByCodeAccessStrategy</a></code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(anonymousAccessDuration: string) => DefaultOrderByCodeAccessStrategy`} /> ### canAccessOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => boolean`} /> </div>
--- title: "OrderCodeStrategy" 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'; ## OrderCodeStrategy <GenerationInfo sourceFile="packages/core/src/config/order/order-code-strategy.ts" sourceLine="39" packageName="@vendure/core" /> The OrderCodeStrategy determines how Order codes are generated. A custom strategy can be defined which e.g. integrates with an existing system to generate a code: :::info This is configured via the `orderOptions.orderCodeStrategy` property of your VendureConfig. ::: *Example* ```ts class MyOrderCodeStrategy implements OrderCodeStrategy { // Some imaginary service which calls out to an existing external // order management system. private mgmtService: ExternalOrderManagementService; init(injector: Injector) { this.mgmtService = injector.get(ExternalOrderManagementService); } async generate(ctx: RequestContext) { const result = await this.mgmtService.getAvailableOrderParams(); return result.code; } } ``` ```ts title="Signature" interface OrderCodeStrategy extends InjectableStrategy { generate(ctx: RequestContext): string | Promise<string>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### generate <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>) => string | Promise&#60;string&#62;`} /> Generates the order code. </div> ## DefaultOrderCodeStrategy <GenerationInfo sourceFile="packages/core/src/config/order/order-code-strategy.ts" sourceLine="55" packageName="@vendure/core" /> The default OrderCodeStrategy generates a random string consisting of 16 uppercase letters and numbers. ```ts title="Signature" class DefaultOrderCodeStrategy implements OrderCodeStrategy { generate(ctx: RequestContext) => string; } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-code-strategy#ordercodestrategy'>OrderCodeStrategy</a></code> <div className="members-wrapper"> ### generate <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>) => string`} /> </div>
--- title: "OrderItemPriceCalculationStrategy" 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'; ## OrderItemPriceCalculationStrategy <GenerationInfo sourceFile="packages/core/src/config/order/order-item-price-calculation-strategy.ts" sourceLine="60" packageName="@vendure/core" /> The OrderItemPriceCalculationStrategy defines the listPrice of an OrderLine when adding an item to an Order. By default the <a href='/reference/typescript-api/orders/default-order-item-price-calculation-strategy#defaultorderitempricecalculationstrategy'>DefaultOrderItemPriceCalculationStrategy</a> is used. :::info This is configured via the `orderOptions.orderItemPriceCalculationStrategy` property of your VendureConfig. ::: ### When is the strategy invoked ? * addItemToOrder (only on the new order line) * adjustOrderLine (only on the adjusted order line) * setOrderShippingAddress (on all order lines) * setOrderBillingAddress (on all order lines) ### OrderItemPriceCalculationStrategy vs Promotions Both the OrderItemPriceCalculationStrategy and Promotions can be used to alter the price paid for a product. The main difference is when a Promotion is applied, it adds a `discount` line to the Order, and the regular price is used for the value of `OrderLine.listPrice` property, whereas the OrderItemPriceCalculationStrategy actually alters the value of `OrderLine.listPrice` itself, and does not add any discounts to the Order. Use OrderItemPriceCalculationStrategy if: * The price calculation is based on the properties of the ProductVariant and any CustomFields specified on the OrderLine, for example via a product configurator. * The logic is a permanent part of your business requirements. Use Promotions if: * You want to implement "discounts" and "special offers" * The calculation is not a permanent part of your business requirements. * The price depends on dynamic aspects such as quantities and which other ProductVariants are in the Order. * The configuration of the logic needs to be manipulated via the Admin UI. ### Example use-cases A custom OrderItemPriceCalculationStrategy can be used to implement things like: * A gift-wrapping service, where a boolean custom field is defined on the OrderLine. If `true`, a gift-wrapping surcharge would be added to the price. * A product-configurator where e.g. various finishes, colors, and materials can be selected and stored as OrderLine custom fields (see [the Custom Fields guide](/guides/developer-guide/custom-fields/). * Price lists or bulk pricing, where different price bands are stored e.g. in a customField on the ProductVariant, and this is used to calculate the price based on the current quantity. ```ts title="Signature" interface OrderItemPriceCalculationStrategy extends InjectableStrategy { calculateUnitPrice( ctx: RequestContext, productVariant: ProductVariant, orderLineCustomFields: { [key: string]: any }, order: Order, quantity: number, ): PriceCalculationResult | Promise<PriceCalculationResult>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### calculateUnitPrice <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, productVariant: <a href='/reference/typescript-api/entities/product-variant#productvariant'>ProductVariant</a>, orderLineCustomFields: { [key: string]: any }, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>, quantity: number) => <a href='/reference/typescript-api/common/price-calculation-result#pricecalculationresult'>PriceCalculationResult</a> | Promise&#60;<a href='/reference/typescript-api/common/price-calculation-result#pricecalculationresult'>PriceCalculationResult</a>&#62;`} /> Receives the ProductVariant to be added to the Order as well as any OrderLine custom fields and returns the price for a single unit. Note: if you have any `relation` type custom fields defined on the OrderLine entity, they will only be passed in to this method if they are set to `eager: true`. Otherwise, you can use the <a href='/reference/typescript-api/data-access/entity-hydrator#entityhydrator'>EntityHydrator</a> to join the missing relations. Note: the `quantity` argument was added in v2.0.0 </div>
--- title: "OrderMergeStrategy" 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'; ## OrderMergeStrategy <GenerationInfo sourceFile="packages/core/src/config/order/order-merge-strategy.ts" sourceLine="48" packageName="@vendure/core" /> An OrderMergeStrategy defines what happens when a Customer with an existing Order signs in with a guest Order, where both Orders may contain differing OrderLines. Somehow these differing OrderLines need to be reconciled into a single collection of OrderLines. The OrderMergeStrategy defines the rules governing this reconciliation. :::info This is configured via the `orderOptions.mergeStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface OrderMergeStrategy extends InjectableStrategy { merge(ctx: RequestContext, guestOrder: Order, existingOrder: Order): MergedOrderLine[]; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### merge <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, guestOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>, existingOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/orders/order-merge-strategy#mergedorderline'>MergedOrderLine</a>[]`} /> Merges the lines of the guest Order with those of the existing Order which is associated with the active customer. </div> ## MergedOrderLine <GenerationInfo sourceFile="packages/core/src/config/order/order-merge-strategy.ts" sourceLine="15" packageName="@vendure/core" /> The result of the <a href='/reference/typescript-api/orders/order-merge-strategy#ordermergestrategy'>OrderMergeStrategy</a> `merge` method. ```ts title="Signature" interface MergedOrderLine { orderLineId: ID; quantity: number; customFields?: any; } ``` <div className="members-wrapper"> ### orderLineId <MemberInfo kind="property" type={`<a href='/reference/typescript-api/common/id#id'>ID</a>`} /> ### quantity <MemberInfo kind="property" type={`number`} /> ### customFields <MemberInfo kind="property" type={`any`} /> </div>
--- title: "OrderOptions" 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'; ## OrderOptions <GenerationInfo sourceFile="packages/core/src/config/vendure-config.ts" sourceLine="482" packageName="@vendure/core" /> ```ts title="Signature" interface OrderOptions { orderItemsLimit?: number; orderLineItemsLimit?: number; orderItemPriceCalculationStrategy?: OrderItemPriceCalculationStrategy; process?: Array<OrderProcess<any>>; stockAllocationStrategy?: StockAllocationStrategy; mergeStrategy?: OrderMergeStrategy; checkoutMergeStrategy?: OrderMergeStrategy; orderCodeStrategy?: OrderCodeStrategy; orderByCodeAccessStrategy?: OrderByCodeAccessStrategy; changedPriceHandlingStrategy?: ChangedPriceHandlingStrategy; orderPlacedStrategy?: OrderPlacedStrategy; activeOrderStrategy?: ActiveOrderStrategy<any> | Array<ActiveOrderStrategy<any>>; orderSellerStrategy?: OrderSellerStrategy; guestCheckoutStrategy?: GuestCheckoutStrategy; } ``` <div className="members-wrapper"> ### orderItemsLimit <MemberInfo kind="property" type={`number`} default="999" /> The maximum number of individual items allowed in a single order. This option exists to prevent excessive resource usage when dealing with very large orders. For example, if an order contains a million items, then any operations on that order (modifying a quantity, adding or removing an item) will require Vendure to loop through all million items to perform price calculations against active promotions and taxes. This can have a significant performance impact for very large values. Attempting to exceed this limit will cause Vendure to throw a {@link OrderItemsLimitError}. ### orderLineItemsLimit <MemberInfo kind="property" type={`number`} default="999" /> The maximum number of items allowed per order line. This option is an addition on the `orderItemsLimit` for more granular control. Note `orderItemsLimit` is still important in order to prevent excessive resource usage. Attempting to exceed this limit will cause Vendure to throw a {@link OrderItemsLimitError}. ### orderItemPriceCalculationStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/order-item-price-calculation-strategy#orderitempricecalculationstrategy'>OrderItemPriceCalculationStrategy</a>`} default="DefaultPriceCalculationStrategy" /> Defines the logic used to calculate the unit price of an OrderLine when adding an item to an Order. ### process <MemberInfo kind="property" type={`Array&#60;<a href='/reference/typescript-api/orders/order-process#orderprocess'>OrderProcess</a>&#60;any&#62;&#62;`} default="[]" /> Allows the definition of custom states and transition logic for the order process state machine. Takes an array of objects implementing the <a href='/reference/typescript-api/orders/order-process#orderprocess'>OrderProcess</a> interface. ### stockAllocationStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/stock-allocation-strategy#stockallocationstrategy'>StockAllocationStrategy</a>`} default="<a href='/reference/typescript-api/orders/default-stock-allocation-strategy#defaultstockallocationstrategy'>DefaultStockAllocationStrategy</a>" /> Determines the point of the order process at which stock gets allocated. ### mergeStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/order-merge-strategy#ordermergestrategy'>OrderMergeStrategy</a>`} default="<a href='/reference/typescript-api/orders/merge-strategies#mergeordersstrategy'>MergeOrdersStrategy</a>" /> Defines the strategy used to merge a guest Order and an existing Order when signing in. ### checkoutMergeStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/order-merge-strategy#ordermergestrategy'>OrderMergeStrategy</a>`} default="<a href='/reference/typescript-api/orders/merge-strategies#usegueststrategy'>UseGuestStrategy</a>" /> Defines the strategy used to merge a guest Order and an existing Order when signing in as part of the checkout flow. ### orderCodeStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/order-code-strategy#ordercodestrategy'>OrderCodeStrategy</a>`} default="<a href='/reference/typescript-api/orders/order-code-strategy#defaultordercodestrategy'>DefaultOrderCodeStrategy</a>" /> Allows a user-defined function to create Order codes. This can be useful when integrating with existing systems. By default, Vendure will generate a 16-character alphanumeric string. Note: when using a custom function for Order codes, bear in mind the database limit for string types (e.g. 255 chars for a varchar field in MySQL), and also the need for codes to be unique. ### orderByCodeAccessStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/order-by-code-access-strategy#orderbycodeaccessstrategy'>OrderByCodeAccessStrategy</a>`} default="<a href='/reference/typescript-api/orders/order-by-code-access-strategy#defaultorderbycodeaccessstrategy'>DefaultOrderByCodeAccessStrategy</a>" since="1.1.0" /> Defines the strategy used to check if and how an Order may be retrieved via the orderByCode query. The default strategy permits permanent access to the Customer owning the Order and anyone within 2 hours after placing the Order. ### changedPriceHandlingStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/changed-price-handling-strategy#changedpricehandlingstrategy'>ChangedPriceHandlingStrategy</a>`} default="DefaultChangedPriceHandlingStrategy" /> Defines how we handle the situation where an item exists in an Order, and then later on another is added but in the meantime the price of the ProductVariant has changed. By default, the latest price will be used. Any price changes resulting from using a newer price will be reflected in the GraphQL `OrderLine.unitPrice[WithTax]ChangeSinceAdded` field. ### orderPlacedStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/order-placed-strategy#orderplacedstrategy'>OrderPlacedStrategy</a>`} default="<a href='/reference/typescript-api/orders/default-order-placed-strategy#defaultorderplacedstrategy'>DefaultOrderPlacedStrategy</a>" /> Defines the point of the order process at which the Order is set as "placed". ### activeOrderStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/active-order-strategy#activeorderstrategy'>ActiveOrderStrategy</a>&#60;any&#62; | Array&#60;<a href='/reference/typescript-api/orders/active-order-strategy#activeorderstrategy'>ActiveOrderStrategy</a>&#60;any&#62;&#62;`} default="<a href='/reference/typescript-api/orders/default-active-order-strategy#defaultactiveorderstrategy'>DefaultActiveOrderStrategy</a>" since="1.9.0" /> Defines the strategy used to determine the active Order when interacting with Shop API operations such as `activeOrder` and `addItemToOrder`. By default, the strategy uses the active Session. Note that if multiple strategies are defined, they will be checked in order and the first one that returns an Order will be used. ### orderSellerStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/order-seller-strategy#ordersellerstrategy'>OrderSellerStrategy</a>`} default="<a href='/reference/typescript-api/orders/order-seller-strategy#defaultordersellerstrategy'>DefaultOrderSellerStrategy</a>" since="2.0.0" /> Defines how Orders will be split amongst multiple Channels in a multivendor scenario. ### guestCheckoutStrategy <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/guest-checkout-strategy#guestcheckoutstrategy'>GuestCheckoutStrategy</a>`} default="<a href='/reference/typescript-api/orders/default-guest-checkout-strategy#defaultguestcheckoutstrategy'>DefaultGuestCheckoutStrategy</a>" since="2.0.0" /> Defines how we deal with guest checkouts. </div>
--- title: "OrderPlacedStrategy" 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'; ## OrderPlacedStrategy <GenerationInfo sourceFile="packages/core/src/config/order/order-placed-strategy.ts" sourceLine="24" packageName="@vendure/core" /> This strategy is responsible for deciding at which stage in the order process the Order will be set as "placed" (i.e. the Customer has checked out, and next it must be processed by an Administrator). By default, the order is set as "placed" when it transitions from 'ArrangingPayment' to either 'PaymentAuthorized' or 'PaymentSettled'. :::info This is configured via the `orderOptions.orderPlacedStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface OrderPlacedStrategy extends InjectableStrategy { shouldSetAsPlaced( ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order, ): boolean | Promise<boolean>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### shouldSetAsPlaced <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, fromState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, toState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => boolean | Promise&#60;boolean&#62;`} /> This method is called whenever an _active_ Order transitions from one state to another. If it resolves to `true`, then the Order will be set as "placed", which means: * Order.active = false * Order.placedAt = new Date() * Any active Promotions are linked to the Order </div>
--- title: "OrderProcess" 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'; ## OrderProcess <GenerationInfo sourceFile="packages/core/src/config/order/order-process.ts" sourceLine="35" packageName="@vendure/core" /> An OrderProcess is used to define the way the order process works as in: what states an Order can be in, and how it may transition from one state to another. Using the `onTransitionStart()` hook, an OrderProcess can perform checks before allowing a state transition to occur, and the `onTransitionEnd()` hook allows logic to be executed after a state change. For detailed description of the interface members, see the <a href='/reference/typescript-api/state-machine/state-machine-config#statemachineconfig'>StateMachineConfig</a> docs. :::info This is configured via the `orderOptions.process` property of your VendureConfig. ::: ```ts title="Signature" interface OrderProcess<State extends keyof CustomOrderStates | string> extends InjectableStrategy { transitions?: Transitions<State, State | OrderState> & Partial<Transitions<OrderState | State>>; onTransitionStart?: OnTransitionStartFn<State | OrderState, OrderTransitionData>; onTransitionEnd?: OnTransitionEndFn<State | OrderState, OrderTransitionData>; onTransitionError?: OnTransitionErrorFn<State | OrderState>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### transitions <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/transitions#transitions'>Transitions</a>&#60;State, State | <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>&#62; &#38; Partial&#60;<a href='/reference/typescript-api/state-machine/transitions#transitions'>Transitions</a>&#60;<a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a> | State&#62;&#62;`} /> ### onTransitionStart <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/state-machine-config#ontransitionstartfn'>OnTransitionStartFn</a>&#60;State | <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, <a href='/reference/typescript-api/orders/order-process#ordertransitiondata'>OrderTransitionData</a>&#62;`} /> ### onTransitionEnd <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/state-machine-config#ontransitionendfn'>OnTransitionEndFn</a>&#60;State | <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, <a href='/reference/typescript-api/orders/order-process#ordertransitiondata'>OrderTransitionData</a>&#62;`} /> ### onTransitionError <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/state-machine-config#ontransitionerrorfn'>OnTransitionErrorFn</a>&#60;State | <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>&#62;`} /> </div> ## DefaultOrderProcessOptions <GenerationInfo sourceFile="packages/core/src/config/order/default-order-process.ts" sourceLine="50" packageName="@vendure/core" since="2.0.0" /> Options which can be passed to the <a href='/reference/typescript-api/orders/order-process#configuredefaultorderprocess'>configureDefaultOrderProcess</a> function to configure an instance of the default <a href='/reference/typescript-api/orders/order-process#orderprocess'>OrderProcess</a>. By default, all options are set to `true`. ```ts title="Signature" interface DefaultOrderProcessOptions { checkModificationPayments?: boolean; checkAdditionalPaymentsAmount?: boolean; checkAllVariantsExist?: boolean; arrangingPaymentRequiresContents?: boolean; arrangingPaymentRequiresCustomer?: boolean; arrangingPaymentRequiresShipping?: boolean; arrangingPaymentRequiresStock?: boolean; checkPaymentsCoverTotal?: boolean; checkAllItemsBeforeCancel?: boolean; checkFulfillmentStates?: boolean; } ``` <div className="members-wrapper"> ### checkModificationPayments <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents an Order from transitioning out of the `Modifying` state if the Order price has changed and there is no Payment or Refund associated with the Modification. ### checkAdditionalPaymentsAmount <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents an Order from transitioning out of the `ArrangingAdditionalPayment` state if the Order's Payments do not cover the full amount of `totalWithTax`. ### checkAllVariantsExist <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents the transition from `AddingItems` to any other state (apart from `Cancelled`) if and of the ProductVariants no longer exists due to deletion. ### arrangingPaymentRequiresContents <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents transition to the `ArrangingPayment` state if the active Order has no lines. ### arrangingPaymentRequiresCustomer <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents transition to the `ArrangingPayment` state if the active Order has no customer associated with it. ### arrangingPaymentRequiresShipping <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents transition to the `ArrangingPayment` state if the active Order has no shipping method set. ### arrangingPaymentRequiresStock <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents transition to the `ArrangingPayment` state if there is insufficient saleable stock to cover the contents of the Order. ### checkPaymentsCoverTotal <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents transition to the `PaymentAuthorized` or `PaymentSettled` states if the order `totalWithTax` amount is not covered by Payment(s) in the corresponding states. ### checkAllItemsBeforeCancel <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents transition to the `Cancelled` state unless all OrderItems are already cancelled. ### checkFulfillmentStates <MemberInfo kind="property" type={`boolean`} default="true" /> Prevents transition to the `Shipped`, `PartiallyShipped`, `Delivered` & `PartiallyDelivered` states unless there are corresponding Fulfillments in the correct states to allow this. E.g. `Shipped` only if all items in the Order are part of a Fulfillment which itself is in the `Shipped` state. </div> ## configureDefaultOrderProcess <GenerationInfo sourceFile="packages/core/src/config/order/default-order-process.ts" sourceLine="163" packageName="@vendure/core" since="2.0.0" /> Used to configure a customized instance of the default <a href='/reference/typescript-api/orders/order-process#orderprocess'>OrderProcess</a> that ships with Vendure. Using this function allows you to turn off certain checks and constraints that are enabled by default. ```ts import { configureDefaultOrderProcess, VendureConfig } from '@vendure/core'; const myCustomOrderProcess = configureDefaultOrderProcess({ // Disable the constraint that requires // Orders to have a shipping method assigned // before payment. arrangingPaymentRequiresShipping: false, }); export const config: VendureConfig = { orderOptions: { process: [myCustomOrderProcess], }, }; ``` The <a href='/reference/typescript-api/orders/order-process#defaultorderprocessoptions'>DefaultOrderProcessOptions</a> type defines all available options. If you require even more customization, you can create your own implementation of the <a href='/reference/typescript-api/orders/order-process#orderprocess'>OrderProcess</a> interface. ```ts title="Signature" function configureDefaultOrderProcess(options: DefaultOrderProcessOptions): void ``` Parameters ### options <MemberInfo kind="parameter" type={`<a href='/reference/typescript-api/orders/order-process#defaultorderprocessoptions'>DefaultOrderProcessOptions</a>`} /> ## defaultOrderProcess <GenerationInfo sourceFile="packages/core/src/config/order/default-order-process.ts" sourceLine="475" packageName="@vendure/core" since="2.0.0" /> This is the built-in <a href='/reference/typescript-api/orders/order-process#orderprocess'>OrderProcess</a> that ships with Vendure. A customized version of this process can be created using the <a href='/reference/typescript-api/orders/order-process#configuredefaultorderprocess'>configureDefaultOrderProcess</a> function, which allows you to pass in an object to enable/disable certain checks. ## OrderStates <GenerationInfo sourceFile="packages/core/src/service/helpers/order-state-machine/order-state.ts" sourceLine="21" packageName="@vendure/core" since="2.0.0" /> An interface to extend the <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a> type. ```ts title="Signature" interface OrderStates { } ``` ## OrderState <GenerationInfo sourceFile="packages/core/src/service/helpers/order-state-machine/order-state.ts" sourceLine="42" packageName="@vendure/core" /> These are the default states of the Order process. They can be augmented and modified by using the <a href='/reference/typescript-api/orders/order-options#orderoptions'>OrderOptions</a> `process` property, and by default the <a href='/reference/typescript-api/orders/order-process#defaultorderprocess'>defaultOrderProcess</a> will add the states - `ArrangingPayment` - `PaymentAuthorized` - `PaymentSettled` - `PartiallyShipped` - `Shipped` - `PartiallyDelivered` - `Delivered` - `Modifying` - `ArrangingAdditionalPayment` ```ts title="Signature" type OrderState = | 'Created' | 'Draft' | 'AddingItems' | 'Cancelled' | keyof CustomOrderStates | keyof OrderStates ``` ## OrderTransitionData <GenerationInfo sourceFile="packages/core/src/service/helpers/order-state-machine/order-state.ts" sourceLine="57" packageName="@vendure/core" /> This is the object passed to the <a href='/reference/typescript-api/orders/order-process#orderprocess'>OrderProcess</a> state transition hooks. ```ts title="Signature" interface OrderTransitionData { ctx: RequestContext; order: Order; } ``` <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>`} /> </div>
--- title: "OrderSellerStrategy" 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'; ## OrderSellerStrategy <GenerationInfo sourceFile="packages/core/src/config/order/order-seller-strategy.ts" sourceLine="43" packageName="@vendure/core" since="2.0.0" /> This strategy defines how an Order can be split into multiple sub-orders for the use-case of a multivendor application. :::info This is configured via the `orderOptions.orderSellerStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface OrderSellerStrategy extends InjectableStrategy { setOrderLineSellerChannel?( ctx: RequestContext, orderLine: OrderLine, ): Channel | undefined | Promise<Channel | undefined>; splitOrder?(ctx: RequestContext, order: Order): SplitOrderContents[] | Promise<SplitOrderContents[]>; afterSellerOrdersCreated?( ctx: RequestContext, aggregateOrder: Order, sellerOrders: Order[], ): void | Promise<void>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### setOrderLineSellerChannel <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, orderLine: <a href='/reference/typescript-api/entities/order-line#orderline'>OrderLine</a>) => <a href='/reference/typescript-api/entities/channel#channel'>Channel</a> | undefined | Promise&#60;<a href='/reference/typescript-api/entities/channel#channel'>Channel</a> | undefined&#62;`} /> This method is called whenever a new OrderLine is added to the Order via the `addItemToOrder` mutation or the underlying `addItemToOrder()` method of the <a href='/reference/typescript-api/services/order-service#orderservice'>OrderService</a>. It should return the ID of the Channel to which this OrderLine will be assigned, which will be used to set the <a href='/reference/typescript-api/entities/order-line#orderline'>OrderLine</a> `sellerChannel` property. ### splitOrder <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => <a href='/reference/typescript-api/orders/order-seller-strategy#splitordercontents'>SplitOrderContents</a>[] | Promise&#60;<a href='/reference/typescript-api/orders/order-seller-strategy#splitordercontents'>SplitOrderContents</a>[]&#62;`} /> Upon checkout (by default, when the Order moves from "active" to "inactive" according to the <a href='/reference/typescript-api/orders/order-placed-strategy#orderplacedstrategy'>OrderPlacedStrategy</a>), this method will be called in order to split the Order into multiple Orders, one for each Seller. ### afterSellerOrdersCreated <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, aggregateOrder: <a href='/reference/typescript-api/entities/order#order'>Order</a>, sellerOrders: <a href='/reference/typescript-api/entities/order#order'>Order</a>[]) => void | Promise&#60;void&#62;`} /> This method is called after splitting the orders, including calculating the totals for each of the seller Orders. This method can be used to set platform fee surcharges on the seller Orders as well as perform any payment processing needed. </div> ## DefaultOrderSellerStrategy <GenerationInfo sourceFile="packages/core/src/config/order/default-order-seller-strategy.ts" sourceLine="11" packageName="@vendure/core" since="2.0.0" /> The DefaultOrderSellerStrategy treats the Order as single-vendor. ```ts title="Signature" class DefaultOrderSellerStrategy implements OrderSellerStrategy { } ``` * Implements: <code><a href='/reference/typescript-api/orders/order-seller-strategy#ordersellerstrategy'>OrderSellerStrategy</a></code> ## SplitOrderContents <GenerationInfo sourceFile="packages/core/src/config/order/order-seller-strategy.ts" sourceLine="19" packageName="@vendure/core" since="2.0.0" /> The contents of the aggregate Order which make up a single seller Order. ```ts title="Signature" interface SplitOrderContents { channelId: ID; state: OrderState; lines: OrderLine[]; shippingLines: ShippingLine[]; } ``` <div className="members-wrapper"> ### channelId <MemberInfo kind="property" type={`<a href='/reference/typescript-api/common/id#id'>ID</a>`} /> ### state <MemberInfo kind="property" type={`<a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>`} /> ### lines <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/order-line#orderline'>OrderLine</a>[]`} /> ### shippingLines <MemberInfo kind="property" type={`<a href='/reference/typescript-api/entities/shipping-line#shippingline'>ShippingLine</a>[]`} /> </div>
--- title: "StockAllocationStrategy" 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'; ## StockAllocationStrategy <GenerationInfo sourceFile="packages/core/src/config/order/stock-allocation-strategy.ts" sourceLine="20" packageName="@vendure/core" /> This strategy is responsible for deciding at which stage in the order process stock will be allocated. :::info This is configured via the `orderOptions.stockAllocationStrategy` property of your VendureConfig. ::: ```ts title="Signature" interface StockAllocationStrategy extends InjectableStrategy { shouldAllocateStock( ctx: RequestContext, fromState: OrderState, toState: OrderState, order: Order, ): boolean | Promise<boolean>; } ``` * Extends: <code><a href='/reference/typescript-api/common/injectable-strategy#injectablestrategy'>InjectableStrategy</a></code> <div className="members-wrapper"> ### shouldAllocateStock <MemberInfo kind="method" type={`(ctx: <a href='/reference/typescript-api/request/request-context#requestcontext'>RequestContext</a>, fromState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, toState: <a href='/reference/typescript-api/orders/order-process#orderstate'>OrderState</a>, order: <a href='/reference/typescript-api/entities/order#order'>Order</a>) => boolean | Promise&#60;boolean&#62;`} /> This method is called whenever an Order transitions from one state to another. If it resolves to `true`, then stock will be allocated for this order. </div>
--- title: "Payment" weight: 10 date: 2023-07-14T16:57:49.648Z showtoc: false generated: true --- <!-- This file was generated from the Vendure source. Do not modify. Instead, re-run the "docs:build" script --> # payment
--- title: "DefaultPaymentProcess" 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'; ## defaultPaymentProcess <GenerationInfo sourceFile="packages/core/src/config/payment/default-payment-process.ts" sourceLine="26" packageName="@vendure/core" /> The default <a href='/reference/typescript-api/payment/payment-process#paymentprocess'>PaymentProcess</a>
--- title: "DummyPaymentHandler" 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'; ## dummyPaymentHandler <GenerationInfo sourceFile="packages/core/src/config/payment/dummy-payment-method-handler.ts" sourceLine="27" packageName="@vendure/core" /> A dummy PaymentMethodHandler which simply creates a Payment without any integration with an external payment provider. Intended only for use in development. By specifying certain metadata keys, failures can be simulated: *Example* ```GraphQL addPaymentToOrder(input: { method: 'dummy-payment-method', metadata: { shouldDecline: false, shouldError: false, shouldErrorOnSettle: true, } }) { # ... } ```
--- title: "Payment" 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: "PaymentMethodConfigOptions" 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'; ## PaymentMethodConfigOptions <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="255" packageName="@vendure/core" /> Defines the object which is used to construct the <a href='/reference/typescript-api/payment/payment-method-handler#paymentmethodhandler'>PaymentMethodHandler</a>. ```ts title="Signature" interface PaymentMethodConfigOptions<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { createPayment: CreatePaymentFn<T>; settlePayment: SettlePaymentFn<T>; cancelPayment?: CancelPaymentFn<T>; createRefund?: CreateRefundFn<T>; onStateTransitionStart?: OnTransitionStartFn<PaymentState, PaymentTransitionData>; } ``` * Extends: <code><a href='/reference/typescript-api/configurable-operation-def/configurable-operation-def-options#configurableoperationdefoptions'>ConfigurableOperationDefOptions</a>&#60;T&#62;</code> <div className="members-wrapper"> ### createPayment <MemberInfo kind="property" type={`<a href='/reference/typescript-api/payment/payment-method-types#createpaymentfn'>CreatePaymentFn</a>&#60;T&#62;`} /> This function provides the logic for creating a payment. For example, it may call out to a third-party service with the data and should return a <a href='/reference/typescript-api/payment/payment-method-types#createpaymentresult'>CreatePaymentResult</a> object contains the details of the payment. ### settlePayment <MemberInfo kind="property" type={`<a href='/reference/typescript-api/payment/payment-method-types#settlepaymentfn'>SettlePaymentFn</a>&#60;T&#62;`} /> This function provides the logic for settling a payment, also known as "capturing". For payment integrations that settle/capture the payment on creation (i.e. the `createPayment()` method returns with a state of `'Settled'`) this method need only return `{ success: true }`. ### cancelPayment <MemberInfo kind="property" type={`<a href='/reference/typescript-api/payment/payment-method-types#cancelpaymentfn'>CancelPaymentFn</a>&#60;T&#62;`} since="1.7.0" /> This function provides the logic for cancelling a payment, which would be invoked when a call is made to the `cancelPayment` mutation in the Admin API. Cancelling a payment can apply if, for example, you have created a "payment intent" with the payment provider but not yet completed the payment. It allows the incomplete payment to be cleaned up on the provider's end if it gets cancelled via Vendure. ### createRefund <MemberInfo kind="property" type={`<a href='/reference/typescript-api/payment/payment-method-types#createrefundfn'>CreateRefundFn</a>&#60;T&#62;`} /> This function provides the logic for refunding a payment created with this payment method. Some payment providers may not provide the facility to programmatically create a refund. In such a case, this method should be omitted and any Refunds will have to be settled manually by an administrator. ### onStateTransitionStart <MemberInfo kind="property" type={`<a href='/reference/typescript-api/state-machine/state-machine-config#ontransitionstartfn'>OnTransitionStartFn</a>&#60;<a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a>, <a href='/reference/typescript-api/payment/payment-transition-data#paymenttransitiondata'>PaymentTransitionData</a>&#62;`} /> This function, when specified, will be invoked before any transition from one <a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a> to another. The return value (a sync / async `boolean`) is used to determine whether the transition is permitted. </div>
--- title: "PaymentMethodEligibilityChecker" 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'; ## PaymentMethodEligibilityChecker <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-eligibility-checker.ts" sourceLine="47" packageName="@vendure/core" /> The PaymentMethodEligibilityChecker class is used to check whether an order qualifies for a given <a href='/reference/typescript-api/entities/payment-method#paymentmethod'>PaymentMethod</a>. *Example* ```ts const ccPaymentEligibilityChecker = new PaymentMethodEligibilityChecker({ code: 'order-total-payment-eligibility-checker', description: [{ languageCode: LanguageCode.en, value: 'Checks that the order total is above some minimum value' }], args: { orderMinimum: { type: 'int', ui: { component: 'currency-form-input' } }, }, check: (ctx, order, args) => { return order.totalWithTax >= args.orderMinimum; }, }); ``` ```ts title="Signature" class PaymentMethodEligibilityChecker<T extends ConfigArgs = ConfigArgs> extends ConfigurableOperationDef<T> { constructor(config: PaymentMethodEligibilityCheckerConfig<T>) } ``` * Extends: <code><a href='/reference/typescript-api/configurable-operation-def/#configurableoperationdef'>ConfigurableOperationDef</a>&#60;T&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(config: <a href='/reference/typescript-api/payment/payment-method-eligibility-checker#paymentmethodeligibilitycheckerconfig'>PaymentMethodEligibilityCheckerConfig</a>&#60;T&#62;) => PaymentMethodEligibilityChecker`} /> </div> ## PaymentMethodEligibilityCheckerConfig <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-eligibility-checker.ts" sourceLine="20" packageName="@vendure/core" /> Configuration passed into the constructor of a <a href='/reference/typescript-api/payment/payment-method-eligibility-checker#paymentmethodeligibilitychecker'>PaymentMethodEligibilityChecker</a> to configure its behavior. ```ts title="Signature" interface PaymentMethodEligibilityCheckerConfig<T extends ConfigArgs> extends ConfigurableOperationDefOptions<T> { check: CheckPaymentMethodEligibilityCheckerFn<T>; } ``` * Extends: <code><a href='/reference/typescript-api/configurable-operation-def/configurable-operation-def-options#configurableoperationdefoptions'>ConfigurableOperationDefOptions</a>&#60;T&#62;</code> <div className="members-wrapper"> ### check <MemberInfo kind="property" type={`<a href='/reference/typescript-api/payment/payment-method-eligibility-checker#checkpaymentmethodeligibilitycheckerfn'>CheckPaymentMethodEligibilityCheckerFn</a>&#60;T&#62;`} /> </div> ## CheckPaymentMethodEligibilityCheckerFn <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-eligibility-checker.ts" sourceLine="83" packageName="@vendure/core" /> A function which implements logic to determine whether a given <a href='/reference/typescript-api/entities/order#order'>Order</a> is eligible for a particular payment method. If the function resolves to `false` or a string, the check is considered to have failed. A string result can be used to provide information about the reason for ineligibility, if desired. ```ts title="Signature" type CheckPaymentMethodEligibilityCheckerFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, args: ConfigArgValues<T>, method: PaymentMethod, ) => boolean | string | Promise<boolean | string> ```
--- title: "PaymentMethodHandler" 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'; ## PaymentMethodHandler <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="354" packageName="@vendure/core" /> A PaymentMethodHandler contains the code which is used to generate a Payment when a call to the `addPaymentToOrder` mutation is made. It contains any necessary steps of interfacing with a third-party payment gateway before the Payment is created and can also define actions to fire when the state of the payment is changed. PaymentMethodHandlers are instantiated using a <a href='/reference/typescript-api/payment/payment-method-config-options#paymentmethodconfigoptions'>PaymentMethodConfigOptions</a> object, which configures the business logic used to create, settle and refund payments. *Example* ```ts import { PaymentMethodHandler, CreatePaymentResult, SettlePaymentResult, LanguageCode } from '@vendure/core'; // A mock 3rd-party payment SDK import gripeSDK from 'gripe'; export const examplePaymentHandler = new PaymentMethodHandler({ code: 'example-payment-provider', description: [{ languageCode: LanguageCode.en, value: 'Example Payment Provider', }], args: { apiKey: { type: 'string' }, }, createPayment: async (ctx, order, amount, args, metadata): Promise<CreatePaymentResult> => { try { const result = await gripeSDK.charges.create({ amount, apiKey: args.apiKey, source: metadata.authToken, }); return { amount: order.total, state: 'Settled' as const, transactionId: result.id.toString(), metadata: result.outcome, }; } catch (err: any) { return { amount: order.total, state: 'Declined' as const, metadata: { errorMessage: err.message, }, }; } }, settlePayment: async (ctx, order, payment, args): Promise<SettlePaymentResult> => { return { success: true }; } }); ``` ```ts title="Signature" class PaymentMethodHandler<T extends ConfigArgs = ConfigArgs> extends ConfigurableOperationDef<T> { constructor(config: PaymentMethodConfigOptions<T>) } ``` * Extends: <code><a href='/reference/typescript-api/configurable-operation-def/#configurableoperationdef'>ConfigurableOperationDef</a>&#60;T&#62;</code> <div className="members-wrapper"> ### constructor <MemberInfo kind="method" type={`(config: <a href='/reference/typescript-api/payment/payment-method-config-options#paymentmethodconfigoptions'>PaymentMethodConfigOptions</a>&#60;T&#62;) => PaymentMethodHandler`} /> </div>
--- title: "Payment Method Types" 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'; ## CreatePaymentResult <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="30" packageName="@vendure/core" /> This object is the return value of the <a href='/reference/typescript-api/payment/payment-method-types#createpaymentfn'>CreatePaymentFn</a>. ```ts title="Signature" interface CreatePaymentResult { amount: number; state: Exclude<PaymentState, 'Error'>; transactionId?: string; errorMessage?: string; metadata?: PaymentMetadata; } ``` <div className="members-wrapper"> ### amount <MemberInfo kind="property" type={`number`} /> The amount (as an integer - i.e. $10 = `1000`) that this payment is for. Typically this should equal the Order total, unless multiple payment methods are being used for the order. ### state <MemberInfo kind="property" type={`Exclude&#60;<a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a>, 'Error'&#62;`} /> The <a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a> of the resulting Payment. In a single-step payment flow, this should be set to `'Settled'`. In a two-step flow, this should be set to `'Authorized'`. If using a {@link CustomPaymentProcess}, may be something else entirely according to your business logic. ### transactionId <MemberInfo kind="property" type={`string`} /> The unique payment reference code typically assigned by the payment provider. ### errorMessage <MemberInfo kind="property" type={`string`} /> If the payment is declined or fails for ome other reason, pass the relevant error message here, and it gets returned with the ErrorResponse of the `addPaymentToOrder` mutation. ### metadata <MemberInfo kind="property" type={`PaymentMetadata`} /> This field can be used to store other relevant data which is often provided by the payment provider, such as security data related to the payment method or data used in troubleshooting or debugging. Any data stored in the optional `public` property will be available via the Shop API. This is useful for certain checkout flows such as external gateways, where the payment provider returns a unique url which must then be passed to the storefront app. </div> ## CreatePaymentErrorResult <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="83" packageName="@vendure/core" /> This object is the return value of the <a href='/reference/typescript-api/payment/payment-method-types#createpaymentfn'>CreatePaymentFn</a> when there has been an error. ```ts title="Signature" interface CreatePaymentErrorResult { amount: number; state: 'Error'; transactionId?: string; errorMessage: string; metadata?: PaymentMetadata; } ``` <div className="members-wrapper"> ### amount <MemberInfo kind="property" type={`number`} /> ### state <MemberInfo kind="property" type={`'Error'`} /> ### transactionId <MemberInfo kind="property" type={`string`} /> ### errorMessage <MemberInfo kind="property" type={`string`} /> ### metadata <MemberInfo kind="property" type={`PaymentMetadata`} /> </div> ## CreateRefundResult <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="98" packageName="@vendure/core" /> This object is the return value of the <a href='/reference/typescript-api/payment/payment-method-types#createrefundfn'>CreateRefundFn</a>. ```ts title="Signature" interface CreateRefundResult { state: RefundState; transactionId?: string; metadata?: PaymentMetadata; } ``` <div className="members-wrapper"> ### state <MemberInfo kind="property" type={`<a href='/reference/typescript-api/payment/refund-state#refundstate'>RefundState</a>`} /> ### transactionId <MemberInfo kind="property" type={`string`} /> ### metadata <MemberInfo kind="property" type={`PaymentMetadata`} /> </div> ## SettlePaymentResult <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="112" packageName="@vendure/core" /> This object is the return value of the <a href='/reference/typescript-api/payment/payment-method-types#settlepaymentfn'>SettlePaymentFn</a> when the Payment has been successfully settled. ```ts title="Signature" interface SettlePaymentResult { success: true; metadata?: PaymentMetadata; } ``` <div className="members-wrapper"> ### success <MemberInfo kind="property" type={`true`} /> ### metadata <MemberInfo kind="property" type={`PaymentMetadata`} /> </div> ## SettlePaymentErrorResult <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="125" packageName="@vendure/core" /> This object is the return value of the <a href='/reference/typescript-api/payment/payment-method-types#settlepaymentfn'>SettlePaymentFn</a> when the Payment could not be settled. ```ts title="Signature" interface SettlePaymentErrorResult { success: false; state?: Exclude<PaymentState, 'Settled'>; errorMessage?: string; metadata?: PaymentMetadata; } ``` <div className="members-wrapper"> ### success <MemberInfo kind="property" type={`false`} /> ### state <MemberInfo kind="property" type={`Exclude&#60;<a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a>, 'Settled'&#62;`} /> The state to transition this Payment to upon unsuccessful settlement. Defaults to `Error`. Note that if using a different state, it must be legal to transition to that state from the `Authorized` state according to the PaymentState config (which can be customized using the {@link CustomPaymentProcess}). ### errorMessage <MemberInfo kind="property" type={`string`} /> The message that will be returned when attempting to settle the payment, and will also be persisted as `Payment.errorMessage`. ### metadata <MemberInfo kind="property" type={`PaymentMetadata`} /> </div> ## CancelPaymentResult <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="153" packageName="@vendure/core" /> This object is the return value of the <a href='/reference/typescript-api/payment/payment-method-types#cancelpaymentfn'>CancelPaymentFn</a> when the Payment has been successfully cancelled. ```ts title="Signature" interface CancelPaymentResult { success: true; metadata?: PaymentMetadata; } ``` <div className="members-wrapper"> ### success <MemberInfo kind="property" type={`true`} /> ### metadata <MemberInfo kind="property" type={`PaymentMetadata`} /> </div> ## CancelPaymentErrorResult <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="165" packageName="@vendure/core" /> This object is the return value of the <a href='/reference/typescript-api/payment/payment-method-types#cancelpaymentfn'>CancelPaymentFn</a> when the Payment could not be cancelled. ```ts title="Signature" interface CancelPaymentErrorResult { success: false; state?: Exclude<PaymentState, 'Cancelled'>; errorMessage?: string; metadata?: PaymentMetadata; } ``` <div className="members-wrapper"> ### success <MemberInfo kind="property" type={`false`} /> ### state <MemberInfo kind="property" type={`Exclude&#60;<a href='/reference/typescript-api/payment/payment-state#paymentstate'>PaymentState</a>, 'Cancelled'&#62;`} /> The state to transition this Payment to upon unsuccessful cancellation. Defaults to `Error`. Note that if using a different state, it must be legal to transition to that state from the `Authorized` state according to the PaymentState config (which can be customized using the {@link CustomPaymentProcess}). ### errorMessage <MemberInfo kind="property" type={`string`} /> The message that will be returned when attempting to cancel the payment, and will also be persisted as `Payment.errorMessage`. ### metadata <MemberInfo kind="property" type={`PaymentMetadata`} /> </div> ## CreatePaymentFn <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="193" packageName="@vendure/core" /> This function contains the logic for creating a payment. See <a href='/reference/typescript-api/payment/payment-method-handler#paymentmethodhandler'>PaymentMethodHandler</a> for an example. Returns a <a href='/reference/typescript-api/payment/payment-method-types#createpaymentresult'>CreatePaymentResult</a>. ```ts title="Signature" type CreatePaymentFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, amount: number, args: ConfigArgValues<T>, metadata: PaymentMetadata, method: PaymentMethod, ) => CreatePaymentResult | CreatePaymentErrorResult | Promise<CreatePaymentResult | CreatePaymentErrorResult> ``` ## SettlePaymentFn <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="209" packageName="@vendure/core" /> This function contains the logic for settling a payment. See <a href='/reference/typescript-api/payment/payment-method-handler#paymentmethodhandler'>PaymentMethodHandler</a> for an example. ```ts title="Signature" type SettlePaymentFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, payment: Payment, args: ConfigArgValues<T>, method: PaymentMethod, ) => SettlePaymentResult | SettlePaymentErrorResult | Promise<SettlePaymentResult | SettlePaymentErrorResult> ``` ## CancelPaymentFn <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="224" packageName="@vendure/core" /> This function contains the logic for cancelling a payment. See <a href='/reference/typescript-api/payment/payment-method-handler#paymentmethodhandler'>PaymentMethodHandler</a> for an example. ```ts title="Signature" type CancelPaymentFn<T extends ConfigArgs> = ( ctx: RequestContext, order: Order, payment: Payment, args: ConfigArgValues<T>, method: PaymentMethod, ) => CancelPaymentResult | CancelPaymentErrorResult | Promise<CancelPaymentResult | CancelPaymentErrorResult> ``` ## CreateRefundFn <GenerationInfo sourceFile="packages/core/src/config/payment/payment-method-handler.ts" sourceLine="239" packageName="@vendure/core" /> This function contains the logic for creating a refund. See <a href='/reference/typescript-api/payment/payment-method-handler#paymentmethodhandler'>PaymentMethodHandler</a> for an example. ```ts title="Signature" type CreateRefundFn<T extends ConfigArgs> = ( ctx: RequestContext, input: RefundOrderInput, amount: number, order: Order, payment: Payment, args: ConfigArgValues<T>, method: PaymentMethod, ) => CreateRefundResult | Promise<CreateRefundResult> ```
--- title: "PaymentOptions" 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'; ## PaymentOptions <GenerationInfo sourceFile="packages/core/src/config/vendure-config.ts" sourceLine="825" packageName="@vendure/core" /> Defines payment-related options in the <a href='/reference/typescript-api/configuration/vendure-config#vendureconfig'>VendureConfig</a>. ```ts title="Signature" interface PaymentOptions { paymentMethodHandlers: PaymentMethodHandler[]; paymentMethodEligibilityCheckers?: PaymentMethodEligibilityChecker[]; customPaymentProcess?: Array<PaymentProcess<any>>; process?: Array<PaymentProcess<any>>; } ``` <div className="members-wrapper"> ### paymentMethodHandlers <MemberInfo kind="property" type={`<a href='/reference/typescript-api/payment/payment-method-handler#paymentmethodhandler'>PaymentMethodHandler</a>[]`} /> Defines which <a href='/reference/typescript-api/payment/payment-method-handler#paymentmethodhandler'>PaymentMethodHandler</a>s are available when configuring <a href='/reference/typescript-api/entities/payment-method#paymentmethod'>PaymentMethod</a>s ### paymentMethodEligibilityCheckers <MemberInfo kind="property" type={`<a href='/reference/typescript-api/payment/payment-method-eligibility-checker#paymentmethodeligibilitychecker'>PaymentMethodEligibilityChecker</a>[]`} /> Defines which <a href='/reference/typescript-api/payment/payment-method-eligibility-checker#paymentmethodeligibilitychecker'>PaymentMethodEligibilityChecker</a>s are available when configuring <a href='/reference/typescript-api/entities/payment-method#paymentmethod'>PaymentMethod</a>s ### customPaymentProcess <MemberInfo kind="property" type={`Array&#60;<a href='/reference/typescript-api/payment/payment-process#paymentprocess'>PaymentProcess</a>&#60;any&#62;&#62;`} /> ### process <MemberInfo kind="property" type={`Array&#60;<a href='/reference/typescript-api/payment/payment-process#paymentprocess'>PaymentProcess</a>&#60;any&#62;&#62;`} default="<a href='/reference/typescript-api/payment/default-payment-process#defaultpaymentprocess'>defaultPaymentProcess</a>" since="2.0.0" /> Allows the definition of custom states and transition logic for the payment process state machine. Takes an array of objects implementing the <a href='/reference/typescript-api/payment/payment-process#paymentprocess'>PaymentProcess</a> interface. </div>