Przeglądaj źródła

chore: Tidy up dev server files

Michael Bromley 1 rok temu
rodzic
commit
45a2a8bd7a

+ 0 - 287
packages/dev-server/cockroachdb-search-strategy.ts

@@ -1,287 +0,0 @@
-import { LogicalOperator, SearchInput, SearchResult } from '@vendure/common/lib/generated-types';
-import { ID } from '@vendure/common/lib/shared-types';
-import {
-    Injector,
-    PLUGIN_INIT_OPTIONS,
-    RequestContext,
-    TransactionalConnection,
-    UserInputError,
-} from '@vendure/core';
-import { SearchIndexItem } from '@vendure/core/dist/plugin/default-search-plugin/entities/search-index-item.entity';
-import { SearchStrategy } from '@vendure/core/dist/plugin/default-search-plugin/search-strategy/search-strategy';
-import { getFieldsToSelect } from '@vendure/core/dist/plugin/default-search-plugin/search-strategy/search-strategy-common';
-import {
-    applyLanguageConstraints,
-    createCollectionIdCountMap,
-    createFacetIdCountMap,
-    createPlaceholderFromId,
-    mapToSearchResult,
-} from '@vendure/core/dist/plugin/default-search-plugin/search-strategy/search-strategy-utils';
-import { DefaultSearchPluginInitOptions } from '@vendure/core/dist/plugin/default-search-plugin/types';
-import { Brackets, SelectQueryBuilder } from 'typeorm';
-
-/**
- * A weighted fulltext search for PostgeSQL.
- */
-export class CockroachdbSearchStrategy implements SearchStrategy {
-    protected readonly minTermLength = 2;
-    protected connection: TransactionalConnection;
-    protected options: DefaultSearchPluginInitOptions;
-
-    async init(injector: Injector) {
-        this.connection = injector.get(TransactionalConnection);
-        this.options = injector.get(PLUGIN_INIT_OPTIONS);
-    }
-
-    async getFacetValueIds(
-        ctx: RequestContext,
-        input: SearchInput,
-        enabledOnly: boolean,
-    ): Promise<Map<ID, number>> {
-        const facetValuesQb = this.connection
-            .getRepository(ctx, SearchIndexItem)
-            .createQueryBuilder('si')
-            .select(['"si"."productId"', 'MAX("si"."productVariantId")'])
-            .addSelect('string_agg("si"."facetValueIds",\',\')', 'facetValues');
-
-        this.applyTermAndFilters(ctx, facetValuesQb, input, true);
-        if (!input.groupByProduct) {
-            facetValuesQb.groupBy('"si"."productVariantId", "si"."productId"');
-        }
-        if (enabledOnly) {
-            facetValuesQb.andWhere('"si"."enabled" = :enabled', { enabled: true });
-        }
-        const facetValuesResult = await facetValuesQb.getRawMany();
-        return createFacetIdCountMap(facetValuesResult);
-    }
-
-    async getCollectionIds(
-        ctx: RequestContext,
-        input: SearchInput,
-        enabledOnly: boolean,
-    ): Promise<Map<ID, number>> {
-        const collectionsQb = this.connection
-            .getRepository(ctx, SearchIndexItem)
-            .createQueryBuilder('si')
-            .select(['"si"."productId"', 'MAX("si"."productVariantId")'])
-            .addSelect('string_agg("si"."collectionIds",\',\')', 'collections');
-
-        this.applyTermAndFilters(ctx, collectionsQb, input, true);
-        if (!input.groupByProduct) {
-            collectionsQb.groupBy('"si"."productVariantId", "si"."productId"');
-        }
-        if (enabledOnly) {
-            collectionsQb.andWhere('"si"."enabled" = :enabled', { enabled: true });
-        }
-        const collectionsResult = await collectionsQb.getRawMany();
-        return createCollectionIdCountMap(collectionsResult);
-    }
-
-    async getSearchResults(
-        ctx: RequestContext,
-        input: SearchInput,
-        enabledOnly: boolean,
-    ): Promise<SearchResult[]> {
-        const take = input.take || 25;
-        const skip = input.skip || 0;
-        const sort = input.sort;
-        const qb = this.connection
-            .getRepository(ctx, SearchIndexItem)
-            .createQueryBuilder('si')
-            .select(this.createPostgresSelect(!!input.groupByProduct));
-        if (input.groupByProduct) {
-            qb.addSelect('MIN(si.price)', 'minPrice')
-                .addSelect('MAX(si.price)', 'maxPrice')
-                .addSelect('MIN(si.priceWithTax)', 'minPriceWithTax')
-                .addSelect('MAX(si.priceWithTax)', 'maxPriceWithTax');
-        }
-        this.applyTermAndFilters(ctx, qb, input);
-
-        if (sort) {
-            if (sort.name) {
-                qb.addOrderBy('"si_productName"', sort.name);
-            }
-            if (sort.price) {
-                qb.addOrderBy('"si_price"', sort.price);
-            }
-        } else {
-            if (input.term && input.term.length > this.minTermLength) {
-                qb.addOrderBy('score', 'DESC');
-            } else {
-                qb.addOrderBy('"si_productVariantId"', 'ASC');
-            }
-        }
-        if (enabledOnly) {
-            qb.andWhere('"si"."enabled" = :enabled', { enabled: true });
-        }
-
-        return qb
-            .limit(take)
-            .offset(skip)
-            .getRawMany()
-            .then(res => res.map(r => mapToSearchResult(r, ctx.channel.defaultCurrencyCode)));
-    }
-
-    async getTotalCount(ctx: RequestContext, input: SearchInput, enabledOnly: boolean): Promise<number> {
-        const innerQb = this.applyTermAndFilters(
-            ctx,
-            this.connection
-                .getRepository(ctx, SearchIndexItem)
-                .createQueryBuilder('si')
-                .select(this.createPostgresSelect(!!input.groupByProduct)),
-            input,
-        );
-        if (enabledOnly) {
-            innerQb.andWhere('"si"."enabled" = :enabled', { enabled: true });
-        }
-        const totalItemsQb = this.connection.rawConnection
-            .createQueryBuilder()
-            .select('COUNT(*) as total')
-            .from(`(${innerQb.getQuery()})`, 'inner')
-            .setParameters(innerQb.getParameters());
-        return totalItemsQb.getRawOne().then(res => res.total);
-    }
-
-    protected applyTermAndFilters(
-        ctx: RequestContext,
-        qb: SelectQueryBuilder<SearchIndexItem>,
-        input: SearchInput & { inStock?: boolean },
-        forceGroup: boolean = false,
-    ): SelectQueryBuilder<SearchIndexItem> {
-        const { term, facetValueFilters, facetValueIds, facetValueOperator, collectionId, collectionSlug } =
-            input;
-        // join multiple words with the logical AND operator
-        const termLogicalAnd = term
-            ? term
-                  .trim()
-                  .split(/\s+/g)
-                  .map(t => `'${t}':*`)
-                  .join(' & ')
-            : '';
-
-        qb.where('1 = 1');
-        if (term && term.length > this.minTermLength) {
-            const minIfGrouped = (colName: string) =>
-                input.groupByProduct || forceGroup ? `MIN(${colName})` : colName;
-            qb.addSelect(
-                `
-                    (ts_rank_cd(to_tsvector(${minIfGrouped('si.sku')}), to_tsquery(:term)) * 10 +
-                    ts_rank_cd(to_tsvector(${minIfGrouped('si.productName')}), to_tsquery(:term)) * 2 +
-                    ts_rank_cd(to_tsvector(${minIfGrouped(
-                        'si.productVariantName',
-                    )}), to_tsquery(:term)) * 1.5 +
-                    ts_rank_cd(to_tsvector(${minIfGrouped('si.description')}), to_tsquery(:term)) * 1)
-                            `,
-                'score',
-            )
-                .andWhere(
-                    new Brackets(qb1 => {
-                        qb1.where('to_tsvector(si.sku) @@ to_tsquery(:term)')
-                            .orWhere('to_tsvector(si.productName) @@ to_tsquery(:term)')
-                            .orWhere('to_tsvector(si.productVariantName) @@ to_tsquery(:term)')
-                            .orWhere('to_tsvector(si.description) @@ to_tsquery(:term)');
-                    }),
-                )
-                .setParameters({ term: termLogicalAnd });
-        }
-        if (input.inStock != null) {
-            if (input.groupByProduct) {
-                qb.andWhere('si.productInStock = :inStock', { inStock: input.inStock });
-            } else {
-                qb.andWhere('si.inStock = :inStock', { inStock: input.inStock });
-            }
-        }
-        if (facetValueIds?.length) {
-            qb.andWhere(
-                new Brackets(qb1 => {
-                    for (const id of facetValueIds) {
-                        const placeholder = createPlaceholderFromId(id);
-                        const clause = `:${placeholder} = ANY (string_to_array(si.facetValueIds, ','))`;
-                        const params = { [placeholder]: id };
-                        if (facetValueOperator === LogicalOperator.AND) {
-                            qb1.andWhere(clause, params);
-                        } else {
-                            qb1.orWhere(clause, params);
-                        }
-                    }
-                }),
-            );
-        }
-        if (facetValueFilters?.length) {
-            qb.andWhere(
-                new Brackets(qb1 => {
-                    for (const facetValueFilter of facetValueFilters) {
-                        qb1.andWhere(
-                            new Brackets(qb2 => {
-                                if (facetValueFilter.and && facetValueFilter.or?.length) {
-                                    throw new UserInputError('error.facetfilterinput-invalid-input');
-                                }
-                                if (facetValueFilter.and) {
-                                    const placeholder = createPlaceholderFromId(facetValueFilter.and);
-                                    const clause = `:${placeholder} = ANY (string_to_array(si.facetValueIds, ','))`;
-                                    const params = { [placeholder]: facetValueFilter.and };
-                                    qb2.where(clause, params);
-                                }
-                                if (facetValueFilter.or?.length) {
-                                    for (const id of facetValueFilter.or) {
-                                        const placeholder = createPlaceholderFromId(id);
-                                        const clause = `:${placeholder} = ANY (string_to_array(si.facetValueIds, ','))`;
-                                        const params = { [placeholder]: id };
-                                        qb2.orWhere(clause, params);
-                                    }
-                                }
-                            }),
-                        );
-                    }
-                }),
-            );
-        }
-        if (collectionId) {
-            qb.andWhere(":collectionId::varchar = ANY (string_to_array(si.collectionIds, ','))", {
-                collectionId,
-            });
-        }
-        if (collectionSlug) {
-            qb.andWhere(":collectionSlug::varchar = ANY (string_to_array(si.collectionSlugs, ','))", {
-                collectionSlug,
-            });
-        }
-
-        applyLanguageConstraints(qb, ctx.languageCode, ctx.channel.defaultLanguageCode);
-        qb.andWhere('si.channelId = :channelId', { channelId: ctx.channelId });
-        if (input.groupByProduct === true) {
-            qb.groupBy('si.productId');
-        }
-        return qb;
-    }
-
-    /**
-     * When a select statement includes a GROUP BY clause,
-     * then all selected columns must be aggregated. So we just apply the
-     * "MIN" function in this case to all other columns than the productId.
-     */
-    private createPostgresSelect(groupByProduct: boolean): string {
-        return getFieldsToSelect(this.options.indexStockStatus)
-            .map(col => {
-                const qualifiedName = `si.${col}`;
-                const alias = `si_${col}`;
-                if (groupByProduct && col !== 'productId') {
-                    if (
-                        col === 'facetIds' ||
-                        col === 'facetValueIds' ||
-                        col === 'collectionIds' ||
-                        col === 'channelIds'
-                    ) {
-                        return `string_agg(${qualifiedName}, ',') as "${alias}"`;
-                    } else if (col === 'enabled' || col === 'inStock' || col === 'productInStock') {
-                        return `bool_or(${qualifiedName}) as "${alias}"`;
-                    } else {
-                        return `MIN(${qualifiedName}) as "${alias}"`;
-                    }
-                } else {
-                    return `${qualifiedName} as "${alias}"`;
-                }
-            })
-            .join(', ');
-    }
-}

