### Quick Start Option Prompt in @vendure/create Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/getting-started/installation/index.mdx Displays the initial prompt in the @vendure/create tool where the user selects the 'Quick Start' option. This option is highlighted as the fastest way to get a Vendure server running, handling all configuration automatically. ```console ┌ Let's create a Vendure App ✨ │ ◆ How should we proceed? │ ● Quick Start (Get up and running in a single step) # [!code highlight] │ ○ Manual Configuration └ ``` -------------------------------- ### Bootstrap with onBeforeAppListen for Swagger Setup Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/common/bootstrap.mdx Utilize the `onBeforeAppListen` option to perform actions just before the application starts listening for connections. This example demonstrates setting up Swagger API documentation. ```typescript import { bootstrap } from '@vendure/core'; import { config } from './vendure-config'; import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; bootstrap(config, { onBeforeAppListen: async (app) => { const config = new DocumentBuilder() .setTitle('Cats example') .setDescription('The cats API description') .setVersion('1.0') .addTag('cats') .build(); const documentFactory = () => SwaggerModule.createDocument(app, config); SwaggerModule.setup('api', app, documentFactory); } }); ``` -------------------------------- ### Start Vendure development server Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/getting-started/installation/index.mdx Commands to navigate to the project directory and launch the Vendure server and storefront in development mode. ```bash cd my-shop npm run dev ``` -------------------------------- ### Start Server with Preloaded SDK Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/telemetry-plugin/index.mdx Start the Vendure server using Node.js with the `--require` flag to load the instrumentation script. Examples are provided for both production builds and development with ts-node. ```bash node --require ./dist/instrumentation.js ./dist/server.js ``` ```bash npx ts-node --require ./src/instrumentation.ts ./src/server.ts ``` -------------------------------- ### Start Dashboard Development Server Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/extending-the-dashboard/getting-started/index.mdx Commands to initiate the Vendure server and the Vite development server for the dashboard interface. ```bash npm run dev npx vite ``` -------------------------------- ### Example Payment Method Handler Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/payment/payment-method-handler.mdx This example demonstrates how to create a custom PaymentMethodHandler for a third-party payment provider. It includes logic for creating payments, handling potential errors, and settling payments. Ensure you have the necessary SDK (e.g., `gripeSDK`) installed and configured. ```typescript 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 => { 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 => { return { success: true }; } }); ``` -------------------------------- ### Next.js Storefront Inclusion Prompt in @vendure/create Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/getting-started/installation/index.mdx Shows the prompt within the @vendure/create tool asking whether to include the official Next.js storefront starter. This is an optional step that provides a pre-built storefront connected to the Vendure server, recommended for quickly visualizing a working setup. ```console ┌ Let's create a Vendure App ✨ │ ◇ How should we proceed? │ Quick Start │ ◇ Using port 3000 │ ◇ Docker is running │ ◆ Would you like to include the Next.js storefront? # [!code highlight] │ ○ No # [!code highlight] │ ● Yes # [!code highlight] └ # [!code highlight] ``` -------------------------------- ### Start Docusaurus Server for Docs Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Starts the Docusaurus development server to preview documentation changes. Navigate to the docs directory first. ```bash cd docs bun run start ``` -------------------------------- ### Troubleshoot installation with verbose logging Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/getting-started/installation/index.mdx Run the Vendure creation command with a verbose log level to debug potential installation failures. ```bash npx @vendure/create my-shop --log-level verbose ``` -------------------------------- ### Service Implementation Example Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/data-access/list-query-builder.mdx Example of a Vendure service that utilizes the ListQueryBuilder to fetch and return a paginated list of blog posts. ```typescript @Injectable() export class BlogPostService { constructor(private listQueryBuilder: ListQueryBuilder) {} findAll(ctx: RequestContext, options?: ListQueryOptions) { return this.listQueryBuilder .build(BlogPost, options) .getManyAndCount() .then(async ([items, totalItems]) => { return { items, totalItems }; }); } } ``` -------------------------------- ### Install ioredis Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/cache/redis-cache-plugin.mdx To use the RedisCachePlugin, you must first install the `ioredis` package. ```shell npm install ioredis@^5.3.2 ``` -------------------------------- ### Install Vendure GraphiQL Plugin Source: https://github.com/vendurehq/vendure/blob/master/packages/graphiql-plugin/README.md Install the plugin using npm or yarn. ```bash npm install @vendure/graphiql-plugin ``` ```bash yarn add @vendure/graphiql-plugin ``` -------------------------------- ### PromotionItemAction Example Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/promotions/promotion-action.mdx Example of creating a PromotionItemAction to apply a percentage discount to individual order lines. This action modifies the price of each item based on the provided discount argument. ```typescript // Applies a percentage discount to each OrderLine const itemPercentageDiscount = new PromotionItemAction({ code: 'item_percentage_discount', args: { discount: 'percentage' }, execute(ctx, orderLine, args) { return -orderLine.unitPrice * (args.discount / 100); }, description: 'Discount every item by { discount }%', }); ``` -------------------------------- ### Install TelemetryPlugin Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/telemetry-plugin/index.mdx Install the TelemetryPlugin using npm. ```bash npm install @vendure/telemetry-plugin ``` -------------------------------- ### Start Database with Docker Compose Source: https://github.com/vendurehq/vendure/blob/master/packages/dev-server/README.md Ensure a database is running by using Docker Compose. This command starts a MariaDB instance. ```bash docker-compose up -d mariadb ``` -------------------------------- ### Installing HardenPlugin Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/deployment/production-configuration/index.mdx Installs the HardenPlugin, which enhances security by locking down the schema and protecting against malicious queries. Use npm or yarn to install. ```bash npm install @vendure/harden-plugin ``` -------------------------------- ### Example Payment Handler Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/payment/payment-method-handler.mdx This example demonstrates how to create a PaymentMethodHandler for a mock payment provider. It includes the `createPayment` and `settlePayment` methods, showcasing interaction with a hypothetical third-party SDK. ```APIDOC ## Example Payment Handler ### Description This example demonstrates how to create a PaymentMethodHandler for a mock payment provider. It includes the `createPayment` and `settlePayment` methods, showcasing interaction with a hypothetical third-party SDK. ### Usage ```typescript 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 => { 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 => { return { success: true }; } }); ``` ``` -------------------------------- ### Start PostgreSQL Docker Container Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Starts the PostgreSQL 16 Docker container for development against PostgreSQL. ```bash docker-compose up -d postgres_16 ``` -------------------------------- ### isVisible Example for BulkAction Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/admin-ui-api/bulk-actions/bulk-action.mdx Demonstrates how to conditionally display a bulk action based on user permissions and available channels. This example requires importing `registerBulkAction` and `DataService`. ```typescript import { registerBulkAction, DataService } from '@vendure/admin-ui/core'; registerBulkAction({ location: 'product-list', label: 'Assign to channel', // Only display this action if there are multiple channels isVisible: ({ injector }) => injector.get(DataService).client .userStatus() .mapSingle(({ userStatus }) => 1 < userStatus.channels.length) .toPromise(), // ... }); ``` -------------------------------- ### Install BullMQ package Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/job-queue-plugin/bull-mqjob-queue-plugin.mdx Required dependency installation for the plugin. ```shell npm install bullmq@^5.4.2 ``` -------------------------------- ### Install Top-Level Dependencies with Bun Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Install the project's top-level dependencies using Bun. This command should be run in the root directory of the Vendure repository. ```bash bun install ``` -------------------------------- ### SESTransportOptions with Example Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/email-plugin/transport-options.mdx Configure the email plugin to send emails using AWS SES. This example shows how to initialize the SES client and configure the transport options within VendureConfig. ```typescript import { SES, SendRawEmailCommand } from '@aws-sdk/client-ses' const ses = new SES({ apiVersion: '2010-12-01', region: 'eu-central-1', credentials: { accessKeyId: process.env.SES_ACCESS_KEY || '', secretAccessKey: process.env.SES_SECRET_KEY || '', }, }) const config: VendureConfig = { // Add an instance of the plugin to the plugins array plugins: [ EmailPlugin.init({ handler: defaultEmailHandlers, templateLoader: new FileBasedTemplateLoader(path.join(__dirname, '../static/email/templates')), transport: { type: 'ses', SES: { ses, aws: { SendRawEmailCommand } }, sendingRate: 10, // optional messages per second sending rate }, }), ], }; ``` ```typescript interface SESTransportOptions extends SESTransport.Options { type: 'ses'; } ``` -------------------------------- ### PromotionOrderAction Example Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/promotions/promotion-action.mdx Example of creating a PromotionOrderAction to apply a percentage discount to the entire order. This action modifies the order's subTotal based on the discount argument. ```typescript // Applies a percentage discount to the entire Order const orderPercentageDiscount = new PromotionOrderAction({ code: 'order_percentage_discount', args: { discount: 'percentage' }, execute(ctx, order, args) { return -order.subTotal * (args.discount / 100); }, description: 'Discount order by { discount }%', }); ``` -------------------------------- ### Start MariaDB Docker Container Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Starts the MariaDB Docker container, which is the default database for the Vendure dev server if no other DB is specified. ```bash docker-compose up -d mariadb ``` -------------------------------- ### BulkActionComponent Example with Refetching Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/dashboard/list-views/bulk-actions.mdx An example demonstrating a typical bulk action implementation. It shows how to use `usePaginatedList` to refetch data after an action and `table.resetRowSelection()` to clear the selection. ```tsx import { BulkActionComponent, DataTableBulkActionItem, usePaginatedList } from '@vendure/dashboard'; // This is an example of a bulk action that shows some typical // uses of the provided props export const MyBulkAction: BulkActionComponent = ({ selection, table }) => { const { refetchPaginatedList } = usePaginatedList(); const doTheAction = async () => { // Actual logic of the action // goes here... // On success, we refresh the list refetchPaginatedList(); // and un-select any selected rows in the table table.resetRowSelection(); }; return ( Delete} confirmationText={Are you sure?} icon={Check} className="text-destructive" /> ); } ``` -------------------------------- ### Install Vendure Dashboard Package Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/extending-the-dashboard/getting-started/index.mdx Installs the `@vendure/dashboard` package using npm. This is the first step in adding the dashboard to your project. ```bash npm install @vendure/dashboard ``` -------------------------------- ### Configure OpenTelemetry SDK with getSdkConfiguration Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/telemetry-plugin/get-sdk-configuration.mdx Use this example to set up a custom preload script for the OpenTelemetry Node SDK. It demonstrates how to configure exporters, processors, and resource attributes. Ensure environment variables like OTEL_EXPORTER_OTLP_ENDPOINT are set. ```typescript import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'; import { NodeSDK } from '@opentelemetry/sdk-node'; import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; import { getSdkConfiguration } from '@vendure/telemetry-plugin/preload'; process.env.OTEL_EXPORTER_OTLP_ENDPOINT = 'http://localhost:3100/otlp'; process.env.OTEL_LOGS_EXPORTER = 'otlp'; process.env.OTEL_RESOURCE_ATTRIBUTES = 'service.name=vendure-dev-server'; const traceExporter = new OTLPTraceExporter({ url: 'http://localhost:4318/v1/traces', }); const logExporter = new OTLPLogExporter(); const config = getSdkConfiguration({ config: { spanProcessors: [new BatchSpanProcessor(traceExporter)], logRecordProcessors: [new BatchLogRecordProcessor(logExporter)], }, }); const sdk = new NodeSDK(config); sdk.start(); ``` -------------------------------- ### Install copyfiles Dependency Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/extending-the-admin-ui/getting-started/index.mdx These commands show how to install the `copyfiles` package, which is used in the `package.json` scripts for copying build artifacts. It provides instructions for both npm and yarn package managers. ```bash npm install copyfiles ``` ```bash yarn add copyfiles ``` -------------------------------- ### Install Loyalty Points Plugin Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/how-to/publish-plugin/index.mdx Install the loyalty points plugin package using npm. This is the first step before configuring the plugin in the Vendure project. ```bash npm install @acme/vendure-plugin-loyalty-points ``` -------------------------------- ### Worker Health Check Request Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/deployment/using-docker.mdx Example GET request to the worker's health check endpoint. ```text REQUEST: GET http://localhost:3020/health ``` -------------------------------- ### Start Release Versioning and Building Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Initiates the release process by running Lerna to version packages, build them, and create a changelog. Manually select the version number when prompted. ```bash bun run publish-release ``` -------------------------------- ### Server Health Check Request Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/deployment/using-docker.mdx Example GET request to the server's health check endpoint. ```text REQUEST: GET http://localhost:3000/health ``` -------------------------------- ### Displaying Product Images with Transformations Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/storefront/product-detail/index.mdx Demonstrates how to use query parameters with image URLs to apply size presets and format conversions (like WebP) for optimized image display. Includes a React component example using the `` element for advanced format selection. ```APIDOC ## Displaying Images with Transformations To leverage dynamic image transformations provided by the `AssetServerPlugin`, append query strings to your image URLs. ### Example Usage To use the `'large'` size preset (800x800) and convert the image to WebP format: ```tsx ``` ### Advanced Usage with `` Element For optimal format selection by the browser, use the HTML `` element. This can be encapsulated in a reusable component. ```tsx interface VendureAssetProps { preview: string; preset: 'tiny' | 'thumb' | 'small' | 'medium' | 'large'; alt: string; } export function VendureAsset({ preview, preset, alt }: VendureAssetProps) { return ( {alt} ); } ``` ``` -------------------------------- ### Populate Vendure with Test Data using @vendure/create Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/developer-guide/importing-data/index.mdx This script populates an existing Vendure installation with test data, similar to the initial setup. It requires `@vendure/create` to be installed as a dev dependency. Ensure your database tables are dropped before running this script. ```typescript import { populate } from '@vendure/core/cli'; import { bootstrap, VendureConfig } from '@vendure/core'; import { config } from './vendure-config'; populate( () => bootstrap({ ...config, importExportOptions: { importAssetsDir: path.join( require.resolve('@vendure/create/assets/products.csv'), '../images' ), }, dbConnectionOptions: {...config.dbConnectionOptions, synchronize: true} }), require('@vendure/create/assets/initial-data.json'), require.resolve('@vendure/create/assets/products.csv') ) .then(app => app.close()) .catch(err => { console.log(err); process.exit(1); }); ``` -------------------------------- ### Build Reference Documentation Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Builds the auto-generated reference documentation. This command should be run from the project root directory. ```bash bun run docs:build ``` -------------------------------- ### Create and Use Cache Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/cache/index.mdx Demonstrates how to create a Cache instance with custom key generation and default options, and then use it to retrieve or compute and store data. ```typescript const cache = cacheService.createCache({ getKey: id => `ProductVariantIds:${id}`, options: { ttl: 1000 * 60 * 60, tags: ['products'], }, }); // This will fetch the value from the cache if it exists, or // fetch it from the ProductService if not, and then cache // using the key 'ProductVariantIds.${id}'. const variantIds = await cache.get(id, async () => { const variants await ProductService.getVariantsByProductId(ctx, id) ; // The cached value must be serializable, so we just return the ids return variants.map(v => v.id); }); ``` -------------------------------- ### Preload OpenTelemetry SDK Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/telemetry-plugin/index.mdx Preload the OpenTelemetry SDK in an instrumentation script before starting the Vendure server. This example configures OTLP exporters for logs and traces. ```typescript import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'; import { NodeSDK } from '@opentelemetry/sdk-node'; import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'; import { getSdkConfiguration } from '@vendure/telemetry-plugin/preload'; // In this example we are using Loki as the OTLP endpoint for logging process.env.OTEL_EXPORTER_OTLP_ENDPOINT = 'http://localhost:3100/otlp'; process.env.OTEL_LOGS_EXPORTER = 'otlp'; process.env.OTEL_RESOURCE_ATTRIBUTES = 'service.name=vendure-dev-server'; // We are using Jaeger as the OTLP endpoint for tracing const traceExporter = new OTLPTraceExporter({ url: 'http://localhost:4318/v1/traces', }); const logExporter = new OTLPLogExporter(); // The getSdkConfiguration method returns a configuration object for the OpenTelemetry Node SDK. // It also performs other configuration tasks such as setting a special environment variable // to enable instrumentation in the Vendure core code. const config = getSdkConfiguration({ config: { // Pass in any custom configuration options for the Node SDK here spanProcessors: [new BatchSpanProcessor(traceExporter)], logRecordProcessors: [new BatchLogRecordProcessor(logExporter)], }, }); const sdk = new NodeSDK(config); sdk.start(); ``` -------------------------------- ### Populate Test Data for Dev Server Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Navigates to the dev-server package and runs the script to populate the database with test data. Assumes MySQL/MariaDB by default. ```bash cd packages/dev-server bun run populate ``` -------------------------------- ### Watch Email Plugin Changes Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Starts a watcher for the email-plugin package to automatically recompile changes. This is part of a two-terminal setup for testing backend changes. ```bash cd packages/email-plugin bun run watch ``` -------------------------------- ### Example Usage of BaseDetailComponent Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/admin-ui-api/list-detail-views/base-detail-component.mdx Demonstrates how to extend BaseDetailComponent to create a custom entity detail component. It includes form group setup and the implementation of the setFormValues method. ```typescript import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { BaseDetailComponent, ServerConfigService, DataService, LanguageCode, MyEntityFragment } from '@vendure/admin-ui'; @Component({ selector: 'app-my-entity', templateUrl: './my-entity.component.html', styleUrls: ['./my-entity.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class GlobalSettingsComponent extends BaseDetailComponent implements OnInit { detailForm: FormGroup; constructor( router: Router, route: ActivatedRoute, serverConfigService: ServerConfigService, protected dataService: DataService, private formBuilder: FormBuilder, ) { super(route, router, serverConfigService, dataService); this.detailForm = this.formBuilder.group({ name: [''], }); } protected setFormValues(entity: MyEntityFragment, languageCode: LanguageCode): void { this.detailForm.patchValue({ name: entity.name, }); } } ``` -------------------------------- ### SharpAssetPreviewStrategy Constructor Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/asset-server-plugin/sharp-asset-preview-strategy.mdx Initializes the SharpAssetPreviewStrategy with optional configuration for preview generation. ```APIDOC ## SharpAssetPreviewStrategy This strategy uses the [Sharp library](https://sharp.pixelplumbing.com/) to generate preview images of uploaded binary files. For non-image binaries, a generic "file" icon with the mime type overlay will be generated. By default, this strategy will produce previews up to maximum dimensions of 1600 x 1600 pixels. The created preview images will match the input format - so a source file in jpeg format will output a jpeg preview, a webp source file will output a webp preview, and so on. The settings for the outputs will default to Sharp's defaults (https://sharp.pixelplumbing.com/api-output). However, it is possible to pass your own configurations to control the output of each format: ```ts AssetServerPlugin.init({ previewStrategy: new SharpAssetPreviewStrategy({ jpegOptions: { quality: 95 }, webpOptions: { quality: 95 }, }), }), ``` ### Constructor ```ts constructor(config?: SharpAssetPreviewConfig) ``` #### Parameters - **config** (SharpAssetPreviewConfig) - Optional configuration object to customize preview generation. ``` -------------------------------- ### Start Job Queue on Main Server Process Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/developer-guide/worker-job-queue/index.mdx Starts the JobQueueService on the main Vendure server process. This is primarily for testing or automated tasks and is not recommended for production as it bypasses the benefits of background processing. It requires manually getting the `JobQueueService` from the application context. ```typescript import { bootstrap, JobQueueService } from '@vendure/core'; import { config } from './vendure-config'; bootstrap(config) .then(app => app.get(JobQueueService).start()) .catch(err => { console.log(err); process.exit(1); }); ``` -------------------------------- ### Install Dependencies with Force Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md If encountering 'Error: Bindings not found.', use this command to reinstall dependencies, forcing resolution. ```bash bun install --force ``` -------------------------------- ### Configure DashboardPlugin in Vendure Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/extending-the-dashboard/getting-started/index.mdx Registers the DashboardPlugin in the Vendure configuration object. It requires specifying the route and the directory where the dashboard build files are located. ```typescript import { DashboardPlugin } from '@vendure/dashboard/plugin'; const config: VendureConfig = { plugins: [ DashboardPlugin.init({ route: 'dashboard', appDir: './dist/dashboard', }), ], }; ``` -------------------------------- ### Example: Get Buffer Sizes (TypeScript) Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/job-queue/job-buffer-storage-strategy.mdx Demonstrates how to retrieve the number of buffered jobs for specific buffer IDs using the `bufferSize` method. This is useful for monitoring job queue load. ```typescript const sizes = await myJobBufferStrategy.bufferSize(['buffer-1', 'buffer-2']); // sizes = { 'buffer-1': 12, 'buffer-2': 3 } ``` -------------------------------- ### RedisSessionCacheStrategy Implementation Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/auth/session-cache-strategy.mdx An example implementation of SessionCacheStrategy using Redis for caching session data. Requires the 'ioredis' package. Initializes a Redis client and provides methods for getting, setting, and deleting cached sessions. ```typescript import { CachedSession, Logger, SessionCacheStrategy, VendurePlugin } from '@vendure/core'; import { Redis, RedisOptions } from 'ioredis'; export interface RedisSessionCachePluginOptions { namespace?: string; redisOptions?: RedisOptions; } const loggerCtx = 'RedisSessionCacheStrategy'; const DEFAULT_NAMESPACE = 'vendure-session-cache'; const DEFAULT_TTL = 86400; export class RedisSessionCacheStrategy implements SessionCacheStrategy { private client: Redis; constructor(private options: RedisSessionCachePluginOptions) {} init() { this.client = new Redis(this.options.redisOptions as RedisOptions); this.client.on('error', err => Logger.error(err.message, loggerCtx, err.stack)); } async destroy() { await this.client.quit(); } async get(sessionToken: string): Promise { try { const retrieved = await this.client.get(this.namespace(sessionToken)); if (retrieved) { try { return JSON.parse(retrieved); } catch (e: any) { Logger.error(`Could not parse cached session data: ${e.message}`, loggerCtx); } } } catch (e: any) { Logger.error(`Could not get cached session: ${e.message}`, loggerCtx); } } async set(session: CachedSession) { try { await this.client.set(this.namespace(session.token), JSON.stringify(session), 'EX', DEFAULT_TTL); } catch (e: any) { Logger.error(`Could not set cached session: ${e.message}`, loggerCtx); } } async delete(sessionToken: string) { try { await this.client.del(this.namespace(sessionToken)); } catch (e: any) { Logger.error(`Could not delete cached session: ${e.message}`, loggerCtx); } } clear() { // not implemented } private namespace(key: string) { return `${this.options.namespace ?? DEFAULT_NAMESPACE}:${key}`; } } @VendurePlugin({ configuration: config => { config.authOptions.sessionCacheStrategy = new RedisSessionCacheStrategy( RedisSessionCachePlugin.options, ); return config; }, }) export class RedisSessionCachePlugin { static options: RedisSessionCachePluginOptions; static init(options: RedisSessionCachePluginOptions) { this.options = options; return this; } } ``` -------------------------------- ### Populate Database with Test Data Source: https://github.com/vendurehq/vendure/blob/master/packages/dev-server/README.md Populate the specified database with test data, similar to the Vendure CLI init process, including sample customer and address data. ```bash [DB=mysql|postgres|sqlite] bun run populate ``` -------------------------------- ### Configure Vendure with Multi-Vendor Plugin Source: https://github.com/vendurehq/vendure/blob/master/packages/dev-server/example-plugins/multivendor-plugin/README.md Integrates the MultivendorPlugin into the VendureConfig. Requires platform fee percentage and SKU as initialization parameters. This setup is essential for enabling marketplace features. ```typescript import { MultivendorPlugin } from './plugins/multivendor-plugin/multivendor.plugin'; plugins: [ MultivendorPlugin.init({ platformFeePercent: 10, platformFeeSKU: 'FEE', }), // ... ] ``` -------------------------------- ### create Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/services/product-service.mdx Creates a new product. ```APIDOC ## create ### Description Creates a new product. ### Method `create(ctx: RequestContext, input: CreateProductInput): Promise>` ``` -------------------------------- ### Configure TypeScript Monorepo for Vendure Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/developer-guide/cli/index.mdx Example configuration for a monorepo setup where package-specific tsconfig.json files extend a root configuration to support path mappings. ```json { "compilerOptions": { "baseUrl": ".", "paths": { "@my-org/shared": ["libs/shared/src/index.ts"] } } } ``` ```json { "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "./dist" } } ``` -------------------------------- ### Update tsconfig.json for Vendure Dashboard Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/extending-the-dashboard/getting-started/index.mdx Modifies the main `tsconfig.json` to exclude dashboard-related files and include a new `tsconfig.dashboard.json`. This ensures proper compilation settings for both the main project and the dashboard extensions. ```json { // ... existing options "exclude": [ "node_modules", "migration.ts", "src/plugins/**/ui/*", "admin-ui", "src/plugins/**/dashboard/*", // [!code highlight] "src/gql/*", // [!code highlight] "vite.*.*ts" // [!code highlight] ], "references": [ // [!code highlight] { "path": "./tsconfig.dashboard.json" // [!code highlight] } ] // [!code highlight] } ``` -------------------------------- ### Initialize Strapi Project via CLI Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/how-to/cms-integration-plugin/index.mdx Uses the Strapi CLI to bootstrap a new project. Requires Node.js and npm to be installed on the system. ```bash npx create-strapi-app@latest strapi-integration-app cd strapi-integration-app ``` -------------------------------- ### Configure Vite for Vendure Dashboard Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/extending-the-dashboard/getting-started/index.mdx Sets up the `vite.config.mts` file to integrate the Vendure Dashboard. It configures the base path, build output directory, and the `vendureDashboardPlugin` with essential paths for configuration, API, and GraphQL output. ```typescript import { vendureDashboardPlugin } from '@vendure/dashboard/vite'; import { join, resolve } from 'path'; import { pathToFileURL } from 'url'; import { defineConfig } from 'vite'; export default defineConfig({ base: '/dashboard', build: { outDir: join(__dirname, 'dist/dashboard'), }, plugins: [ vendureDashboardPlugin({ // The vendureDashboardPlugin will scan your configuration in order // to find any plugins which have dashboard extensions, as well as // to introspect the GraphQL schema based on any API extensions // and custom fields that are configured. vendureConfigPath: pathToFileURL('./src/vendure-config.ts'), // Points to the location of your Vendure server. api: { host: 'http://localhost', port: 3000 }, // When you start the Vite server, your Admin API schema will // be introspected and the types will be generated in this location. // These types can be used in your dashboard extensions to provide // type safety when writing queries and mutations. gqlOutputPath: './src/gql', }), ], resolve: { alias: { // This allows all plugins to reference a shared set of // GraphQL types. '@/gql': resolve(__dirname, './src/gql/graphql.ts'), }, }, }); ``` -------------------------------- ### Create tsconfig.dashboard.json for Vendure Dashboard Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/extending-the-dashboard/getting-started/index.mdx Creates a `tsconfig.dashboard.json` file to configure TypeScript compiler options specifically for the Vendure Dashboard. It enables JSX support and sets up path aliases for GraphQL types and internal Vendure Dashboard modules. ```json { "compilerOptions": { "composite": true, "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx", "paths": { // Import alias for the GraphQL types // Please adjust to the location that you have set in your `vite.config.mts` "@/gql": [ "./src/gql/graphql.ts" ], // This line allows TypeScript to properly resolve internal // Vendure Dashboard imports, which is necessary for // type safety in your dashboard extensions. // This path assumes a root-level tsconfig.json file. // You may need to adjust it if your project structure is different. "@/vdb/*": [ "./node_modules/@vendure/dashboard/src/lib/*" ] } }, "include": [ "src/plugins/**/dashboard/*", "src/gql/**/*.ts" ] } ``` -------------------------------- ### Initialize AssetServerPlugin with SharpAssetPreviewStrategy Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/asset-server-plugin/sharp-asset-preview-strategy.mdx Configure the AssetServerPlugin to use the SharpAssetPreviewStrategy, customizing JPEG and WebP output quality. ```typescript AssetServerPlugin.init({ previewStrategy: new SharpAssetPreviewStrategy({ jpegOptions: { quality: 95 }, webpOptions: { quality: 95 }, }), }) ``` -------------------------------- ### Vendure Dashboard Commands (CLI) Source: https://github.com/vendurehq/vendure/blob/master/packages/dashboard/plugin/default-page.html These commands are used to manage the Vendure dashboard. 'npx vite' starts the development server, allowing for live reloading during development. 'npx vite build' compiles the dashboard for production deployment. ```bash npx vite ``` ```bash npx vite build ``` -------------------------------- ### Database Selection Prompt in @vendure/create Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/getting-started/installation/index.mdx Illustrates the interactive prompt within the @vendure/create tool for selecting a database. It shows the 'Manual Configuration' path and highlights the option to choose SQLite, which requires no external dependencies and is recommended for quick testing. ```console ┌ Let's create a Vendure App ✨ │ ◇ How should we proceed? │ Manual Configuration │ ◇ Using port 3000 │ ◆ Which database are you using? │ ○ MySQL │ ○ MariaDB │ ○ Postgres │ ● SQLite # [!code highlight] └ ``` -------------------------------- ### Control Access to Vendure REST Endpoint Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/developer-guide/rest-endpoint/index.mdx Secures a Vendure REST endpoint by specifying required permissions using the `@Allow` decorator. In this example, only users with the `Permission.ReadProduct` permission can access the `/products` GET endpoint. This decorator is applied directly above the route handler method. ```typescript import { Controller, Get } from '@nestjs/common'; import { Allow, Permission, Ctx, ProductService, RequestContext } from '@vendure/core'; @Controller('products') export class ProductsController { constructor(private productService: ProductService) {} @Allow(Permission.ReadProduct) // [!code highlight] @Get() findAll(@Ctx() ctx: RequestContext) { return this.productService.findAll(ctx); } } ``` -------------------------------- ### Development Server Source: https://github.com/vendurehq/vendure/blob/master/packages/admin-ui/README.md Start the development server to view localization changes. Ensure new languages are added to `availableLanguages` in `vendure-ui-config.json`. ```bash bun run dev ``` -------------------------------- ### Initialize Sanity Studio Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/how-to/cms-integration-plugin/index.mdx CLI commands to bootstrap a new Sanity Studio project and start the development server for local integration testing. ```bash npm create sanity@latest -- --project --dataset production --template clean --typescript --output-path studio-vendure-plugin cd studio-vendure-plugin npm run dev ``` -------------------------------- ### Scaffold Vendure Project with @vendure/create Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/getting-started/installation/index.mdx Initiates the creation of a new Vendure project by running the @vendure/create command-line tool. This tool scaffolds the project structure and installs necessary dependencies. The command requires a project name as an argument. ```bash npx @vendure/create my-shop ``` -------------------------------- ### Install S3 Dependencies Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/asset-server-plugin/s3asset-storage-strategy.mdx Before using the S3AssetStorageStrategy, install the necessary AWS SDK packages. ```sh npm install @aws-sdk/client-s3 @aws-sdk/lib-storage ``` -------------------------------- ### Scaffold project with verbose logging Source: https://github.com/vendurehq/vendure/blob/master/packages/create/README.md Initializes a new Vendure application while setting the log level to verbose for detailed installation output. ```shell npx @vendure/create my-app --log-level verbose ``` -------------------------------- ### Install Dataloader Dependency Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/guides/developer-guide/dataloaders/index.mdx Command to install the dataloader package required for batching requests. ```bash npm install dataloader ``` -------------------------------- ### Create and Use a Job Queue Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/job-queue/job-queue-service.mdx Demonstrates how to initialize a JobQueue within a service and add jobs to it. The queue is configured with a name and a processing function. ```typescript 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 } } ``` -------------------------------- ### Install BullMQ dependency Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/core-plugins/job-queue-plugin/bull-mqjob-queue-strategy.mdx Command to install the required bullmq package for the JobQueueStrategy. ```shell npm install bullmq@^5.4.2 ``` -------------------------------- ### UuidIdStrategy Configuration Example Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/configuration/entity-id-strategy.mdx Example of how to configure the UuidIdStrategy in VendureConfig to use UUIDs as primary keys. ```typescript import { UuidIdStrategy, VendureConfig } from '@vendure/core'; export const config: VendureConfig = { entityOptions: { entityIdStrategy: new UuidIdStrategy(), // ... } } ``` -------------------------------- ### Install Vendure Core Package Source: https://github.com/vendurehq/vendure/blob/master/packages/core/README.md This command installs the core Vendure package using npm. It is the first step in setting up a Vendure project. Ensure you have Node.js and npm installed. ```bash $ npm install @vendure/core ``` -------------------------------- ### Resolver Function Example Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/data-access/list-query-builder.mdx Example of a Vendure resolver function that uses the BlogPostService to fetch blog posts. ```typescript @Resolver() export class BlogPostResolver constructor(private blogPostService: BlogPostService) {} @Query() async blogPosts( @Ctx() ctx: RequestContext, @Args() args: any, ): Promise> { return this.blogPostService.findAll(ctx, args.options || undefined); } } ``` -------------------------------- ### Lucide React Icon Import Example Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/dashboard/extensions-api/navigation.mdx Example of how to import icons from 'lucide-react' to be used with navigation items. ```typescript import { PlusIcon } from 'lucide-react'; ``` -------------------------------- ### Populate Test Data with PostgreSQL Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Runs the populate script with the DB environment variable set to 'postgres' to populate the PostgreSQL database. ```bash DB=postgres bun run populate ``` -------------------------------- ### init Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/import-export/default-asset-import-strategy.mdx Initializes the strategy with the given injector. ```APIDOC ## init ### Description Initializes the strategy with the given injector. ### Method init ### Parameters * **injector** (Injector) - Required - The injector to use for initialization. ``` -------------------------------- ### Start Elasticsearch Docker Container Source: https://github.com/vendurehq/vendure/blob/master/CONTRIBUTING.md Starts the Elasticsearch Docker container, necessary when developing Elasticsearch-related plugins. ```bash docker-compose up -d elasticsearch ``` -------------------------------- ### Custom OrderByCodeAccessStrategy Example Source: https://github.com/vendurehq/vendure/blob/master/docs/docs/reference/typescript-api/orders/order-by-code-access-strategy.mdx Implement a custom strategy to control order access. This example denies access on Mondays. ```typescript export class NotMondayOrderByCodeAccessStrategy implements OrderByCodeAccessStrategy { canAccessOrder(ctx: RequestContext, order: Order): boolean { const MONDAY = 1; const today = (new Date()).getDay(); return today !== MONDAY; } } ```