+ 0 - 29
packages/dev-server/compileUiExtensions.ts

@@ -1,29 +0,0 @@
-import { compileUiExtensions } from '@vendure/ui-devkit/compiler';
-import path from 'path';
-import { ReviewsPlugin } from './test-plugins/reviews/reviews-plugin';
-
-void compileUiExtensions({
-    ngCompilerPath: path.join(__dirname, '../../node_modules/@angular/cli/bin/ng.js'),
-    outputPath: path.join(__dirname, './custom-admin-ui'),
-    extensions: [
-        {
-            id: 'greeter',
-            extensionPath: path.join(__dirname, 'test-plugins/with-ui-extension/ui'),
-            ngModules: [
-                {
-                    type: 'lazy',
-                    route: 'greetz',
-                    ngModuleFileName: 'greeter.module.ts',
-                    ngModuleName: 'GreeterModule',
-                },
-                {
-                    type: 'shared',
-                    ngModuleFileName: 'greeter-shared.module.ts',
-                    ngModuleName: 'GreeterSharedModule',
-                },
-            ],
-            routes: [{}],
-        },
-        ReviewsPlugin.uiExtensions,
-    ],
-}).compile?.();

+ 0 - 187
packages/dev-server/eager-relations-bug.ts

@@ -1,187 +0,0 @@
-import { Mutation, Resolver } from '@nestjs/graphql';
-import { DeepPartial } from '@vendure/common/lib/shared-types';
-import {
-    ActiveOrderService,
-    Ctx,
-    CustomFieldRelationService,
-    isGraphQlErrorResult,
-    LanguageCode,
-    Order,
-    OrderService,
-    PluginCommonModule,
-    RequestContext,
-    Transaction,
-    TransactionalConnection,
-    VendurePlugin,
-} from '@vendure/core';
-import { VendureEntity, EntityId, ID, OrderLine } from '@vendure/core';
-import gql from 'graphql-tag';
-import { Column, Entity, ManyToOne } from 'typeorm';
-
-@Entity()
-export class CutCode extends VendureEntity {
-    constructor(input?: DeepPartial<CutCode>) {
-        super(input);
-    }
-
-    @Column()
-    code: string;
-}
-
-@Entity()
-class Cut extends VendureEntity {
-    constructor(input?: DeepPartial<Cut>) {
-        super(input);
-    }
-
-    @ManyToOne(() => OrderLine, { onDelete: 'CASCADE', nullable: true })
-    orderLine: OrderLine;
-
-    @EntityId()
-    orderLineId: ID;
-
-    // ---> BUG: This eager definition won't work as soon as the customField 'cuts' on the OrderLine is set to be eagerly loaded
-    @ManyToOne(() => CutCode, { eager: true })
-    code: CutCode;
-
-    @EntityId()
-    codeId: ID;
-
-    @Column()
-    name: string;
-}
-
-const commonApiExtensions = gql`
-    type CutCode implements Node {
-        id: ID!
-        createdAt: DateTime!
-        updatedAt: DateTime!
-        code: String!
-    }
-    type Cut implements Node {
-        id: ID!
-        createdAt: DateTime!
-        updatedAt: DateTime!
-        orderLine: OrderLine!
-        name: String!
-        code: CutCode!
-    }
-    extend type Mutation {
-        addCutToOrder: Order
-    }
-`;
-
-@Resolver('Order')
-export class EagerRelationsBugOrderResolver {
-    constructor(
-        private connection: TransactionalConnection,
-        private activeOrderService: ActiveOrderService,
-        private orderService: OrderService,
-        private customFieldRelationService: CustomFieldRelationService,
-    ) {}
-
-    @Transaction()
-    @Mutation()
-    async addCutToOrder(@Ctx() ctx: RequestContext): Promise<Order | null> {
-        const sessionOrder = await this.activeOrderService.getActiveOrder(ctx, {}, true);
-
-        const order = await this.orderService.findOne(ctx, sessionOrder.id);
-
-        if (!order) {
-            return null;
-        }
-
-        let orderLine = order.lines.length > 0 ? order.lines[0] : null;
-
-        if (!orderLine) {
-            const result = await this.orderService.addItemToOrder(ctx, sessionOrder.id, 1, 1);
-            if (isGraphQlErrorResult(result)) {
-                throw result.message;
-            } else {
-                orderLine = result.lines[result.lines.length - 1];
-            }
-        }
-
-        let cut = await this.connection.getRepository(ctx, Cut).findOne({ where: { name: 'my-cut' } });
-        if (!cut) {
-            cut = new Cut({ name: 'my-cut' });
-        }
-
-        cut.orderLine = orderLine;
-
-        let cutCode = await this.connection
-            .getRepository(ctx, CutCode)
-            .findOne({ where: { code: 'cut-code' } });
-
-        if (!cutCode) {
-            // Create dummy cutcode
-            const newCutCode = new CutCode({ code: 'cut-code' });
-            cutCode = await this.connection.getRepository(ctx, CutCode).save(newCutCode, { reload: true });
-        }
-
-        cut.code = cutCode;
-
-        // Save cut
-        cut = await this.connection.getRepository(ctx, Cut).save(cut, { reload: true });
-
-        const customFields = {
-            ...orderLine.customFields,
-            cuts: [cut],
-        };
-        orderLine.customFields = customFields;
-        // Save order line
-        const savedOrderLine = await this.connection.getRepository(ctx, OrderLine).save(orderLine);
-        await this.customFieldRelationService.updateRelations(
-            ctx,
-            OrderLine,
-            { customFields },
-            savedOrderLine,
-        );
-
-        return (await this.orderService.findOne(ctx, sessionOrder.id)) || null;
-    }
-}
-
-@VendurePlugin({
-    imports: [PluginCommonModule],
-    providers: [],
-    entities: [Cut, CutCode],
-    shopApiExtensions: {
-        resolvers: [EagerRelationsBugOrderResolver],
-        schema: commonApiExtensions,
-    },
-    adminApiExtensions: {
-        resolvers: [EagerRelationsBugOrderResolver],
-        schema: commonApiExtensions,
-    },
-    configuration: config => {
-        config.customFields.OrderLine.push(
-            {
-                name: 'cuts',
-                type: 'relation',
-                entity: Cut,
-                list: true,
-                eager: true, // ---> BUG: As soon as this relation is set to be loaded eagerly the eager relation to 'code' in the Cut entity won't be resolved anymore.
-                label: [
-                    {
-                        languageCode: LanguageCode.en,
-                        value: 'Cuts',
-                    },
-                ],
-            },
-            {
-                name: 'comment',
-                type: 'string',
-                label: [
-                    {
-                        languageCode: LanguageCode.en,
-                        value: 'Comment',
-                    },
-                ],
-            },
-        );
-        return config;
-    },
-    compatibility: '^3.0.0',
-})
-export class EagerRelationsBugPlugin {}

+ 0 - 27
packages/dev-server/file-logger.ts

@@ -1,27 +0,0 @@
-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', encoding: 'utf8' });
-    }
-
-    error(message: string, context?: string) {
-        this.logfile.write(`${new Date().toISOString()} ERROR: [${context}] ${message}\n`, 'utf8');
-    }
-    warn(message: string, context?: string) {
-        this.logfile.write(`${new Date().toISOString()} WARN: [${context}] ${message}\n`, 'utf8');
-    }
-    info(message: string, context?: string) {
-        this.logfile.write(`${new Date().toISOString()} INFO: [${context}] ${message}\n`, 'utf8');
-    }
-    verbose(message: string, context?: string) {
-        this.logfile.write(`${new Date().toISOString()} VERBOSE: [${context}] ${message}\n`, 'utf8');
-    }
-    debug(message: string, context?: string) {
-        this.logfile.write(`${new Date().toISOString()} DEBUG: [${context}] ${message}\n`, 'utf8');
-    }
-}

+ 0 - 40
packages/dev-server/get-product-count.ts

@@ -1,40 +0,0 @@
-import { bootstrapWorker, Logger, ProductService, RequestContextService } from '@vendure/core';
-
-import { devConfig } from './dev-config';
-
-if (require.main === module) {
-    getProductCount()
-        .then(() => process.exit(0))
-        .catch(err => {
-            Logger.error(err);
-            process.exit(1);
-        });
-}
-
-async function getProductCount() {
-    // This will bootstrap an instance of the Vendure Worker, providing
-    // us access to all of the services defined in the Vendure core.
-    const { app } = await bootstrapWorker(devConfig);
-
-    // Using `app.get()` we can grab an instance of _any_ provider defined in the
-    // Vendure core as well as by our plugins.
-    const productService = app.get(ProductService);
-
-    // For most service methods, we'll need to pass a RequestContext object.
-    // We can use the RequestContextService to create one.
-    const ctx = await app.get(RequestContextService).create({
-        apiType: 'admin',
-    });
-
-    // We use the `findAll()` method to get the total count. Since we aren't
-    // interested in the actual product objects, we can set the `take` option to 0.
-    const { totalItems } = await productService.findAll(ctx, { take: 0 });
-
-    Logger.info(
-        [
-            '\n-----------------------------------------',
-            `There are ${totalItems} products in the database`,
-            '-----------------------------------------',
-        ].join('\n'),
-    );
-}