content
stringlengths 28
1.34M
|
---|
/* eslint-disable @typescript-eslint/no-var-requires */
/**
* @description
* A constant which holds the current version of the Vendure core. You can use
* this when your code needs to know the version of Vendure which is running.
*
* @example
* ```ts
* import { VENDURE_VERSION } from '\@vendure/core';
*
* console.log('Vendure version:', VENDURE_VERSION);
* ```
*
* @docsCategory common
* @since 2.0.0
*/
export const VENDURE_VERSION: string = require('../package.json').version;
|
import { Module } from '@nestjs/common';
import { CacheModule } from '../cache/cache.module';
import { ConfigModule } from '../config/config.module';
import { ConnectionModule } from '../connection/connection.module';
import { DataImportModule } from '../data-import/data-import.module';
import { JobQueueModule } from '../job-queue/job-queue.module';
import { createDynamicGraphQlModulesForPlugins } from '../plugin/dynamic-plugin-api.module';
import { ServiceModule } from '../service/service.module';
import { ConfigurableOperationCodec } from './common/configurable-operation-codec';
import { CustomFieldRelationResolverService } from './common/custom-field-relation-resolver.service';
import { IdCodecService } from './common/id-codec.service';
import { AdministratorResolver } from './resolvers/admin/administrator.resolver';
import { AssetResolver } from './resolvers/admin/asset.resolver';
import { AuthResolver } from './resolvers/admin/auth.resolver';
import { ChannelResolver } from './resolvers/admin/channel.resolver';
import { CollectionResolver } from './resolvers/admin/collection.resolver';
import { CountryResolver } from './resolvers/admin/country.resolver';
import { CustomerGroupResolver } from './resolvers/admin/customer-group.resolver';
import { CustomerResolver } from './resolvers/admin/customer.resolver';
import { DraftOrderResolver } from './resolvers/admin/draft-order.resolver';
import { DuplicateEntityResolver } from './resolvers/admin/duplicate-entity.resolver';
import { FacetResolver } from './resolvers/admin/facet.resolver';
import { GlobalSettingsResolver } from './resolvers/admin/global-settings.resolver';
import { ImportResolver } from './resolvers/admin/import.resolver';
import { JobResolver } from './resolvers/admin/job.resolver';
import { OrderResolver } from './resolvers/admin/order.resolver';
import { PaymentMethodResolver } from './resolvers/admin/payment-method.resolver';
import { ProductOptionResolver } from './resolvers/admin/product-option.resolver';
import { ProductResolver } from './resolvers/admin/product.resolver';
import { PromotionResolver } from './resolvers/admin/promotion.resolver';
import { RoleResolver } from './resolvers/admin/role.resolver';
import { SearchResolver } from './resolvers/admin/search.resolver';
import { SellerResolver } from './resolvers/admin/seller.resolver';
import { ShippingMethodResolver } from './resolvers/admin/shipping-method.resolver';
import { StockLocationResolver } from './resolvers/admin/stock-location.resolver';
import { TagResolver } from './resolvers/admin/tag.resolver';
import { TaxCategoryResolver } from './resolvers/admin/tax-category.resolver';
import { TaxRateResolver } from './resolvers/admin/tax-rate.resolver';
import { ZoneResolver } from './resolvers/admin/zone.resolver';
import { AdministratorEntityResolver } from './resolvers/entity/administrator-entity.resolver';
import { AssetEntityResolver } from './resolvers/entity/asset-entity.resolver';
import { ChannelEntityResolver } from './resolvers/entity/channel-entity.resolver';
import { CollectionEntityResolver } from './resolvers/entity/collection-entity.resolver';
import { CountryEntityResolver } from './resolvers/entity/country-entity.resolver';
import {
CustomerAdminEntityResolver,
CustomerEntityResolver,
} from './resolvers/entity/customer-entity.resolver';
import { CustomerGroupEntityResolver } from './resolvers/entity/customer-group-entity.resolver';
import { FacetEntityResolver } from './resolvers/entity/facet-entity.resolver';
import { FacetValueEntityResolver } from './resolvers/entity/facet-value-entity.resolver';
import {
FulfillmentAdminEntityResolver,
FulfillmentEntityResolver,
} from './resolvers/entity/fulfillment-entity.resolver';
import { FulfillmentLineEntityResolver } from './resolvers/entity/fulfillment-line-entity.resolver';
import { JobEntityResolver } from './resolvers/entity/job-entity.resolver';
import { OrderAdminEntityResolver, OrderEntityResolver } from './resolvers/entity/order-entity.resolver';
import { OrderLineEntityResolver } from './resolvers/entity/order-line-entity.resolver';
import {
PaymentAdminEntityResolver,
PaymentEntityResolver,
} from './resolvers/entity/payment-entity.resolver';
import { PaymentMethodEntityResolver } from './resolvers/entity/payment-method-entity.resolver';
import {
ProductAdminEntityResolver,
ProductEntityResolver,
} from './resolvers/entity/product-entity.resolver';
import { ProductOptionEntityResolver } from './resolvers/entity/product-option-entity.resolver';
import { ProductOptionGroupEntityResolver } from './resolvers/entity/product-option-group-entity.resolver';
import {
ProductVariantAdminEntityResolver,
ProductVariantEntityResolver,
} from './resolvers/entity/product-variant-entity.resolver';
import { RefundEntityResolver } from './resolvers/entity/refund-entity.resolver';
import { RefundLineEntityResolver } from './resolvers/entity/refund-line-entity.resolver';
import { RoleEntityResolver } from './resolvers/entity/role-entity.resolver';
import { ShippingLineEntityResolver } from './resolvers/entity/shipping-line-entity.resolver';
import { ShippingMethodEntityResolver } from './resolvers/entity/shipping-method-entity.resolver';
import { TaxRateEntityResolver } from './resolvers/entity/tax-rate-entity.resolver';
import { UserEntityResolver } from './resolvers/entity/user-entity.resolver';
import { ZoneEntityResolver } from './resolvers/entity/zone-entity.resolver';
import { ShopAuthResolver } from './resolvers/shop/shop-auth.resolver';
import { ShopCustomerResolver } from './resolvers/shop/shop-customer.resolver';
import { ShopEnvironmentResolver } from './resolvers/shop/shop-environment.resolver';
import { ShopOrderResolver } from './resolvers/shop/shop-order.resolver';
import { ShopProductsResolver } from './resolvers/shop/shop-products.resolver';
const adminResolvers = [
AdministratorResolver,
AssetResolver,
AuthResolver,
ChannelResolver,
CollectionResolver,
CountryResolver,
CustomerGroupResolver,
CustomerResolver,
DraftOrderResolver,
DuplicateEntityResolver,
FacetResolver,
GlobalSettingsResolver,
ImportResolver,
JobResolver,
OrderResolver,
PaymentMethodResolver,
ProductOptionResolver,
ProductResolver,
PromotionResolver,
RoleResolver,
SearchResolver,
ShippingMethodResolver,
StockLocationResolver,
TagResolver,
TaxCategoryResolver,
TaxRateResolver,
SellerResolver,
ZoneResolver,
];
const shopResolvers = [
ShopAuthResolver,
ShopCustomerResolver,
ShopOrderResolver,
ShopProductsResolver,
ShopEnvironmentResolver,
];
export const entityResolvers = [
AssetEntityResolver,
ChannelEntityResolver,
CollectionEntityResolver,
CountryEntityResolver,
CustomerEntityResolver,
CustomerGroupEntityResolver,
FacetEntityResolver,
FacetValueEntityResolver,
FulfillmentEntityResolver,
FulfillmentLineEntityResolver,
OrderEntityResolver,
OrderLineEntityResolver,
PaymentEntityResolver,
ProductEntityResolver,
ProductOptionEntityResolver,
ProductOptionGroupEntityResolver,
ProductVariantEntityResolver,
RefundEntityResolver,
RefundLineEntityResolver,
RoleEntityResolver,
ShippingLineEntityResolver,
UserEntityResolver,
TaxRateEntityResolver,
ShippingMethodEntityResolver,
ZoneEntityResolver,
];
export const adminEntityResolvers = [
AdministratorEntityResolver,
CustomerAdminEntityResolver,
OrderAdminEntityResolver,
PaymentMethodEntityResolver,
FulfillmentAdminEntityResolver,
PaymentAdminEntityResolver,
ProductVariantAdminEntityResolver,
ProductAdminEntityResolver,
JobEntityResolver,
];
/**
* The internal module containing some shared providers used by more than
* one API module.
*/
@Module({
imports: [ConfigModule, ServiceModule, CacheModule, ConnectionModule.forRoot()],
providers: [IdCodecService, ConfigurableOperationCodec, CustomFieldRelationResolverService],
exports: [
IdCodecService,
CacheModule,
ConfigModule,
ConfigurableOperationCodec,
CustomFieldRelationResolverService,
ServiceModule,
ConnectionModule.forRoot(),
],
})
export class ApiSharedModule {}
/**
* The internal module containing the Admin GraphQL API resolvers
*/
@Module({
imports: [
ApiSharedModule,
JobQueueModule,
DataImportModule,
...createDynamicGraphQlModulesForPlugins('admin'),
],
providers: [...adminResolvers, ...entityResolvers, ...adminEntityResolvers],
exports: [...adminResolvers],
})
export class AdminApiModule {}
/**
* The internal module containing the Shop GraphQL API resolvers
*/
@Module({
imports: [ApiSharedModule, ...createDynamicGraphQlModulesForPlugins('shop')],
providers: [...shopResolvers, ...entityResolvers],
exports: [...shopResolvers],
})
export class ShopApiModule {}
|
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import path from 'path';
import { ConfigService } from '../config/config.service';
import { ConnectionModule } from '../connection/connection.module';
import { DataImportModule } from '../data-import/data-import.module';
import { I18nModule } from '../i18n/i18n.module';
import { ServiceModule } from '../service/service.module';
import { AdminApiModule, ApiSharedModule, ShopApiModule } from './api-internal-modules';
import { configureGraphQLModule } from './config/configure-graphql-module';
import { AuthGuard } from './middleware/auth-guard';
import { ExceptionLoggerFilter } from './middleware/exception-logger.filter';
import { IdInterceptor } from './middleware/id-interceptor';
import { TranslateErrorResultInterceptor } from './middleware/translate-error-result-interceptor';
import { ValidateCustomFieldsInterceptor } from './middleware/validate-custom-fields-interceptor';
/**
* The ApiModule is responsible for the public API of the application. This is where requests
* come in, are parsed and then handed over to the ServiceModule classes which take care
* of the business logic.
*/
@Module({
imports: [
ServiceModule,
ConnectionModule.forRoot(),
DataImportModule,
I18nModule,
ApiSharedModule,
AdminApiModule,
ShopApiModule,
configureGraphQLModule(configService => ({
apiType: 'shop',
apiPath: configService.apiOptions.shopApiPath,
playground: configService.apiOptions.shopApiPlayground,
debug: configService.apiOptions.shopApiDebug,
typePaths: ['shop-api', 'common'].map(p => path.join(__dirname, 'schema', p, '*.graphql')),
resolverModule: ShopApiModule,
validationRules: configService.apiOptions.shopApiValidationRules,
})),
configureGraphQLModule(configService => ({
apiType: 'admin',
apiPath: configService.apiOptions.adminApiPath,
playground: configService.apiOptions.adminApiPlayground,
debug: configService.apiOptions.adminApiDebug,
typePaths: ['admin-api', 'common'].map(p => path.join(__dirname, 'schema', p, '*.graphql')),
resolverModule: AdminApiModule,
validationRules: configService.apiOptions.adminApiValidationRules,
})),
],
providers: [
{
provide: APP_GUARD,
useClass: AuthGuard,
},
{
provide: APP_INTERCEPTOR,
useClass: IdInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: ValidateCustomFieldsInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: TranslateErrorResultInterceptor,
},
{
provide: APP_FILTER,
useClass: ExceptionLoggerFilter,
},
],
})
export class ApiModule implements NestModule {
constructor(private configService: ConfigService) {}
async configure(consumer: MiddlewareConsumer) {
const { adminApiPath, shopApiPath } = this.configService.apiOptions;
const { uploadMaxFileSize } = this.configService.assetOptions;
// @ts-ignore
const { default: graphqlUploadExpress } = await import('graphql-upload/graphqlUploadExpress.mjs');
consumer
.apply(graphqlUploadExpress({ maxFileSize: uploadMaxFileSize }))
.forRoutes(adminApiPath, shopApiPath);
}
}
|
export { ApiType } from './common/get-api-type';
export * from './common/request-context';
export * from './common/extract-session-token';
export * from './decorators/allow.decorator';
export * from './decorators/transaction.decorator';
export * from './decorators/api.decorator';
export * from './decorators/relations.decorator';
export * from './decorators/request-context.decorator';
export * from './resolvers/admin/search.resolver';
export * from './middleware/auth-guard';
export * from './middleware/exception-logger.filter';
export * from './middleware/id-interceptor';
|
import { Injectable } from '@nestjs/common';
import { ConfigurableOperation, ConfigurableOperationInput } from '@vendure/common/lib/generated-types';
import { Type } from '@vendure/common/lib/shared-types';
import { ConfigurableOperationDef } from '../../common/configurable-operation';
import { InternalServerError } from '../../common/error/errors';
import {
PromotionCondition,
PromotionItemAction,
PromotionOrderAction,
ShippingCalculator,
ShippingEligibilityChecker,
} from '../../config';
import { CollectionFilter } from '../../config/catalog/collection-filter';
import { ConfigService } from '../../config/config.service';
import { PaymentMethodEligibilityChecker } from '../../config/payment/payment-method-eligibility-checker';
import { PaymentMethodHandler } from '../../config/payment/payment-method-handler';
import { IdCodecService } from './id-codec.service';
@Injectable()
export class ConfigurableOperationCodec {
constructor(private configService: ConfigService, private idCodecService: IdCodecService) {}
/**
* Decodes any ID type arguments of a ConfigurableOperationDef
*/
decodeConfigurableOperationIds<T extends ConfigurableOperationDef<any>>(
defType: Type<ConfigurableOperationDef<any>>,
input: ConfigurableOperationInput[],
): ConfigurableOperationInput[] {
const availableDefs = this.getAvailableDefsOfType(defType);
for (const operationInput of input) {
const def = availableDefs.find(d => d.code === operationInput.code);
if (!def) {
continue;
}
for (const arg of operationInput.arguments) {
const argDef = def.args[arg.name];
if (argDef && argDef.type === 'ID' && arg.value) {
if (argDef.list === true) {
const ids = JSON.parse(arg.value) as string[];
const decodedIds = ids.map(id => this.idCodecService.decode(id));
arg.value = JSON.stringify(decodedIds);
} else {
arg.value = this.idCodecService.decode(arg.value);
}
}
}
}
return input;
}
/**
* Encodes any ID type arguments of a ConfigurableOperationDef
*/
encodeConfigurableOperationIds<T extends ConfigurableOperationDef<any>>(
defType: Type<ConfigurableOperationDef<any>>,
input: ConfigurableOperation[],
): ConfigurableOperation[] {
const availableDefs = this.getAvailableDefsOfType(defType);
for (const operationInput of input) {
const def = availableDefs.find(d => d.code === operationInput.code);
if (!def) {
continue;
}
for (const arg of operationInput.args) {
const argDef = def.args[arg.name];
if (argDef && argDef.type === 'ID' && arg.value) {
if (argDef.list === true) {
const ids = JSON.parse(arg.value) as string[];
const encodedIds = ids.map(id => this.idCodecService.encode(id));
arg.value = JSON.stringify(encodedIds);
} else {
const encodedId = this.idCodecService.encode(arg.value);
arg.value = JSON.stringify(encodedId);
}
}
}
}
return input;
}
getAvailableDefsOfType(defType: Type<ConfigurableOperationDef>): ConfigurableOperationDef[] {
switch (defType) {
case CollectionFilter:
return this.configService.catalogOptions.collectionFilters;
case PaymentMethodHandler:
return this.configService.paymentOptions.paymentMethodHandlers;
case PaymentMethodEligibilityChecker:
return this.configService.paymentOptions.paymentMethodEligibilityCheckers || [];
case PromotionItemAction:
case PromotionOrderAction:
return this.configService.promotionOptions.promotionActions || [];
case PromotionCondition:
return this.configService.promotionOptions.promotionConditions || [];
case ShippingEligibilityChecker:
return this.configService.shippingOptions.shippingEligibilityCheckers || [];
case ShippingCalculator:
return this.configService.shippingOptions.shippingCalculators || [];
default:
throw new InternalServerError('error.unknown-configurable-operation-definition', {
name: defType.name,
});
}
}
}
|
import { Injectable } from '@nestjs/common';
import { ID } from '@vendure/common/lib/shared-types';
import { FindOptionsUtils } from 'typeorm/find-options/FindOptionsUtils';
import { Translatable } from '../../common/types/locale-types';
import { ConfigService } from '../../config/config.service';
import { RelationCustomFieldConfig } from '../../config/custom-field/custom-field-types';
import { TransactionalConnection } from '../../connection/transactional-connection';
import { VendureEntity } from '../../entity/base/base.entity';
import { ProductVariant } from '../../entity/product-variant/product-variant.entity';
import { ProductPriceApplicator } from '../../service/helpers/product-price-applicator/product-price-applicator';
import { TranslatorService } from '../../service/helpers/translator/translator.service';
import { RequestContext } from './request-context';
export interface ResolveRelationConfig {
ctx: RequestContext;
entityId: ID;
entityName: string;
fieldDef: RelationCustomFieldConfig;
}
@Injectable()
export class CustomFieldRelationResolverService {
constructor(
private connection: TransactionalConnection,
private configService: ConfigService,
private productPriceApplicator: ProductPriceApplicator,
private translator: TranslatorService,
) {}
/**
* @description
* Used to dynamically resolve related entities in custom fields. Based on the field
* config, this method is able to query the correct entity or entities from the database
* to be returned through the GraphQL API.
*/
async resolveRelation(config: ResolveRelationConfig): Promise<VendureEntity | VendureEntity[]> {
const { ctx, entityId, entityName, fieldDef } = config;
const subQb = this.connection
.getRepository(ctx, entityName)
.createQueryBuilder('entity')
.leftJoin(`entity.customFields.${fieldDef.name}`, 'relationEntity')
.select('relationEntity.id')
.where('entity.id = :id');
const qb = this.connection
.getRepository(ctx, fieldDef.entity)
.createQueryBuilder('relation')
.where(`relation.id IN (${subQb.getQuery()})`)
.setParameters({ id: entityId });
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
FindOptionsUtils.joinEagerRelations(qb, qb.alias, qb.expressionMap.mainAlias!.metadata);
const result = fieldDef.list ? await qb.getMany() : await qb.getOne();
return await this.translateEntity(ctx, result, fieldDef);
}
async translateEntity(
ctx: RequestContext,
result: VendureEntity | VendureEntity[] | null,
fieldDef: RelationCustomFieldConfig,
) {
if (result == null) return null;
if (fieldDef.entity === ProductVariant) {
if (Array.isArray(result)) {
await Promise.all(result.map(r => this.applyVariantPrices(ctx, r as any)));
} else {
await this.applyVariantPrices(ctx, result as any);
}
}
const translated: any = Array.isArray(result)
? result.map(r => (this.isTranslatable(r) ? this.translator.translate(r, ctx) : r))
: this.isTranslatable(result)
? this.translator.translate(result, ctx)
: result;
return translated;
}
private isTranslatable(input: unknown): input is Translatable {
return typeof input === 'object' && input != null && input.hasOwnProperty('translations');
}
private async applyVariantPrices(ctx: RequestContext, variant: ProductVariant): Promise<ProductVariant> {
const taxCategory = await this.connection
.getRepository(ctx, ProductVariant)
.createQueryBuilder()
.relation('taxCategory')
.of(variant)
.loadOne();
variant.taxCategory = taxCategory;
return this.productPriceApplicator.applyChannelPriceAndTax(variant, ctx);
}
}
|
import { Request } from 'express';
import { AuthOptions } from '../../config/vendure-config';
/**
* Get the session token from either the cookie or the Authorization header, depending
* on the configured tokenMethod.
*/
export function extractSessionToken(
req: Request,
tokenMethod: Exclude<AuthOptions['tokenMethod'], undefined>,
): string | undefined {
const tokenFromCookie = getFromCookie(req);
const tokenFromHeader = getFromHeader(req);
if (tokenMethod === 'cookie') {
return tokenFromCookie;
} else if (tokenMethod === 'bearer') {
return tokenFromHeader;
}
if (tokenMethod.includes('cookie') && tokenFromCookie) {
return tokenFromCookie;
}
if (tokenMethod.includes('bearer') && tokenFromHeader) {
return tokenFromHeader;
}
}
function getFromCookie(req: Request): string | undefined {
if (req.session && req.session.token) {
return req.session.token;
}
}
function getFromHeader(req: Request): string | undefined {
const authHeader = req.get('Authorization');
if (authHeader) {
const matches = authHeader.trim().match(/^bearer\s(.+)$/i);
if (matches) {
return matches[1];
}
}
}
|
import { GraphQLResolveInfo } from 'graphql';
/**
* @description
* Which of the GraphQL APIs the current request came via.
*
* @docsCategory request
*/
export type ApiType = 'admin' | 'shop' | 'custom';
/**
* Inspects the GraphQL "info" resolver argument to determine which API
* the request came through.
*/
export function getApiType(info?: GraphQLResolveInfo): ApiType {
const query = info && info.schema.getQueryType();
if (query) {
return !!query.getFields().administrators ? 'admin' : 'shop';
}
return 'custom';
}
|
import {
ASTVisitor,
DocumentNode,
getNamedType,
GraphQLInputObjectType,
GraphQLNamedType,
GraphQLSchema,
isInputObjectType,
isListType,
isNonNullType,
OperationDefinitionNode,
TypeInfo,
visit,
visitWithTypeInfo,
} from 'graphql';
export type TypeTree = {
operation: TypeTreeNode;
fragments: { [name: string]: TypeTreeNode };
};
/**
* Represents a GraphQLNamedType which pertains to an input variables object or an output.
* Used when traversing the data object in order to provide the type for the field
* being visited.
*/
export type TypeTreeNode = {
type: GraphQLNamedType | undefined;
parent: TypeTreeNode | TypeTree;
isList: boolean;
fragmentRefs: string[];
children: { [name: string]: TypeTreeNode };
};
/**
* This class is used to transform the values of input variables or an output object.
*/
export class GraphqlValueTransformer {
private outputCache = new WeakMap<DocumentNode, TypeTree>();
private inputCache = new WeakMap<OperationDefinitionNode, TypeTree>();
constructor(private schema: GraphQLSchema) {}
/**
* Transforms the values in the `data` object into the return value of the `visitorFn`.
*/
transformValues(
typeTree: TypeTree,
data: Record<string, unknown>,
visitorFn: (value: any, type: GraphQLNamedType) => any,
) {
this.traverse(data, (key, value, path) => {
const typeTreeNode = this.getTypeNodeByPath(typeTree, path);
const type = (typeTreeNode && typeTreeNode.type) as GraphQLNamedType;
return visitorFn(value, type);
});
}
/**
* Constructs a tree of TypeTreeNodes for the output of a GraphQL operation.
*/
getOutputTypeTree(document: DocumentNode): TypeTree {
const cached = this.outputCache.get(document);
if (cached) {
return cached;
}
const typeInfo = new TypeInfo(this.schema);
const typeTree: TypeTree = {
operation: {} as any,
fragments: {},
};
const rootNode: TypeTreeNode = {
type: undefined,
isList: false,
parent: typeTree,
fragmentRefs: [],
children: {},
};
typeTree.operation = rootNode;
let currentNode = rootNode;
const visitor: ASTVisitor = {
enter: node => {
const type = typeInfo.getType();
const fieldDef = typeInfo.getFieldDef();
if (node.kind === 'Field') {
const newNode: TypeTreeNode = {
type: (type && getNamedType(type)) || undefined,
isList: this.isList(type),
fragmentRefs: [],
parent: currentNode,
children: {},
};
currentNode.children[node.alias?.value ?? node.name.value] = newNode;
currentNode = newNode;
}
if (node.kind === 'FragmentSpread') {
currentNode.fragmentRefs.push(node.name.value);
}
if (node.kind === 'FragmentDefinition') {
const rootFragmentNode: TypeTreeNode = {
type: undefined,
isList: false,
fragmentRefs: [],
parent: typeTree,
children: {},
};
currentNode = rootFragmentNode;
typeTree.fragments[node.name.value] = rootFragmentNode;
}
},
leave: node => {
if (node.kind === 'Field') {
if (!this.isTypeTree(currentNode.parent)) {
currentNode = currentNode.parent;
}
}
if (node.kind === 'FragmentDefinition') {
currentNode = rootNode;
}
},
};
for (const operation of document.definitions) {
visit(operation, visitWithTypeInfo(typeInfo, visitor));
}
this.outputCache.set(document, typeTree);
return typeTree;
}
/**
* Constructs a tree of TypeTreeNodes for the input variables of a GraphQL operation.
*/
getInputTypeTree(definition: OperationDefinitionNode): TypeTree {
const cached = this.inputCache.get(definition);
if (cached) {
return cached;
}
const typeInfo = new TypeInfo(this.schema);
const typeTree: TypeTree = {
operation: {} as any,
fragments: {},
};
const rootNode: TypeTreeNode = {
type: undefined,
isList: false,
parent: typeTree,
fragmentRefs: [],
children: {},
};
typeTree.operation = rootNode;
let currentNode = rootNode;
const visitor: ASTVisitor = {
enter: node => {
if (node.kind === 'Argument') {
const type = typeInfo.getType();
const args = typeInfo.getArgument();
if (args) {
const inputType = getNamedType(args.type);
const newNode: TypeTreeNode = {
type: inputType || undefined,
isList: this.isList(type),
parent: currentNode,
fragmentRefs: [],
children: {},
};
currentNode.children[args.name] = newNode;
if (isInputObjectType(inputType)) {
if (isInputObjectType(inputType)) {
newNode.children = this.getChildrenTreeNodes(inputType, newNode);
}
}
currentNode = newNode;
}
}
},
leave: node => {
if (node.kind === 'Argument') {
if (!this.isTypeTree(currentNode.parent)) {
currentNode = currentNode.parent;
}
}
},
};
visit(definition, visitWithTypeInfo(typeInfo, visitor));
this.inputCache.set(definition, typeTree);
return typeTree;
}
private getChildrenTreeNodes(
inputType: GraphQLInputObjectType,
parent: TypeTreeNode,
): { [name: string]: TypeTreeNode } {
return Object.entries(inputType.getFields()).reduce((result, [key, field]) => {
const namedType = getNamedType(field.type);
if (namedType === parent.type) {
// prevent recursion-induced stack overflow
return result;
}
const child: TypeTreeNode = {
type: namedType,
isList: this.isList(field.type),
parent,
fragmentRefs: [],
children: {},
};
if (isInputObjectType(namedType)) {
child.children = this.getChildrenTreeNodes(namedType, child);
}
return { ...result, [key]: child };
}, {} as { [name: string]: TypeTreeNode });
}
private isList(t: any): boolean {
return isListType(t) || (isNonNullType(t) && isListType(t.ofType));
}
private getTypeNodeByPath(typeTree: TypeTree, path: Array<string | number>): TypeTreeNode | undefined {
let targetNode: TypeTreeNode | undefined = typeTree.operation;
for (const segment of path) {
if (Number.isNaN(Number.parseInt(segment as string, 10))) {
if (targetNode) {
let children: { [name: string]: TypeTreeNode } = targetNode.children;
if (targetNode.fragmentRefs.length) {
const fragmentRefs = targetNode.fragmentRefs.slice();
while (fragmentRefs.length) {
const ref = fragmentRefs.pop();
if (ref) {
const fragment = typeTree.fragments[ref];
children = { ...children, ...fragment.children };
if (fragment.fragmentRefs) {
fragmentRefs.push(...fragment.fragmentRefs);
}
}
}
}
targetNode = children[segment];
}
}
}
return targetNode;
}
private traverse(
o: { [key: string]: any },
visitorFn: (key: string, value: any, path: Array<string | number>) => any,
path: Array<string | number> = [],
) {
for (const key of Object.keys(o)) {
path.push(key);
o[key] = visitorFn(key, o[key], path);
if (o[key] !== null && typeof o[key] === 'object') {
this.traverse(o[key], visitorFn, path);
}
path.pop();
}
}
private isTypeTree(input: TypeTree | TypeTreeNode): input is TypeTree {
return input.hasOwnProperty('fragments');
}
}
|
import { Injectable } from '@nestjs/common';
import { ConfigService } from '../../config/config.service';
import { IdCodec } from './id-codec';
@Injectable()
export class IdCodecService {
private idCodec: IdCodec;
constructor(configService: ConfigService) {
this.idCodec = new IdCodec(
configService.entityOptions.entityIdStrategy ?? configService.entityIdStrategy,
);
}
encode<T extends string | number | boolean | object | undefined>(target: T, transformKeys?: string[]): T {
return this.idCodec.encode(target, transformKeys);
}
decode<T extends string | number | object | undefined>(target: T, transformKeys?: string[]): T {
return this.idCodec.decode(target, transformKeys);
}
}
|
import { beforeEach, describe, expect, it } from 'vitest';
import { DECODED, ENCODED, MockIdStrategy } from '../../config/config.service.mock';
import { IdCodec } from './id-codec';
describe('IdCodecService', () => {
let idCodec: IdCodec;
beforeEach(async () => {
idCodec = new IdCodec(new MockIdStrategy());
});
describe('encode()', () => {
it('works with a string', () => {
const input = 'id';
const result = idCodec.encode(input);
expect(result).toEqual(ENCODED);
});
it('works with a number', () => {
const input = 123;
const result = idCodec.encode(input);
expect(result).toEqual(ENCODED);
});
it('works with a boolean', () => {
const input = true;
const result = idCodec.encode(input);
expect(result).toEqual(true);
});
it('passes through null or undefined without throwing', () => {
expect(idCodec.encode(null as any)).toBeNull();
expect(idCodec.encode(undefined as any)).toBeUndefined();
});
it('returns a clone of the input object', () => {
const input = { id: 'id', name: 'foo' };
const result = idCodec.encode(input);
expect(result).not.toBe(input);
});
it('returns a deep clone', () => {
const obj1 = { 1: true };
const obj2 = { 2: true };
const arr = [obj1, obj2];
const parent = { myArray: arr };
const input = { foo: parent };
const result = idCodec.encode(input);
expect(result).not.toBe(input);
expect(result.foo).not.toBe(parent);
expect(result.foo.myArray).not.toBe(arr);
expect(result.foo.myArray[0]).not.toBe(obj1);
expect(result.foo.myArray[1]).not.toBe(obj2);
});
it('does not clone complex object instances', () => {
/* eslint-disable @typescript-eslint/no-floating-promises */
const promise = new Promise(() => {
/**/
});
const date = new Date();
const regex = new RegExp('');
const input = {
promise,
date,
regex,
};
const result = idCodec.encode(input);
expect(result.promise).toBe(promise);
expect(result.date).toBe(date);
expect(result.regex).toBe(regex);
/* eslint-enable @typescript-eslint/no-floating-promises */
});
it('works with simple entity', () => {
const input = { id: 'id', name: 'foo' };
const result = idCodec.encode(input);
expect(result).toEqual({ id: ENCODED, name: 'foo' });
});
it('works with 2-level nested entities', () => {
const input = {
id: 'id',
friend: { id: 'id' },
};
const result = idCodec.encode(input);
expect(result).toEqual({
id: ENCODED,
friend: { id: ENCODED },
});
});
it('works with 3-level nested entities', () => {
const input = {
id: 'id',
friend: {
dog: { id: 'id' },
},
};
const result = idCodec.encode(input);
expect(result).toEqual({
id: ENCODED,
friend: {
dog: { id: ENCODED },
},
});
});
it('works with list of simple entities', () => {
const input = [
{ id: 'id', name: 'foo' },
{ id: 'id', name: 'bar' },
];
const result = idCodec.encode(input);
expect(result).toEqual([
{ id: ENCODED, name: 'foo' },
{ id: ENCODED, name: 'bar' },
]);
});
it('does not throw with an empty list', () => {
const input: any[] = [];
const result = idCodec.encode(input);
expect(() => idCodec.encode(input)).not.toThrow();
});
it('works with nested list of simple entities', () => {
const input = {
items: [
{ id: 'id', name: 'foo' },
{ id: 'id', name: 'bar' },
],
};
const result = idCodec.encode(input);
expect(result).toEqual({
items: [
{ id: ENCODED, name: 'foo' },
{ id: ENCODED, name: 'bar' },
],
});
});
it('works with large and nested list', () => {
const length = 100;
const input = {
items: Array.from({ length }).map(() => ({
id: 'id',
name: { bar: 'baz' },
foo: 'yo',
friends: [{ id: 'id', name: { first: 'boris', id: 'id' } }],
})),
};
const result = idCodec.encode(input);
expect(result.items.length).toBe(length);
expect(result.items[0].id).toBe(ENCODED);
expect(result.items[0].friends[0].id).toBe(ENCODED);
expect(result.items[0].friends[0].name.id).toBe(ENCODED);
});
it('works with lists with a nullable object property', () => {
const input = {
items: [{ user: null }, { user: { id: 'id' } }],
};
const result = idCodec.encode(input);
expect(result.items[0].user).toBe(null);
expect(result.items[1].user).toEqual({ id: ENCODED });
});
it('works with nested list of nested lists', () => {
const input = {
items: [
{
id: 'id',
friends: [{ id: 'id' }, { id: 'id' }],
},
{
id: 'id',
friends: [{ id: 'id' }, { id: 'id' }],
},
],
};
const result = idCodec.encode(input);
expect(result).toEqual({
items: [
{
id: ENCODED,
friends: [{ id: ENCODED }, { id: ENCODED }],
},
{
id: ENCODED,
friends: [{ id: ENCODED }, { id: ENCODED }],
},
],
});
});
it('transformKeys can be customized', () => {
const input = { id: 'id', name: 'foo' };
const result = idCodec.encode(input, ['name']);
expect(result).toEqual({ id: ENCODED, name: ENCODED });
});
});
describe('decode()', () => {
it('works with a string', () => {
const input = 'id';
const result = idCodec.decode(input);
expect(result).toEqual(DECODED);
});
it('works with a number', () => {
const input = 123;
const result = idCodec.decode(input);
expect(result).toEqual(DECODED);
});
it('works with simple entity', () => {
const input = { id: 'id', name: 'foo' };
const result = idCodec.decode(input);
expect(result).toEqual({ id: DECODED, name: 'foo' });
});
it('works with 2-level nested entities', () => {
const input = {
id: 'id',
friend: { id: 'id' },
};
const result = idCodec.decode(input);
expect(result).toEqual({
id: DECODED,
friend: { id: DECODED },
});
});
it('works with 3-level nested entities', () => {
const input = {
id: 'id',
friend: {
dog: { id: 'id' },
},
};
const result = idCodec.decode(input);
expect(result).toEqual({
id: DECODED,
friend: {
dog: { id: DECODED },
},
});
});
it('works with list of simple entities', () => {
const input = [
{ id: 'id', name: 'foo' },
{ id: 'id', name: 'bar' },
];
const result = idCodec.decode(input);
expect(result).toEqual([
{ id: DECODED, name: 'foo' },
{ id: DECODED, name: 'bar' },
]);
});
it('works with nested list of simple entities', () => {
const input = {
items: [
{ id: 'id', name: 'foo' },
{ id: 'id', name: 'bar' },
],
};
const result = idCodec.decode(input);
expect(result).toEqual({
items: [
{ id: DECODED, name: 'foo' },
{ id: DECODED, name: 'bar' },
],
});
});
it('works with lists with a nullable object property', () => {
const input = {
items: [{ user: null }, { user: { id: 'id' } }],
};
const result = idCodec.decode(input);
expect(result.items[0].user).toBe(null);
expect(result.items[1].user).toEqual({ id: DECODED });
});
it('works with large and nested list', () => {
const length = 100;
const input = {
items: Array.from({ length }).map(() => ({
id: 'id',
name: { bar: 'baz' },
foo: 'yo',
friends: [{ id: 'id', name: { first: 'boris', id: 'id' } }],
})),
};
const result = idCodec.decode(input);
expect(result.items.length).toBe(length);
expect(result.items[0].id).toBe(DECODED);
expect(result.items[0].friends[0].id).toBe(DECODED);
expect(result.items[0].friends[0].name.id).toBe(DECODED);
});
it('works with nested list of nested lists', () => {
const input = {
items: [
{
id: 'id',
friends: [{ id: 'id' }, { id: 'id' }],
},
{
id: 'id',
friends: [{ id: 'id' }, { id: 'id' }],
},
],
};
const result = idCodec.decode(input);
expect(result).toEqual({
items: [
{
id: DECODED,
friends: [{ id: DECODED }, { id: DECODED }],
},
{
id: DECODED,
friends: [{ id: DECODED }, { id: DECODED }],
},
],
});
});
it('transformKeys can be customized', () => {
const input = { name: 'foo' };
const result = idCodec.decode(input, ['name']);
expect(result).toEqual({ name: DECODED });
});
it('id keys is still implicitly decoded when transformKeys are defined', () => {
const input = { id: 'id', name: 'foo' };
const result = idCodec.decode(input, ['name']);
expect(result).toEqual({ id: DECODED, name: DECODED });
});
it('transformKeys works for nested matching keys', () => {
const input = {
input: {
id: 'id',
featuredAssetId: 'id',
foo: 'bar',
},
};
const result = idCodec.decode(input, ['featuredAssetId']);
expect(result).toEqual({
input: {
id: DECODED,
featuredAssetId: DECODED,
foo: 'bar',
},
});
});
it('transformKeys works for nested matching key array', () => {
const input = {
input: {
id: 'id',
assetIds: ['id1', 'id2', 'id3'],
foo: 'bar',
},
};
const result = idCodec.decode(input, ['assetIds']);
expect(result).toEqual({
input: {
id: DECODED,
assetIds: [DECODED, DECODED, DECODED],
foo: 'bar',
},
});
});
it('transformKeys works for multiple nested keys', () => {
const input = {
input: {
id: 'id',
featuredAssetId: 'id',
assetIds: ['id1', 'id2', 'id3'],
foo: 'bar',
},
};
const result = idCodec.decode(input, ['featuredAssetId', 'assetIds']);
expect(result).toEqual({
input: {
id: DECODED,
featuredAssetId: DECODED,
assetIds: [DECODED, DECODED, DECODED],
foo: 'bar',
},
});
});
// https://github.com/vendure-ecommerce/vendure/issues/1596
it('works with heterogeneous array', () => {
const input1 = { value: [null, 'foo'] };
const input2 = { value: [false, 'foo'] };
const input3 = { value: [{}, 'foo'] };
const input4 = { value: [[], 'foo'] };
const input5 = { value: [0, 'foo'] };
const result1 = idCodec.decode(input1);
const result2 = idCodec.decode(input2);
const result3 = idCodec.decode(input3);
const result4 = idCodec.decode(input4);
const result5 = idCodec.decode(input5);
expect(result1).toEqual(input1);
expect(result2).toEqual(input2);
expect(result3).toEqual(input3);
expect(result4).toEqual(input4);
expect(result5).toEqual(input5);
});
});
});
|
import { ID } from '@vendure/common/lib/shared-types';
import { isObject } from '@vendure/common/lib/shared-utils';
import { EntityIdStrategy } from '../../config/entity/entity-id-strategy';
import { VendureEntity } from '../../entity/base/base.entity';
const ID_KEYS = ['id'];
/**
* This service is responsible for encoding/decoding entity IDs according to the configured EntityIdStrategy.
* It should only need to be used in resolvers - the design is that once a request hits the business logic layer
* (ProductService etc) all entity IDs are in the form used as the primary key in the database.
*/
export class IdCodec {
constructor(private entityIdStrategy: EntityIdStrategy<any>) {}
/**
* Decode an id from the client into the format used as the database primary key.
* Acts recursively on all objects containing an "id" property.
*
* @param target - The object to be decoded
* @param transformKeys - An optional array of keys of the target to be decoded. If not defined,
* then the default recursive behaviour will be used.
* @return A decoded clone of the target
*/
decode<T extends string | number | object | undefined>(target: T, transformKeys?: string[]): T {
const transformKeysWithId = [...(transformKeys || []), ...ID_KEYS];
return this.transformRecursive(
target,
input => this.entityIdStrategy.decodeId(input),
transformKeysWithId,
);
}
/**
* Encode any entity ids according to the encode.
* Acts recursively on all objects containing an "id" property.
*
* @param target - The object to be encoded
* @param transformKeys - An optional array of keys of the target to be encoded. If not defined,
* then the default recursive behaviour will be used.
* @return An encoded clone of the target
*/
encode<T extends string | number | boolean | object | undefined>(target: T, transformKeys?: string[]): T {
const transformKeysWithId = [...(transformKeys || []), ...ID_KEYS];
return this.transformRecursive(
target,
input => this.entityIdStrategy.encodeId(input),
transformKeysWithId,
);
}
private transformRecursive<T>(target: T, transformFn: (input: any) => ID, transformKeys?: string[]): T {
// noinspection SuspiciousInstanceOfGuard
if (
target == null ||
typeof target === 'boolean' ||
target instanceof Promise ||
target instanceof Date ||
target instanceof RegExp
) {
return target;
}
if (typeof target === 'string' || typeof target === 'number') {
return transformFn(target as any) as any;
}
if (Array.isArray(target)) {
(target as any) = target.slice(0);
if (
target.length === 0 ||
typeof target[0] === 'string' ||
typeof target[0] === 'number' ||
typeof target[0] === 'boolean' ||
target[0] == null
) {
return target;
}
const isSimpleObject = this.isSimpleObject(target[0]);
if (isSimpleObject) {
const length = target.length;
for (let i = 0; i < length; i++) {
target[i] = this.transform(target[i], transformFn, transformKeys);
}
} else {
const length = target.length;
for (let i = 0; i < length; i++) {
target[i] = this.transformRecursive(target[i], transformFn, transformKeys);
}
}
} else {
target = this.transform(target, transformFn, transformKeys);
if (isObject(target)) {
for (const key of Object.keys(target)) {
if (this.isObject(target[key as keyof T])) {
target[key as keyof T] = this.transformRecursive(
target[key as keyof T],
transformFn,
transformKeys,
);
}
}
}
}
return target;
}
private transform<T>(target: T, transformFn: (input: any) => ID, transformKeys?: string[]): T {
if (target == null || !this.isObject(target) || Array.isArray(target)) {
return target;
}
const clone = Object.assign({}, target);
if (transformKeys) {
for (const key of transformKeys) {
if (target[key as keyof T]) {
const val = target[key as keyof T];
if (Array.isArray(val)) {
(clone as any)[key] = val.map(v => transformFn(v));
} else {
(clone as any)[key] = transformFn(val);
}
}
}
}
return clone;
}
private isSimpleObject(target: any): boolean {
if (!target) {
return true;
}
const values = Object.values(target);
for (const value of values) {
if (this.isObject(value) || value === null) {
return false;
}
}
return true;
}
private isObject(target: any): target is object {
return typeof target === 'object' && target != null;
}
}
|
import { ArgumentsHost, ExecutionContext } from '@nestjs/common';
import { GqlContextType, GqlExecutionContext } from '@nestjs/graphql';
import { Request, Response } from 'express';
import { GraphQLResolveInfo } from 'graphql';
import { InternalServerError } from '../../common/error/errors';
export type RestContext = { req: Request; res: Response; isGraphQL: false; info: undefined };
export type GraphQLContext = {
req: Request;
res: Response;
isGraphQL: true;
info: GraphQLResolveInfo;
};
/**
* Parses in the Nest ExecutionContext of the incoming request, accounting for both
* GraphQL & REST requests.
*/
export function parseContext(context: ExecutionContext | ArgumentsHost): RestContext | GraphQLContext {
// TODO: Remove this check once this issue is resolved: https://github.com/nestjs/graphql/pull/1469
if ((context as ExecutionContext).getHandler?.()?.name === '__resolveType') {
return {
req: context.getArgs()[1].req,
res: context.getArgs()[1].res,
isGraphQL: false,
info: undefined,
};
}
if (context.getType() === 'http') {
const httpContext = context.switchToHttp();
return {
isGraphQL: false,
req: httpContext.getRequest(),
res: httpContext.getResponse(),
info: undefined,
};
} else if (context.getType<GqlContextType>() === 'graphql') {
const gqlContext = GqlExecutionContext.create(context as ExecutionContext);
return {
isGraphQL: true,
req: gqlContext.getContext().req,
res: gqlContext.getContext().res,
info: gqlContext.getInfo(),
};
} else {
throw new InternalServerError(`Context "${context.getType()}" is not supported.`);
}
}
|
import { CurrencyCode, LanguageCode } from '@vendure/common/lib/generated-types';
import { beforeAll, describe, expect, it } from 'vitest';
import { CachedSession } from '../../config/session-cache/session-cache-strategy';
import { Channel } from '../../entity/channel/channel.entity';
import { Order } from '../../entity/order/order.entity';
import { Zone } from '../../entity/zone/zone.entity';
import { RequestContext, SerializedRequestContext } from './request-context';
describe('RequestContext', () => {
describe('serialize/deserialize', () => {
let serializedCtx: SerializedRequestContext;
let original: RequestContext;
beforeAll(() => {
original = createRequestContext();
serializedCtx = original.serialize();
});
it('apiType', () => {
const result = RequestContext.deserialize(serializedCtx);
expect(result.apiType).toBe(original.apiType);
});
it('channelId', () => {
const result = RequestContext.deserialize(serializedCtx);
expect(result.channelId).toBe(original.channelId);
});
it('languageCode', () => {
const result = RequestContext.deserialize(serializedCtx);
expect(result.languageCode).toBe(original.languageCode);
});
it('activeUserId', () => {
const result = RequestContext.deserialize(serializedCtx);
expect(result.activeUserId).toBe(original.activeUserId);
});
it('isAuthorized', () => {
const result = RequestContext.deserialize(serializedCtx);
expect(result.isAuthorized).toBe(original.isAuthorized);
});
it('authorizedAsOwnerOnly', () => {
const result = RequestContext.deserialize(serializedCtx);
expect(result.authorizedAsOwnerOnly).toBe(original.authorizedAsOwnerOnly);
});
it('channel', () => {
const result = RequestContext.deserialize(serializedCtx);
expect(result.channel).toEqual(original.channel);
});
it('session', () => {
const result = RequestContext.deserialize(serializedCtx);
expect(result.session).toEqual(original.session);
});
// https://github.com/vendure-ecommerce/vendure/issues/864
it('serialize request context with circular refs', () => {
const cyclic: any = {};
const cyclic1: any = {
prop: cyclic,
};
cyclic.prop = cyclic1;
const requestContext = createRequestContext({
simple: 'foo',
arr: [1, 2, 3],
cycle: cyclic,
cycleArr: [cyclic, cyclic],
});
const serialized = requestContext.serialize();
expect(serialized._req).toEqual({
simple: 'foo',
arr: [1, 2, 3],
cycle: {},
cycleArr: [{}, {}],
});
});
});
describe('copy', () => {
let original: RequestContext;
beforeAll(() => {
original = createRequestContext();
});
it('is a RequestContext instance', () => {
const copy = original.copy();
expect(copy instanceof RequestContext).toBe(true);
});
it('is not identical to original', () => {
const copy = original.copy();
expect(copy === original).toBe(false);
});
it('getters work', () => {
const copy = original.copy();
expect(copy.apiType).toEqual(original.apiType);
expect(copy.channelId).toEqual(original.channelId);
expect(copy.languageCode).toEqual(original.languageCode);
expect(copy.activeUserId).toEqual(original.activeUserId);
expect(copy.isAuthorized).toEqual(original.isAuthorized);
expect(copy.authorizedAsOwnerOnly).toEqual(original.authorizedAsOwnerOnly);
expect(copy.channel).toEqual(original.channel);
expect(copy.session).toEqual(original.session);
});
it('mutating copy leaves original intact', () => {
const copy = original.copy();
(copy as any).foo = 'bar';
expect((copy as any).foo).toBe('bar');
expect((original as any).foo).toBeUndefined();
});
it('mutating deep property affects both', () => {
const copy = original.copy();
copy.channel.code = 'changed';
expect(copy.channel.code).toBe('changed');
expect(original.channel.code).toBe('changed');
});
});
function createRequestContext(req?: any) {
const activeOrder = new Order({
id: '55555',
active: true,
code: 'ADAWDJAWD',
});
const session = {
cacheExpiry: Number.MAX_SAFE_INTEGER,
expires: new Date(),
id: '1234',
token: '2d37187e9e8fc47807fe4f58ca',
activeOrderId: '123',
user: {
id: '8833774',
identifier: 'user',
verified: true,
channelPermissions: [],
},
} satisfies CachedSession;
const zone = new Zone({
id: '62626',
name: 'Europe',
});
const channel = new Channel({
token: 'oiajwodij09au3r',
id: '995859',
code: '__default_channel__',
defaultCurrencyCode: CurrencyCode.EUR,
pricesIncludeTax: true,
defaultLanguageCode: LanguageCode.en,
defaultShippingZone: zone,
defaultTaxZone: zone,
});
return new RequestContext({
apiType: 'admin',
languageCode: LanguageCode.en,
channel,
session,
req: req ?? {},
isAuthorized: true,
authorizedAsOwnerOnly: false,
});
}
});
|
import { CurrencyCode, LanguageCode, Permission } from '@vendure/common/lib/generated-types';
import { ID, JsonCompatible } from '@vendure/common/lib/shared-types';
import { isObject } from '@vendure/common/lib/shared-utils';
import { Request } from 'express';
import { TFunction } from 'i18next';
import { idsAreEqual } from '../../common/utils';
import { CachedSession } from '../../config/session-cache/session-cache-strategy';
import { Channel } from '../../entity/channel/channel.entity';
import { ApiType } from './get-api-type';
export type SerializedRequestContext = {
_req?: any;
_session: JsonCompatible<Required<CachedSession>>;
_apiType: ApiType;
_channel: JsonCompatible<Channel>;
_languageCode: LanguageCode;
_isAuthorized: boolean;
_authorizedAsOwnerOnly: boolean;
};
/**
* @description
* The RequestContext holds information relevant to the current request, which may be
* required at various points of the stack.
*
* It is a good practice to inject the RequestContext (using the {@link Ctx} decorator) into
* _all_ resolvers & REST handler, and then pass it through to the service layer.
*
* This allows the service layer to access information about the current user, the active language,
* the active Channel, and so on. In addition, the {@link TransactionalConnection} relies on the
* presence of the RequestContext object in order to correctly handle per-request database transactions.
*
* @example
* ```ts
* \@Query()
* myQuery(\@Ctx() ctx: RequestContext) {
* return this.myService.getData(ctx);
* }
* ```
* @docsCategory request
*/
export class RequestContext {
private readonly _languageCode: LanguageCode;
private readonly _currencyCode: CurrencyCode;
private readonly _channel: Channel;
private readonly _session?: CachedSession;
private readonly _isAuthorized: boolean;
private readonly _authorizedAsOwnerOnly: boolean;
private readonly _translationFn: TFunction;
private readonly _apiType: ApiType;
private readonly _req?: Request;
/**
* @internal
*/
constructor(options: {
req?: Request;
apiType: ApiType;
channel: Channel;
session?: CachedSession;
languageCode?: LanguageCode;
currencyCode?: CurrencyCode;
isAuthorized: boolean;
authorizedAsOwnerOnly: boolean;
translationFn?: TFunction;
}) {
const { req, apiType, channel, session, languageCode, currencyCode, translationFn } = options;
this._req = req;
this._apiType = apiType;
this._channel = channel;
this._session = session;
this._languageCode = languageCode || (channel && channel.defaultLanguageCode);
this._currencyCode = currencyCode || (channel && channel.defaultCurrencyCode);
this._isAuthorized = options.isAuthorized;
this._authorizedAsOwnerOnly = options.authorizedAsOwnerOnly;
this._translationFn = translationFn || (((key: string) => key) as any);
}
/**
* @description
* Creates an "empty" RequestContext object. This is only intended to be used
* when a service method must be called outside the normal request-response
* cycle, e.g. when programmatically populating data. Usually a better alternative
* is to use the {@link RequestContextService} `create()` method, which allows more control
* over the resulting RequestContext object.
*/
static empty(): RequestContext {
return new RequestContext({
apiType: 'admin',
authorizedAsOwnerOnly: false,
channel: new Channel(),
isAuthorized: true,
});
}
/**
* @description
* Creates a new RequestContext object from a serialized object created by the
* `serialize()` method.
*/
static deserialize(ctxObject: SerializedRequestContext): RequestContext {
return new RequestContext({
req: ctxObject._req,
apiType: ctxObject._apiType,
channel: new Channel(ctxObject._channel),
session: {
...ctxObject._session,
expires: ctxObject._session?.expires && new Date(ctxObject._session.expires),
},
languageCode: ctxObject._languageCode,
isAuthorized: ctxObject._isAuthorized,
authorizedAsOwnerOnly: ctxObject._authorizedAsOwnerOnly,
});
}
/**
* @description
* Returns `true` if there is an active Session & User associated with this request,
* and that User has the specified permissions on the active Channel.
*/
userHasPermissions(permissions: Permission[]): boolean {
const user = this.session?.user;
if (!user || !this.channelId) {
return false;
}
const permissionsOnChannel = user.channelPermissions.find(c => idsAreEqual(c.id, this.channelId));
if (permissionsOnChannel) {
return this.arraysIntersect(permissionsOnChannel.permissions, permissions);
}
return false;
}
/**
* @description
* Serializes the RequestContext object into a JSON-compatible simple object.
* This is useful when you need to send a RequestContext object to another
* process, e.g. to pass it to the Job Queue via the {@link JobQueueService}.
*/
serialize(): SerializedRequestContext {
const serializableThis: any = Object.assign({}, this);
if (this._req) {
serializableThis._req = this.shallowCloneRequestObject(this._req);
}
return JSON.parse(JSON.stringify(serializableThis));
}
/**
* @description
* Creates a shallow copy of the RequestContext instance. This means that
* mutations to the copy itself will not affect the original, but deep mutations
* (e.g. copy.channel.code = 'new') *will* also affect the original.
*/
copy(): RequestContext {
return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
}
/**
* @description
* The raw Express request object.
*/
get req(): Request | undefined {
return this._req;
}
/**
* @description
* Signals which API this request was received by, e.g. `admin` or `shop`.
*/
get apiType(): ApiType {
return this._apiType;
}
/**
* @description
* The active {@link Channel} of this request.
*/
get channel(): Channel {
return this._channel;
}
get channelId(): ID {
return this._channel.id;
}
get languageCode(): LanguageCode {
return this._languageCode;
}
get currencyCode(): CurrencyCode {
return this._currencyCode;
}
get session(): CachedSession | undefined {
return this._session;
}
get activeUserId(): ID | undefined {
return this.session?.user?.id;
}
/**
* @description
* True if the current session is authorized to access the current resolver method.
*
* @deprecated Use `userHasPermissions()` method instead.
*/
get isAuthorized(): boolean {
return this._isAuthorized;
}
/**
* @description
* True if the current anonymous session is only authorized to operate on entities that
* are owned by the current session.
*/
get authorizedAsOwnerOnly(): boolean {
return this._authorizedAsOwnerOnly;
}
/**
* @description
* Translate the given i18n key
*/
translate(key: string, variables?: { [k: string]: any }): string {
try {
return this._translationFn(key, variables);
} catch (e: any) {
return `Translation format error: ${JSON.stringify(e.message)}). Original key: ${key}`;
}
}
/**
* Returns true if any element of arr1 appears in arr2.
*/
private arraysIntersect<T>(arr1: T[], arr2: T[]): boolean {
return arr1.reduce((intersects, role) => {
return intersects || arr2.includes(role);
}, false as boolean);
}
/**
* The Express "Request" object is huge and contains many circular
* references. We will preserve just a subset of the whole, by preserving
* only the serializable properties up to 2 levels deep.
* @private
*/
private shallowCloneRequestObject(req: Request) {
function copySimpleFieldsToDepth(target: any, maxDepth: number, depth: number = 0) {
const result: any = {};
// eslint-disable-next-line guard-for-in
for (const key in target) {
if (key === 'host' && depth === 0) {
// avoid Express "deprecated: req.host" warning
continue;
}
let val: any;
try {
val = target[key];
} catch (e: any) {
val = String(e);
}
if (Array.isArray(val)) {
depth++;
result[key] = val.map(v => {
if (!isObject(v) && typeof val !== 'function') {
return v;
} else {
return copySimpleFieldsToDepth(v, maxDepth, depth);
}
});
depth--;
} else if (!isObject(val) && typeof val !== 'function') {
result[key] = val;
} else if (depth < maxDepth) {
depth++;
result[key] = copySimpleFieldsToDepth(val, maxDepth, depth);
depth--;
}
}
return result;
}
return copySimpleFieldsToDepth(req, 1);
}
}
|
import { Request, Response } from 'express';
import ms from 'ms';
import { AuthOptions } from '../../config/vendure-config';
/**
* Sets the authToken either as a cookie or as a response header, depending on the
* config settings.
*/
export function setSessionToken(options: {
sessionToken: string;
rememberMe: boolean;
authOptions: Required<AuthOptions>;
req: Request;
res: Response;
}) {
const { sessionToken, rememberMe, authOptions, req, res } = options;
const usingCookie =
authOptions.tokenMethod === 'cookie' ||
(Array.isArray(authOptions.tokenMethod) && authOptions.tokenMethod.includes('cookie'));
const usingBearer =
authOptions.tokenMethod === 'bearer' ||
(Array.isArray(authOptions.tokenMethod) && authOptions.tokenMethod.includes('bearer'));
if (usingCookie) {
if (req.session) {
if (rememberMe) {
req.sessionOptions.maxAge = ms('1y');
}
req.session.token = sessionToken;
}
}
if (usingBearer) {
res.set(authOptions.authTokenHeaderKey, sessionToken);
}
}
|
import { Permission } from '@vendure/common/lib/generated-types';
import { CustomFieldConfig } from '../../config/custom-field/custom-field-types';
import { RequestContext } from './request-context';
export function userHasPermissionsOnCustomField(ctx: RequestContext, fieldDef: CustomFieldConfig) {
const requiresPermission = (fieldDef.requiresPermission as Permission[]) ?? [];
const permissionsArray = Array.isArray(requiresPermission) ? requiresPermission : [requiresPermission];
if (permissionsArray.length === 0) {
return true;
}
return ctx.userHasPermissions(permissionsArray);
}
|
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { fail } from 'assert';
import { describe, expect, it } from 'vitest';
import { Injector } from '../../common/injector';
import { RequestContext } from './request-context';
import { validateCustomFieldValue } from './validate-custom-field-value';
describe('validateCustomFieldValue()', () => {
const injector = new Injector({} as any);
async function assertThrowsError(validateFn: (() => Promise<void>) | (() => void), message: string) {
try {
await validateFn();
fail('Should have thrown');
} catch (e: any) {
expect(e.message).toBe(message);
}
}
const ctx = RequestContext.empty();
describe('string & localeString', () => {
const validate = (value: string) => () =>
validateCustomFieldValue(
{
name: 'test',
type: 'string',
pattern: '^[0-9]+',
},
value,
injector,
ctx,
);
it('passes valid pattern', async () => {
expect(validate('1')).not.toThrow();
expect(validate('123')).not.toThrow();
expect(validate('1foo')).not.toThrow();
});
it('throws on invalid pattern', async () => {
await assertThrowsError(validate(''), 'error.field-invalid-string-pattern');
await assertThrowsError(validate('foo'), 'error.field-invalid-string-pattern');
await assertThrowsError(validate(' 1foo'), 'error.field-invalid-string-pattern');
});
});
describe('string options', () => {
const validate = (value: string) => () =>
validateCustomFieldValue(
{
name: 'test',
type: 'string',
options: [{ value: 'small' }, { value: 'large' }],
},
value,
injector,
ctx,
);
it('passes valid option', async () => {
expect(validate('small')).not.toThrow();
expect(validate('large')).not.toThrow();
});
it('throws on invalid option', async () => {
await assertThrowsError(validate('SMALL'), 'error.field-invalid-string-option');
await assertThrowsError(validate(''), 'error.field-invalid-string-option');
await assertThrowsError(validate('bad'), 'error.field-invalid-string-option');
});
});
describe('int & float', () => {
const validate = (value: number) => () =>
validateCustomFieldValue(
{
name: 'test',
type: 'int',
min: 5,
max: 10,
},
value,
injector,
ctx,
);
it('passes valid range', async () => {
expect(validate(5)).not.toThrow();
expect(validate(7)).not.toThrow();
expect(validate(10)).not.toThrow();
});
it('throws on invalid range', async () => {
await assertThrowsError(validate(4), 'error.field-invalid-number-range-min');
await assertThrowsError(validate(11), 'error.field-invalid-number-range-max');
await assertThrowsError(validate(-7), 'error.field-invalid-number-range-min');
});
});
describe('datetime', () => {
const validate = (value: string) => () =>
validateCustomFieldValue(
{
name: 'test',
type: 'datetime',
min: '2019-01-01T08:30',
max: '2019-06-01T08:30',
},
value,
injector,
ctx,
);
it('passes valid range', async () => {
expect(validate('2019-01-01T08:30:00.000')).not.toThrow();
expect(validate('2019-06-01T08:30:00.000')).not.toThrow();
expect(validate('2019-04-12T14:15:51.200')).not.toThrow();
});
it('throws on invalid range', async () => {
await assertThrowsError(
validate('2019-01-01T08:29:00.000'),
'error.field-invalid-datetime-range-min',
);
await assertThrowsError(
validate('2019-06-01T08:30:00.100'),
'error.field-invalid-datetime-range-max',
);
});
});
describe('validate function', () => {
const validate1 = (value: string) => () =>
validateCustomFieldValue(
{
name: 'test',
type: 'string',
validate: (v: string) => {
if (v !== 'valid') {
return 'invalid';
}
},
},
value,
injector,
ctx,
);
const validate2 = (value: string, languageCode: LanguageCode) => () => {
const ctxWithLanguage = new RequestContext({
languageCode,
apiType: 'admin',
} as any);
return validateCustomFieldValue(
{
name: 'test',
type: 'string',
validate: (v: string) => {
if (v !== 'valid') {
return [
{ languageCode: LanguageCode.en, value: 'invalid' },
{ languageCode: LanguageCode.de, value: 'ungültig' },
];
}
},
},
value,
injector,
ctxWithLanguage,
);
};
it('passes validate fn string', async () => {
expect(validate1('valid')).not.toThrow();
});
it('passes validate fn localized string', async () => {
expect(validate2('valid', LanguageCode.de)).not.toThrow();
});
it('fails validate fn string', async () => {
await assertThrowsError(validate1('bad'), 'invalid');
});
it('fails validate fn localized string en', async () => {
await assertThrowsError(validate2('bad', LanguageCode.en), 'invalid');
});
it('fails validate fn localized string de', async () => {
await assertThrowsError(validate2('bad', LanguageCode.de), 'ungültig');
});
});
describe('list types', () => {
it('number list', async () => {
const validate = (value: number[]) => () =>
validateCustomFieldValue(
{
name: 'test',
type: 'int',
list: true,
min: 0,
max: 10,
},
value,
injector,
ctx,
);
expect(validate([1, 2, 6])).not.toThrow();
await assertThrowsError(validate([1, 15, 3]), 'error.field-invalid-number-range-max');
});
it('string list with options', async () => {
const validate = (value: string[]) => () =>
validateCustomFieldValue(
{
name: 'test',
list: true,
type: 'string',
options: [{ value: 'small' }, { value: 'large' }],
},
value,
injector,
ctx,
);
expect(validate(['small', 'large'])).not.toThrow();
await assertThrowsError(validate(['small', 'huge']), 'error.field-invalid-string-option');
});
it('list with validate function', async () => {
const validate = (value: string[]) => () =>
validateCustomFieldValue(
{
name: 'test',
type: 'string',
list: true,
validate: (v: string[]) => {
if (!v.every(val => val === 'valid')) {
return 'invalid';
}
},
},
value,
injector,
ctx,
);
expect(validate(['valid', 'valid'])).not.toThrow();
await assertThrowsError(validate(['bad input', 'valid']), 'invalid');
});
});
});
|
import { assertNever } from '@vendure/common/lib/shared-utils';
import { UserInputError } from '../../common/error/errors';
import { Injector } from '../../common/injector';
import {
CustomFieldConfig,
DateTimeCustomFieldConfig,
FloatCustomFieldConfig,
IntCustomFieldConfig,
LocaleStringCustomFieldConfig,
StringCustomFieldConfig,
TypedCustomFieldConfig,
} from '../../config/custom-field/custom-field-types';
import { RequestContext } from './request-context';
import { userHasPermissionsOnCustomField } from './user-has-permissions-on-custom-field';
/**
* Validates the value of a custom field input against any configured constraints.
* If validation fails, an error is thrown.
*/
export async function validateCustomFieldValue(
config: CustomFieldConfig,
value: any | any[],
injector: Injector,
ctx: RequestContext,
): Promise<void> {
if (config.readonly) {
throw new UserInputError('error.field-invalid-readonly', { name: config.name });
}
if (config.nullable === false) {
if (value === null) {
throw new UserInputError('error.field-invalid-non-nullable', {
name: config.name,
});
}
}
if (config.requiresPermission) {
if (!userHasPermissionsOnCustomField(ctx, config)) {
throw new UserInputError('error.field-invalid-no-permission', { name: config.name });
}
}
if (config.list === true && Array.isArray(value)) {
for (const singleValue of value) {
validateSingleValue(config, singleValue);
}
} else {
validateSingleValue(config, value);
}
await validateCustomFunction(config as TypedCustomFieldConfig<any, any>, value, injector, ctx);
}
function validateSingleValue(config: CustomFieldConfig, value: any) {
switch (config.type) {
case 'string':
case 'localeString':
validateStringField(config, value);
break;
case 'int':
case 'float':
validateNumberField(config, value);
break;
case 'datetime':
validateDateTimeField(config, value);
break;
case 'boolean':
case 'relation':
case 'text':
case 'localeText':
break;
default:
assertNever(config);
}
}
async function validateCustomFunction<T extends TypedCustomFieldConfig<any, any>>(
config: T,
value: any,
injector: Injector,
ctx: RequestContext,
) {
if (typeof config.validate === 'function') {
const error = await config.validate(value, injector, ctx);
if (typeof error === 'string') {
throw new UserInputError(error);
}
if (Array.isArray(error)) {
const localizedError = error.find(e => e.languageCode === ctx.languageCode) || error[0];
throw new UserInputError(localizedError.value);
}
}
}
function validateStringField(
config: StringCustomFieldConfig | LocaleStringCustomFieldConfig,
value: string,
): void {
const { pattern } = config;
if (pattern) {
const re = new RegExp(pattern);
if (!re.test(value)) {
throw new UserInputError('error.field-invalid-string-pattern', {
name: config.name,
value,
pattern,
});
}
}
const options = (config as StringCustomFieldConfig).options;
if (options) {
const validOptions = options.map(o => o.value);
if (value === null && config.nullable === true) {
return;
}
if (!validOptions.includes(value)) {
throw new UserInputError('error.field-invalid-string-option', {
name: config.name,
value,
validOptions: validOptions.map(o => `'${o}'`).join(', '),
});
}
}
}
function validateNumberField(config: IntCustomFieldConfig | FloatCustomFieldConfig, value: number): void {
const { min, max } = config;
if (min != null && value < min) {
throw new UserInputError('error.field-invalid-number-range-min', { name: config.name, value, min });
}
if (max != null && max < value) {
throw new UserInputError('error.field-invalid-number-range-max', { name: config.name, value, max });
}
}
function validateDateTimeField(config: DateTimeCustomFieldConfig, value: string): void {
const { min, max } = config;
const valueDate = new Date(value);
if (min != null && valueDate < new Date(min)) {
throw new UserInputError('error.field-invalid-datetime-range-min', {
name: config.name,
value: valueDate.toISOString(),
min,
});
}
if (max != null && new Date(max) < valueDate) {
throw new UserInputError('error.field-invalid-datetime-range-max', {
name: config.name,
value: valueDate.toISOString(),
max,
});
}
}
|
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { DynamicModule } from '@nestjs/common';
import { GqlModuleOptions, GraphQLModule, GraphQLTypesLoader } from '@nestjs/graphql';
import { notNullOrUndefined } from '@vendure/common/lib/shared-utils';
import { buildSchema, extendSchema, GraphQLSchema, printSchema, ValidationContext } from 'graphql';
import path from 'path';
import { ConfigModule } from '../../config/config.module';
import { ConfigService } from '../../config/config.service';
import { I18nModule } from '../../i18n/i18n.module';
import { I18nService } from '../../i18n/i18n.service';
import { getPluginAPIExtensions } from '../../plugin/plugin-metadata';
import { ServiceModule } from '../../service/service.module';
import { ApiSharedModule } from '../api-internal-modules';
import { CustomFieldRelationResolverService } from '../common/custom-field-relation-resolver.service';
import { IdCodecService } from '../common/id-codec.service';
import { AssetInterceptorPlugin } from '../middleware/asset-interceptor-plugin';
import { IdCodecPlugin } from '../middleware/id-codec-plugin';
import { TranslateErrorsPlugin } from '../middleware/translate-errors-plugin';
import { generateActiveOrderTypes } from './generate-active-order-types';
import { generateAuthenticationTypes } from './generate-auth-types';
import { generateErrorCodeEnum } from './generate-error-code-enum';
import { generateListOptions } from './generate-list-options';
import { generatePermissionEnum } from './generate-permissions';
import { generateResolvers } from './generate-resolvers';
import {
addActiveAdministratorCustomFields,
addGraphQLCustomFields,
addModifyOrderCustomFields,
addOrderLineCustomFieldsInput,
addPaymentMethodQuoteCustomFields,
addRegisterCustomerCustomFieldsInput,
addServerConfigCustomFields,
addShippingMethodQuoteCustomFields,
} from './graphql-custom-fields';
export interface GraphQLApiOptions {
apiType: 'shop' | 'admin';
typePaths: string[];
apiPath: string;
debug: boolean;
playground: boolean | any;
// eslint-disable-next-line @typescript-eslint/ban-types
resolverModule: Function;
validationRules: Array<(context: ValidationContext) => any>;
}
/**
* Dynamically generates a GraphQLModule according to the given config options.
*/
export function configureGraphQLModule(
getOptions: (configService: ConfigService) => GraphQLApiOptions,
): DynamicModule {
return GraphQLModule.forRootAsync<ApolloDriverConfig>({
driver: ApolloDriver,
useFactory: (
configService: ConfigService,
i18nService: I18nService,
idCodecService: IdCodecService,
typesLoader: GraphQLTypesLoader,
customFieldRelationResolverService: CustomFieldRelationResolverService,
) => {
return createGraphQLOptions(
i18nService,
configService,
idCodecService,
typesLoader,
customFieldRelationResolverService,
getOptions(configService),
);
},
inject: [
ConfigService,
I18nService,
IdCodecService,
GraphQLTypesLoader,
CustomFieldRelationResolverService,
],
imports: [ConfigModule, I18nModule, ApiSharedModule, ServiceModule],
});
}
async function createGraphQLOptions(
i18nService: I18nService,
configService: ConfigService,
idCodecService: IdCodecService,
typesLoader: GraphQLTypesLoader,
customFieldRelationResolverService: CustomFieldRelationResolverService,
options: GraphQLApiOptions,
): Promise<ApolloDriverConfig> {
const builtSchema = await buildSchemaForApi(options.apiType);
const resolvers = await generateResolvers(
configService,
customFieldRelationResolverService,
options.apiType,
builtSchema,
);
return {
path: '/' + options.apiPath,
typeDefs: printSchema(builtSchema),
include: [options.resolverModule],
fieldResolverEnhancers: ['guards'],
resolvers,
// We no longer rely on the upload facility bundled with Apollo Server, and instead
// manually configure the graphql-upload package. See https://github.com/vendure-ecommerce/vendure/issues/396
uploads: false,
playground: options.playground,
csrfPrevention: false,
debug: options.debug || false,
context: (req: any) => req,
// This is handled by the Express cors plugin
cors: false,
plugins: [
new IdCodecPlugin(idCodecService),
new TranslateErrorsPlugin(i18nService),
new AssetInterceptorPlugin(configService),
...configService.apiOptions.apolloServerPlugins,
],
validationRules: options.validationRules,
introspection: configService.apiOptions.introspection ?? true,
} as ApolloDriverConfig;
/**
* Generates the server's GraphQL schema by combining:
* 1. the default schema as defined in the source .graphql files specified by `typePaths`
* 2. any custom fields defined in the config
* 3. any schema extensions defined by plugins
*/
async function buildSchemaForApi(apiType: 'shop' | 'admin'): Promise<GraphQLSchema> {
const customFields = configService.customFields;
// Paths must be normalized to use forward-slash separators.
// See https://github.com/nestjs/graphql/issues/336
const normalizedPaths = options.typePaths.map(p => p.split(path.sep).join('/'));
const typeDefs = await typesLoader.mergeTypesByPaths(normalizedPaths);
const authStrategies =
apiType === 'shop'
? configService.authOptions.shopAuthenticationStrategy
: configService.authOptions.adminAuthenticationStrategy;
let schema = buildSchema(typeDefs);
getPluginAPIExtensions(configService.plugins, apiType)
.map(e => (typeof e.schema === 'function' ? e.schema() : e.schema))
.filter(notNullOrUndefined)
.forEach(documentNode => (schema = extendSchema(schema, documentNode)));
schema = generateListOptions(schema);
schema = addGraphQLCustomFields(schema, customFields, apiType === 'shop');
schema = addOrderLineCustomFieldsInput(schema, customFields.OrderLine || []);
schema = addModifyOrderCustomFields(schema, customFields.Order || []);
schema = addShippingMethodQuoteCustomFields(schema, customFields.ShippingMethod || []);
schema = addPaymentMethodQuoteCustomFields(schema, customFields.PaymentMethod || []);
schema = generateAuthenticationTypes(schema, authStrategies);
schema = generateErrorCodeEnum(schema);
if (apiType === 'admin') {
schema = addServerConfigCustomFields(schema, customFields);
schema = addActiveAdministratorCustomFields(schema, customFields.Administrator);
}
if (apiType === 'shop') {
schema = addRegisterCustomerCustomFieldsInput(schema, customFields.Customer || []);
schema = generateActiveOrderTypes(schema, configService.orderOptions.activeOrderStrategy);
}
schema = generatePermissionEnum(schema, configService.authOptions.customPermissions);
return schema;
}
}
|
import { stitchSchemas, ValidationLevel } from '@graphql-tools/stitch';
import { Mutation, Query } from '@vendure/common/lib/generated-shop-types';
import {
buildASTSchema,
GraphQLInputFieldConfigMap,
GraphQLInputObjectType,
GraphQLSchema,
isInputObjectType,
} from 'graphql';
import { InternalServerError } from '../../common/error/errors';
import { ActiveOrderStrategy, ACTIVE_ORDER_INPUT_FIELD_NAME } from '../../config/order/active-order-strategy';
/**
* This function is responsible for constructing the `ActiveOrderInput` GraphQL input type.
* It does so based on the inputs defined by the configured ActiveOrderStrategy defineInputType
* methods, dynamically building a mapped input type of the format:
*
*```
* {
* [strategy_name]: strategy_input_type
* }
* ```
*/
export function generateActiveOrderTypes(
schema: GraphQLSchema,
activeOrderStrategies: ActiveOrderStrategy | ActiveOrderStrategy[],
): GraphQLSchema {
const fields: GraphQLInputFieldConfigMap = {};
const strategySchemas: GraphQLSchema[] = [];
const strategiesArray = Array.isArray(activeOrderStrategies)
? activeOrderStrategies
: [activeOrderStrategies];
for (const strategy of strategiesArray) {
if (typeof strategy.defineInputType === 'function') {
const inputSchema = buildASTSchema(strategy.defineInputType());
const inputType = Object.values(inputSchema.getTypeMap()).find(
(type): type is GraphQLInputObjectType => isInputObjectType(type),
);
if (!inputType) {
throw new InternalServerError(
`${strategy.constructor.name}.defineInputType() does not define a GraphQL Input type`,
);
}
fields[strategy.name] = { type: inputType };
strategySchemas.push(inputSchema);
}
}
if (Object.keys(fields).length === 0) {
return schema;
}
const activeOrderInput = new GraphQLInputObjectType({
name: 'ActiveOrderInput',
fields,
});
const activeOrderOperations: Array<{ name: keyof Query | keyof Mutation; isMutation: boolean }> = [
{ name: 'activeOrder', isMutation: false },
{ name: 'eligibleShippingMethods', isMutation: false },
{ name: 'eligiblePaymentMethods', isMutation: false },
{ name: 'nextOrderStates', isMutation: false },
{ name: 'addItemToOrder', isMutation: true },
{ name: 'adjustOrderLine', isMutation: true },
{ name: 'removeOrderLine', isMutation: true },
{ name: 'removeAllOrderLines', isMutation: true },
{ name: 'applyCouponCode', isMutation: true },
{ name: 'removeCouponCode', isMutation: true },
{ name: 'addPaymentToOrder', isMutation: true },
{ name: 'setCustomerForOrder', isMutation: true },
{ name: 'setOrderShippingAddress', isMutation: true },
{ name: 'setOrderBillingAddress', isMutation: true },
{ name: 'setOrderShippingMethod', isMutation: true },
{ name: 'setOrderCustomFields', isMutation: true },
{ name: 'transitionOrderToState', isMutation: true },
];
const queryType = schema.getQueryType();
const mutationType = schema.getMutationType();
const strategyNames = strategiesArray.map(s => s.name).join(', ');
const description = `Inputs for the configured ${
strategiesArray.length === 1 ? 'ActiveOrderStrategy' : 'ActiveOrderStrategies'
} ${strategyNames}`;
for (const operation of activeOrderOperations) {
const field = operation.isMutation
? mutationType?.getFields()[operation.name]
: queryType?.getFields()[operation.name];
if (!field) {
throw new InternalServerError(
`Could not find a GraphQL type definition for the field ${operation.name}`,
);
}
// TODO: Figure out a non-hacky way to do this!
(field.args as any).push({
name: ACTIVE_ORDER_INPUT_FIELD_NAME,
type: activeOrderInput,
description,
defaultValue: null,
extensions: null,
astNode: null,
deprecationReason: null,
});
}
return stitchSchemas({
subschemas: [schema, ...strategySchemas],
types: [activeOrderInput],
typeMergingOptions: { validationSettings: { validationLevel: ValidationLevel.Off } },
});
}
|
import { stitchSchemas, ValidationLevel } from '@graphql-tools/stitch';
import {
buildASTSchema,
GraphQLInputFieldConfigMap,
GraphQLInputObjectType,
GraphQLSchema,
isInputObjectType,
} from 'graphql';
import { InternalServerError } from '../../common/error/errors';
import { AuthenticationStrategy } from '../../config/auth/authentication-strategy';
/**
* This function is responsible for constructing the `AuthenticationInput` GraphQL input type.
* It does so based on the inputs defined by the configured AuthenticationStrategy defineInputType
* methods, dynamically building a mapped input type of the format:
*
*```
* {
* [strategy_name]: strategy_input_type
* }
* ```
*/
export function generateAuthenticationTypes(
schema: GraphQLSchema,
authenticationStrategies: AuthenticationStrategy[],
): GraphQLSchema {
const fields: GraphQLInputFieldConfigMap = {};
const strategySchemas: GraphQLSchema[] = [];
for (const strategy of authenticationStrategies) {
const inputSchema = buildASTSchema(strategy.defineInputType());
const inputType = Object.values(
inputSchema.getTypeMap(),
).find((type): type is GraphQLInputObjectType => isInputObjectType(type));
if (!inputType) {
throw new InternalServerError(
`${strategy.constructor.name}.defineInputType() does not define a GraphQL Input type`,
);
}
fields[strategy.name] = { type: inputType };
strategySchemas.push(inputSchema);
}
const authenticationInput = new GraphQLInputObjectType({
name: 'AuthenticationInput',
fields,
});
return stitchSchemas({
subschemas: [schema, ...strategySchemas],
types: [authenticationInput],
typeMergingOptions: { validationSettings: { validationLevel: ValidationLevel.Off } },
});
}
|
import { buildSchema, extendSchema, GraphQLSchema, parse } from 'graphql';
export const ERROR_INTERFACE_NAME = 'ErrorResult';
/**
* Generates the members of the `ErrorCode` enum dynamically, by getting the names of
* all the types which inherit from the `ErrorResult` interface.
*/
export function generateErrorCodeEnum(typeDefsOrSchema: string | GraphQLSchema): GraphQLSchema {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
const errorNodes = Object.values(schema.getTypeMap())
.map(type => type.astNode)
.filter(node => {
return (
node &&
node?.kind === 'ObjectTypeDefinition' &&
node.interfaces?.map(i => i.name.value).includes(ERROR_INTERFACE_NAME)
);
});
if (!errorNodes.length) {
return schema;
}
const errorCodeEnum = `
extend enum ErrorCode {
${errorNodes.map(n => camelToUpperSnakeCase(n?.name.value || '')).join('\n')}
}`;
return extendSchema(schema, parse(errorCodeEnum));
}
function camelToUpperSnakeCase(input: string): string {
return input.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
}
|
// Using require right now to force the commonjs version of GraphQL to be used
// when running vitest tests. See https://github.com/vitejs/vite/issues/7879
// eslint-disable-next-line @typescript-eslint/no-var-requires
import { describe, expect, it } from 'vitest';
import { generateListOptions } from './generate-list-options';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { buildSchema, printType } = require('graphql');
/* eslint-disable @typescript-eslint/no-non-null-assertion */
describe('generateListOptions()', () => {
const COMMON_TYPES = `
scalar JSON
scalar DateTime
interface PaginatedList {
items: [Node!]!
totalItems: Int!
}
interface Node {
id: ID!
}
enum SortOrder {
ASC
DESC
}
input IDOperators { dummy: String }
input StringOperators { dummy: String }
input BooleanOperators { dummy: String }
input NumberRange { dummy: String }
input NumberOperators { dummy: String }
input DateRange { dummy: String }
input DateOperators { dummy: String }
type PersonList implements PaginatedList {
items: [Person!]!
totalItems: Int!
}
`;
const removeLeadingWhitespace = (s: string) => {
const indent = s.match(/^\s+/m)![0].replace(/\n/, '');
return s.replace(new RegExp(`^${indent}`, 'gm'), '').trim();
};
it('creates the required input types', () => {
const input = `
${COMMON_TYPES}
type Query {
people(options: PersonListOptions): PersonList
}
type Person {
name: String!
age: Int!
}
# Generated at runtime
input PersonListOptions
`;
const result = generateListOptions(input);
expect(printType(result.getType('PersonListOptions')!)).toBe(
removeLeadingWhitespace(`
input PersonListOptions {
"""Skips the first n results, for use in pagination"""
skip: Int
"""Takes n results, for use in pagination"""
take: Int
"""Specifies which properties to sort the results by"""
sort: PersonSortParameter
"""Allows the results to be filtered"""
filter: PersonFilterParameter
}`),
);
expect(printType(result.getType('PersonSortParameter')!)).toBe(
removeLeadingWhitespace(`
input PersonSortParameter {
name: SortOrder
age: SortOrder
}`),
);
expect(printType(result.getType('PersonFilterParameter')!)).toBe(
removeLeadingWhitespace(`
input PersonFilterParameter {
name: StringOperators
age: NumberOperators
_and: [PersonFilterParameter!]
_or: [PersonFilterParameter!]
}`),
);
});
it('works with a non-nullabel list type', () => {
const input = `
${COMMON_TYPES}
type Query {
people: PersonList!
}
type Person {
name: String!
age: Int!
}
`;
const result = generateListOptions(buildSchema(input));
expect(result.getType('PersonListOptions')).toBeTruthy();
});
it('uses the correct filter operators', () => {
const input = `
${COMMON_TYPES}
type Query {
people(options: PersonListOptions): PersonList
}
type Person {
name: String!
age: Int!
updatedAt: DateTime!
admin: Boolean!
score: Float
personType: PersonType!
}
enum PersonType {
TABS
SPACES
}
# Generated at runtime
input PersonListOptions
`;
const result = generateListOptions(buildSchema(input));
expect(printType(result.getType('PersonFilterParameter')!)).toBe(
removeLeadingWhitespace(`
input PersonFilterParameter {
name: StringOperators
age: NumberOperators
updatedAt: DateOperators
admin: BooleanOperators
score: NumberOperators
personType: StringOperators
_and: [PersonFilterParameter!]
_or: [PersonFilterParameter!]
}`),
);
});
it('creates the ListOptions interface and argument if not defined', () => {
const input = `
${COMMON_TYPES}
type Query {
people: PersonList
}
type Person {
name: String!
}
`;
const result = generateListOptions(buildSchema(input));
expect(printType(result.getType('PersonListOptions')!)).toBe(
removeLeadingWhitespace(`
input PersonListOptions {
"""Skips the first n results, for use in pagination"""
skip: Int
"""Takes n results, for use in pagination"""
take: Int
"""Specifies which properties to sort the results by"""
sort: PersonSortParameter
"""Allows the results to be filtered"""
filter: PersonFilterParameter
}`),
);
const args = result.getQueryType()!.getFields().people.args;
expect(args.length).toBe(1);
expect(args[0].name).toBe('options');
expect(args[0].type.toString()).toBe('PersonListOptions');
});
it('extends the ListOptions interface if already defined', () => {
const input = `
${COMMON_TYPES}
type Query {
people(options: PersonListOptions): PersonList
}
type Person {
name: String!
}
input PersonListOptions {
categoryId: ID
}
`;
const result = generateListOptions(buildSchema(input));
expect(printType(result.getType('PersonListOptions')!)).toBe(
removeLeadingWhitespace(`
input PersonListOptions {
categoryId: ID
"""Skips the first n results, for use in pagination"""
skip: Int
"""Takes n results, for use in pagination"""
take: Int
"""Specifies which properties to sort the results by"""
sort: PersonSortParameter
"""Allows the results to be filtered"""
filter: PersonFilterParameter
}`),
);
const args = result.getQueryType()!.getFields().people.args;
expect(args.length).toBe(1);
expect(args[0].name).toBe('options');
expect(args[0].type.toString()).toBe('PersonListOptions');
});
it('ignores properties with types which cannot be sorted or filtered', () => {
const input = `
${COMMON_TYPES}
type Query {
people: PersonList
}
type Person {
id: ID!
name: String!
vitals: [Int]
meta: JSON
user: User!
}
type User {
identifier: String!
}
`;
const result = generateListOptions(buildSchema(input));
expect(printType(result.getType('PersonSortParameter')!)).toBe(
removeLeadingWhitespace(`
input PersonSortParameter {
id: SortOrder
name: SortOrder
}`),
);
expect(printType(result.getType('PersonFilterParameter')!)).toBe(
removeLeadingWhitespace(`
input PersonFilterParameter {
id: IDOperators
name: StringOperators
_and: [PersonFilterParameter!]
_or: [PersonFilterParameter!]
}`),
);
});
it('generates ListOptions for nested list queries', () => {
const input = `
${COMMON_TYPES}
type Query {
people: PersonList
}
type Person {
id: ID!
orders(options: OrderListOptions): OrderList
}
type OrderList implements PaginatedList {
items: [Order!]!
totalItems: Int!
}
type Order {
id: ID!
code: String!
}
# Generated at runtime
input OrderListOptions
`;
const result = generateListOptions(buildSchema(input));
expect(printType(result.getType('OrderListOptions')!)).toBe(
removeLeadingWhitespace(`
input OrderListOptions {
"""Skips the first n results, for use in pagination"""
skip: Int
"""Takes n results, for use in pagination"""
take: Int
"""Specifies which properties to sort the results by"""
sort: OrderSortParameter
"""Allows the results to be filtered"""
filter: OrderFilterParameter
}`),
);
expect(printType(result.getType('OrderSortParameter')!)).toBe(
removeLeadingWhitespace(`
input OrderSortParameter {
id: SortOrder
code: SortOrder
}`),
);
expect(printType(result.getType('OrderFilterParameter')!)).toBe(
removeLeadingWhitespace(`
input OrderFilterParameter {
id: IDOperators
code: StringOperators
_and: [OrderFilterParameter!]
_or: [OrderFilterParameter!]
}`),
);
});
});
|
import { notNullOrUndefined } from '@vendure/common/lib/shared-utils';
import {
buildSchema,
GraphQLEnumType,
GraphQLField,
GraphQLInputField,
GraphQLInputFieldConfig,
GraphQLInputFieldConfigMap,
GraphQLInputObjectType,
GraphQLInputType,
GraphQLInt,
GraphQLList,
GraphQLNamedType,
GraphQLNonNull,
GraphQLObjectType,
GraphQLOutputType,
GraphQLSchema,
isEnumType,
isInputObjectType,
isListType,
isNonNullType,
isObjectType,
// Importing this from graphql/index.js is a workaround for the dual-package
// hazard issue when testing this file in vitest. See https://github.com/vitejs/vite/issues/7879
} from 'graphql/index.js';
// Using require here to prevent issues when running vitest tests also.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { stitchSchemas, ValidationLevel } = require('@graphql-tools/stitch');
/**
* Generates ListOptions inputs for queries which return PaginatedList types.
*/
export function generateListOptions(typeDefsOrSchema: string | GraphQLSchema): GraphQLSchema {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
const queryType = schema.getQueryType();
if (!queryType) {
return schema;
}
const logicalOperatorEnum = schema.getType('LogicalOperator');
const objectTypes = Object.values(schema.getTypeMap()).filter(isObjectType);
const allFields = objectTypes.reduce(
(fields, type) => {
const typeFields = Object.values(type.getFields()).filter(f => isListQueryType(f.type));
return [...fields, ...typeFields];
},
[] as Array<GraphQLField<any, any>>,
);
const generatedTypes: GraphQLNamedType[] = [];
for (const query of allFields) {
const targetTypeName = unwrapNonNullType(query.type).toString().replace(/List$/, '');
const targetType = schema.getType(targetTypeName);
if (targetType && isObjectType(targetType)) {
const sortParameter = createSortParameter(schema, targetType);
const filterParameter = createFilterParameter(schema, targetType);
const existingListOptions = schema.getType(
`${targetTypeName}ListOptions`,
) as GraphQLInputObjectType | null;
const generatedListOptions = new GraphQLInputObjectType({
name: `${targetTypeName}ListOptions`,
fields: {
skip: {
type: GraphQLInt,
description: 'Skips the first n results, for use in pagination',
},
take: { type: GraphQLInt, description: 'Takes n results, for use in pagination' },
sort: {
type: sortParameter,
description: 'Specifies which properties to sort the results by',
},
filter: { type: filterParameter, description: 'Allows the results to be filtered' },
...(logicalOperatorEnum
? {
filterOperator: {
type: logicalOperatorEnum as GraphQLEnumType,
description:
'Specifies whether multiple top-level "filter" fields should be combined ' +
'with a logical AND or OR operation. Defaults to AND.',
},
}
: {}),
...(existingListOptions ? existingListOptions.getFields() : {}),
},
});
if (!query.args.find(a => a.type.toString() === `${targetTypeName}ListOptions`)) {
query.args = [
...query.args,
{
name: 'options',
type: generatedListOptions,
description: null,
defaultValue: null,
extensions: {},
astNode: null,
deprecationReason: null,
},
];
}
generatedTypes.push(filterParameter);
generatedTypes.push(sortParameter);
generatedTypes.push(generatedListOptions);
}
}
return stitchSchemas({
subschemas: [schema],
types: generatedTypes,
typeMergingOptions: { validationSettings: { validationLevel: ValidationLevel.Off } },
});
}
function isListQueryType(type: GraphQLOutputType): type is GraphQLObjectType {
const innerType = unwrapNonNullType(type);
return isObjectType(innerType) && !!innerType.getInterfaces().find(i => i.name === 'PaginatedList');
}
function createSortParameter(schema: GraphQLSchema, targetType: GraphQLObjectType) {
const fields: Array<GraphQLField<any, any> | GraphQLInputField> = Object.values(targetType.getFields());
const targetTypeName = targetType.name;
const SortOrder = schema.getType('SortOrder') as GraphQLEnumType;
const inputName = `${targetTypeName}SortParameter`;
const existingInput = schema.getType(inputName);
if (isInputObjectType(existingInput)) {
fields.push(...Object.values(existingInput.getFields()));
}
const sortableTypes = ['ID', 'String', 'Int', 'Float', 'DateTime', 'Money'];
return new GraphQLInputObjectType({
name: inputName,
fields: fields
.map(field => {
if (unwrapNonNullType(field.type) === SortOrder) {
return field;
} else {
const innerType = unwrapNonNullType(field.type);
if (isListType(innerType)) {
return;
}
return sortableTypes.includes(innerType.name) ? field : undefined;
}
})
.filter(notNullOrUndefined)
.reduce((result, field) => {
const fieldConfig: GraphQLInputFieldConfig = {
type: SortOrder,
};
return {
...result,
[field.name]: fieldConfig,
};
}, {} as GraphQLInputFieldConfigMap),
});
}
function createFilterParameter(schema: GraphQLSchema, targetType: GraphQLObjectType): GraphQLInputObjectType {
const fields: Array<GraphQLField<any, any> | GraphQLInputField> = Object.values(targetType.getFields());
const targetTypeName = targetType.name;
const { StringOperators, BooleanOperators, NumberOperators, DateOperators, IDOperators } =
getCommonTypes(schema);
const inputName = `${targetTypeName}FilterParameter`;
const existingInput = schema.getType(inputName);
if (isInputObjectType(existingInput)) {
fields.push(...Object.values(existingInput.getFields()));
}
function getFilterType(field: GraphQLField<any, any> | GraphQLInputField): GraphQLInputType | undefined {
const innerType = unwrapNonNullType(field.type);
if (isListType(innerType)) {
return;
}
if (isEnumType(innerType)) {
return StringOperators;
}
switch (innerType.name) {
case 'String':
return StringOperators;
case 'Boolean':
return BooleanOperators;
case 'Int':
case 'Float':
case 'Money':
return NumberOperators;
case 'DateTime':
return DateOperators;
case 'ID':
return IDOperators;
default:
return;
}
}
const FilterInputType: GraphQLInputObjectType = new GraphQLInputObjectType({
name: inputName,
fields: () => {
const namedFields = fields.reduce((result, field) => {
const fieldType = field.type;
const filterType = isInputObjectType(fieldType) ? fieldType : getFilterType(field);
if (!filterType) {
return result;
}
const fieldConfig: GraphQLInputFieldConfig = {
type: filterType,
};
return {
...result,
[field.name]: fieldConfig,
};
}, {} as GraphQLInputFieldConfigMap);
return {
...namedFields,
_and: { type: new GraphQLList(new GraphQLNonNull(FilterInputType)) },
_or: { type: new GraphQLList(new GraphQLNonNull(FilterInputType)) },
};
},
});
return FilterInputType;
}
function getCommonTypes(schema: GraphQLSchema) {
const SortOrder = schema.getType('SortOrder') as GraphQLEnumType | null;
const StringOperators = schema.getType('StringOperators') as GraphQLInputType | null;
const BooleanOperators = schema.getType('BooleanOperators') as GraphQLInputType | null;
const NumberRange = schema.getType('NumberRange') as GraphQLInputType | null;
const NumberOperators = schema.getType('NumberOperators') as GraphQLInputType | null;
const DateRange = schema.getType('DateRange') as GraphQLInputType | null;
const DateOperators = schema.getType('DateOperators') as GraphQLInputType | null;
const IDOperators = schema.getType('IDOperators') as GraphQLInputType | null;
if (
!SortOrder ||
!StringOperators ||
!BooleanOperators ||
!NumberRange ||
!NumberOperators ||
!DateRange ||
!DateOperators ||
!IDOperators
) {
throw new Error('A common type was not defined');
}
return {
SortOrder,
StringOperators,
BooleanOperators,
NumberOperators,
DateOperators,
IDOperators,
};
}
/**
* Unwraps the inner type if it is inside a non-nullable type
*/
function unwrapNonNullType(
type: GraphQLOutputType | GraphQLInputType,
): GraphQLNamedType | GraphQLList<GraphQLOutputType | GraphQLInputType> {
if (isNonNullType(type)) {
return type.ofType;
}
return type;
}
|
import { stitchSchemas, ValidationLevel } from '@graphql-tools/stitch';
import { GraphQLEnumType, GraphQLSchema } from 'graphql';
import { GraphQLEnumValueConfigMap } from 'graphql/type/definition';
import { getAllPermissionsMetadata } from '../../common/constants';
import { PermissionDefinition } from '../../common/permission-definition';
const PERMISSION_DESCRIPTION = `@description
Permissions for administrators and customers. Used to control access to
GraphQL resolvers via the {@link Allow} decorator.
## Understanding Permission.Owner
\`Permission.Owner\` is a special permission which is used in some Vendure resolvers to indicate that that resolver should only
be accessible to the "owner" of that resource.
For example, the Shop API \`activeCustomer\` query resolver should only return the Customer object for the "owner" of that Customer, i.e.
based on the activeUserId of the current session. As a result, the resolver code looks like this:
@example
\`\`\`TypeScript
\\@Query()
\\@Allow(Permission.Owner)
async activeCustomer(\\@Ctx() ctx: RequestContext): Promise<Customer | undefined> {
const userId = ctx.activeUserId;
if (userId) {
return this.customerService.findOneByUserId(ctx, userId);
}
}
\`\`\`
Here we can see that the "ownership" must be enforced by custom logic inside the resolver. Since "ownership" cannot be defined generally
nor statically encoded at build-time, any resolvers using \`Permission.Owner\` **must** include logic to enforce that only the owner
of the resource has access. If not, then it is the equivalent of using \`Permission.Public\`.
@docsCategory common`;
/**
* Generates the `Permission` GraphQL enum based on the default & custom permission definitions.
*/
export function generatePermissionEnum(
schema: GraphQLSchema,
customPermissions: PermissionDefinition[],
): GraphQLSchema {
const allPermissionsMetadata = getAllPermissionsMetadata(customPermissions);
const values: GraphQLEnumValueConfigMap = {};
let i = 0;
for (const entry of allPermissionsMetadata) {
values[entry.name] = {
value: i,
description: entry.description,
};
i++;
}
const permissionsEnum = new GraphQLEnumType({
name: 'Permission',
description: PERMISSION_DESCRIPTION,
values,
});
return stitchSchemas({
subschemas: [schema],
types: [permissionsEnum],
typeMergingOptions: { validationSettings: { validationLevel: ValidationLevel.Off } },
});
}
|
import { IFieldResolver, IResolvers } from '@graphql-tools/utils';
import { StockMovementType } from '@vendure/common/lib/generated-types';
import { GraphQLSchema } from 'graphql';
import { GraphQLDateTime, GraphQLJSON } from 'graphql-scalars';
import { REQUEST_CONTEXT_KEY } from '../../common/constants';
import { InternalServerError } from '../../common/error/errors';
import {
adminErrorOperationTypeResolvers,
ErrorResult,
} from '../../common/error/generated-graphql-admin-errors';
import { shopErrorOperationTypeResolvers } from '../../common/error/generated-graphql-shop-errors';
import { Translatable } from '../../common/types/locale-types';
import { ConfigService } from '../../config/config.service';
import { CustomFieldConfig, RelationCustomFieldConfig } from '../../config/custom-field/custom-field-types';
import { Logger } from '../../config/logger/vendure-logger';
import { Region } from '../../entity/region/region.entity';
import { getPluginAPIExtensions } from '../../plugin/plugin-metadata';
import { CustomFieldRelationResolverService } from '../common/custom-field-relation-resolver.service';
import { ApiType } from '../common/get-api-type';
import { RequestContext } from '../common/request-context';
import { userHasPermissionsOnCustomField } from '../common/user-has-permissions-on-custom-field';
import { getCustomFieldsConfigWithoutInterfaces } from './get-custom-fields-config-without-interfaces';
import { GraphQLMoney } from './money-scalar';
/**
* @description
* Generates additional resolvers required for things like resolution of union types,
* custom scalars and "relation"-type custom fields.
*/
export async function generateResolvers(
configService: ConfigService,
customFieldRelationResolverService: CustomFieldRelationResolverService,
apiType: ApiType,
schema: GraphQLSchema,
) {
// Prevent `Type "Node" is missing a "resolveType" resolver.` warnings.
// See https://github.com/apollographql/apollo-server/issues/1075
const dummyResolveType = {
__resolveType() {
return null;
},
};
const stockMovementResolveType = {
__resolveType(value: any) {
switch (value.type) {
case StockMovementType.ADJUSTMENT:
return 'StockAdjustment';
case StockMovementType.ALLOCATION:
return 'Allocation';
case StockMovementType.SALE:
return 'Sale';
case StockMovementType.CANCELLATION:
return 'Cancellation';
case StockMovementType.RETURN:
return 'Return';
case StockMovementType.RELEASE:
return 'Release';
}
},
};
const regionResolveType = {
__resolveType(value: Region) {
switch (value.type) {
case 'country':
return 'Country';
case 'province':
return 'Province';
default: {
throw new InternalServerError(`No __resolveType defined for Region type "${value.type}"`);
}
}
},
};
const customFieldsConfigResolveType = {
__resolveType(value: any) {
switch (value.type) {
case 'string':
return 'StringCustomFieldConfig';
case 'localeString':
return 'LocaleStringCustomFieldConfig';
case 'text':
return 'TextCustomFieldConfig';
case 'localeText':
return 'LocaleTextCustomFieldConfig';
case 'int':
return 'IntCustomFieldConfig';
case 'float':
return 'FloatCustomFieldConfig';
case 'boolean':
return 'BooleanCustomFieldConfig';
case 'datetime':
return 'DateTimeCustomFieldConfig';
case 'relation':
return 'RelationCustomFieldConfig';
}
},
};
// @ts-ignore
const { default: GraphQLUpload } = await import('graphql-upload/GraphQLUpload.mjs');
const commonResolvers = {
JSON: GraphQLJSON,
DateTime: GraphQLDateTime,
Money: GraphQLMoney,
Node: dummyResolveType,
PaginatedList: dummyResolveType,
Upload: GraphQLUpload || dummyResolveType,
SearchResultPrice: {
__resolveType(value: any) {
return value.hasOwnProperty('value') ? 'SinglePrice' : 'PriceRange';
},
},
CustomFieldConfig: customFieldsConfigResolveType,
CustomField: customFieldsConfigResolveType,
ErrorResult: {
__resolveType(value: ErrorResult) {
return value.__typename;
},
},
Region: regionResolveType,
};
const customFieldRelationResolvers = generateCustomFieldRelationResolvers(
configService,
customFieldRelationResolverService,
schema,
);
const adminResolvers = {
StockMovementItem: stockMovementResolveType,
StockMovement: stockMovementResolveType,
...adminErrorOperationTypeResolvers,
...customFieldRelationResolvers.adminResolvers,
};
const shopResolvers = {
...shopErrorOperationTypeResolvers,
...customFieldRelationResolvers.shopResolvers,
};
const resolvers =
apiType === 'admin'
? { ...commonResolvers, ...adminResolvers, ...getCustomScalars(configService, 'admin') }
: { ...commonResolvers, ...shopResolvers, ...getCustomScalars(configService, 'shop') };
return resolvers;
}
/**
* @description
* Based on the CustomFields config, this function dynamically creates resolver functions to perform
* a DB query to fetch the related entity for any custom fields of type "relation".
*/
function generateCustomFieldRelationResolvers(
configService: ConfigService,
customFieldRelationResolverService: CustomFieldRelationResolverService,
schema: GraphQLSchema,
) {
const ENTITY_ID_KEY = '__entityId__';
const adminResolvers: IResolvers = {};
const shopResolvers: IResolvers = {};
const customFieldsConfig = getCustomFieldsConfigWithoutInterfaces(configService.customFields, schema);
for (const [entityName, customFields] of customFieldsConfig) {
if (!schema.getType(entityName)) {
continue;
}
const customFieldTypeName = `${entityName}CustomFields`;
// Some types are not exposed in the Shop API and therefore defining resolvers
// for them would lead to an Apollo error on bootstrap.
const excludeFromShopApi = ['GlobalSettings'].includes(entityName);
// In order to resolve the relations in the CustomFields type, we need
// access to the entity id. Therefore, we attach it to the resolved value
// so that it is available to the `relationResolver` below.
const customFieldResolver: IFieldResolver<any, any> = (source: any) => {
return {
...source.customFields,
[ENTITY_ID_KEY]: source.id,
};
};
const resolverObject = {
customFields: customFieldResolver,
};
adminResolvers[entityName] = resolverObject;
if (!excludeFromShopApi) {
shopResolvers[entityName] = resolverObject;
if (entityName === 'ShippingMethod') {
shopResolvers.ShippingMethodQuote = resolverObject;
}
if (entityName === 'PaymentMethod') {
shopResolvers.PaymentMethodQuote = resolverObject;
}
}
for (const fieldDef of customFields) {
if (fieldDef.internal === true) {
// Do not create any resolvers for internal relations
continue;
}
let resolver: IFieldResolver<any, any>;
if (isRelationalType(fieldDef)) {
resolver = async (source: any, args: any, context: any) => {
const ctx: RequestContext = context.req[REQUEST_CONTEXT_KEY];
if (!userHasPermissionsOnCustomField(ctx, fieldDef)) {
return null;
}
const eagerEntity = source[fieldDef.name];
// If the relation is eager-loaded, we can simply try to translate this relation entity if they have translations
if (eagerEntity != null) {
try {
return await customFieldRelationResolverService.translateEntity(
ctx,
eagerEntity,
fieldDef,
);
} catch (e: any) {
Logger.debug(
`Error resolving eager-loaded custom field entity relation "${entityName}.${fieldDef.name}": ${e.message as string}`,
);
}
}
const entityId = source[ENTITY_ID_KEY];
return customFieldRelationResolverService.resolveRelation({
ctx,
fieldDef,
entityName,
entityId,
});
};
} else {
resolver = async (source: any, args: any, context: any) => {
const ctx: RequestContext = context.req[REQUEST_CONTEXT_KEY];
if (!userHasPermissionsOnCustomField(ctx, fieldDef)) {
return null;
}
return source[fieldDef.name];
};
}
adminResolvers[customFieldTypeName] = {
...adminResolvers[customFieldTypeName],
[fieldDef.name]: resolver,
} as any;
if (fieldDef.public !== false && !excludeFromShopApi) {
shopResolvers[customFieldTypeName] = {
...shopResolvers[customFieldTypeName],
[fieldDef.name]: resolver,
} as any;
}
}
}
return { adminResolvers, shopResolvers };
}
function getCustomScalars(configService: ConfigService, apiType: 'admin' | 'shop') {
return getPluginAPIExtensions(configService.plugins, apiType)
.map(e => (typeof e.scalars === 'function' ? e.scalars() : e.scalars ?? {}))
.reduce(
(all, scalarMap) => ({
...all,
...scalarMap,
}),
{},
);
}
function isRelationalType(input: CustomFieldConfig): input is RelationCustomFieldConfig {
return input.type === 'relation';
}
function isTranslatable(input: unknown): input is Translatable {
return typeof input === 'object' && input != null && input.hasOwnProperty('translations');
}
|
import { GraphQLSchema, isInterfaceType } from 'graphql';
import { CustomFieldConfig, CustomFields } from '../../config/custom-field/custom-field-types';
/**
* @description
* Because the "Region" entity is an interface, it cannot be extended directly, so we need to
* replace it if found in the custom field config with its concrete implementations.
*/
export function getCustomFieldsConfigWithoutInterfaces(
customFieldConfig: CustomFields,
schema: GraphQLSchema,
): Array<[entityName: string, config: CustomFieldConfig[]]> {
const entries = Object.entries(customFieldConfig);
const regionIndex = entries.findIndex(([name]) => name === 'Region');
if (regionIndex !== -1) {
// Region is an interface and cannot directly be extended. Instead, we will use the
// concrete types that implement it.
const regionType = schema.getType('Region');
if (isInterfaceType(regionType)) {
const implementations = schema.getImplementations(regionType);
// Remove "Region" from the list of entities to which custom fields can be added
entries.splice(regionIndex, 1);
for (const implementation of implementations.objects) {
entries.push([implementation.name, customFieldConfig.Region ?? []]);
}
}
}
return entries;
}
|
import { printSchema } from 'graphql';
import { describe, expect, it } from 'vitest';
import { CustomFieldConfig, CustomFields } from '../../config/custom-field/custom-field-types';
import {
addGraphQLCustomFields,
addOrderLineCustomFieldsInput,
addRegisterCustomerCustomFieldsInput,
} from './graphql-custom-fields';
describe('addGraphQLCustomFields()', () => {
it('uses JSON scalar if no custom fields defined', () => {
const input = `
type Product {
id: ID
}
`;
const customFieldConfig: CustomFields = {
Product: [],
};
const result = addGraphQLCustomFields(input, customFieldConfig, false);
expect(printSchema(result)).toMatchSnapshot();
});
it('extends a type', () => {
const input = `
type Product {
id: ID
}
`;
const customFieldConfig: CustomFields = {
Product: [{ name: 'available', type: 'boolean' }],
};
const result = addGraphQLCustomFields(input, customFieldConfig, false);
expect(printSchema(result)).toMatchSnapshot();
});
it('extends a type with a translation', () => {
const input = `
type Product {
id: ID
translations: [ProductTranslation!]!
}
type ProductTranslation {
id: ID
}
`;
const customFieldConfig: CustomFields = {
Product: [
{ name: 'available', type: 'boolean' },
{ name: 'shortName', type: 'localeString' },
],
};
const result = addGraphQLCustomFields(input, customFieldConfig, false);
expect(printSchema(result)).toMatchSnapshot();
});
it('extends a type with a Create input', () => {
const input = `
type Product {
id: ID
}
input CreateProductInput {
image: String
}
`;
const customFieldConfig: CustomFields = {
Product: [
{ name: 'available', type: 'boolean' },
{ name: 'shortName', type: 'localeString' },
],
};
const result = addGraphQLCustomFields(input, customFieldConfig, false);
expect(printSchema(result)).toMatchSnapshot();
});
it('extends a type with an Update input', () => {
const input = `
type Product {
id: ID
}
input UpdateProductInput {
image: String
}
`;
const customFieldConfig: CustomFields = {
Product: [
{ name: 'available', type: 'boolean' },
{ name: 'shortName', type: 'localeString' },
],
};
const result = addGraphQLCustomFields(input, customFieldConfig, false);
expect(printSchema(result)).toMatchSnapshot();
});
it('extends a type with a Create input and a translation', () => {
const input = `
type Product {
id: ID
}
type ProductTranslation {
id: ID
}
input ProductTranslationInput {
id: ID
}
input CreateProductInput {
image: String
}
`;
const customFieldConfig: CustomFields = {
Product: [
{ name: 'available', type: 'boolean' },
{ name: 'shortName', type: 'localeString' },
],
};
const result = addGraphQLCustomFields(input, customFieldConfig, false);
expect(printSchema(result)).toMatchSnapshot();
});
it('extends a type with SortParameters', () => {
const input = `
type Product {
id: ID
}
input ProductSortParameter {
id: SortOrder
}
enum SortOrder {
ASC
DESC
}
`;
const customFieldConfig: CustomFields = {
Product: [
{ name: 'available', type: 'boolean' },
{ name: 'shortName', type: 'localeString' },
],
};
const result = addGraphQLCustomFields(input, customFieldConfig, false);
expect(printSchema(result)).toMatchSnapshot();
});
it('extends a type with FilterParameters', () => {
const input = `
type Product {
name: String
}
input ProductFilterParameter {
id: StringOperators
}
input StringOperators {
eq: String
}
input NumberOperators {
eq: Float
}
input DateOperators {
eq: String
}
input BooleanOperators {
eq: Boolean
}
`;
const customFieldConfig: CustomFields = {
Product: [
{ name: 'available', type: 'boolean' },
{ name: 'shortName', type: 'localeString' },
{ name: 'rating', type: 'float' },
{ name: 'published', type: 'datetime' },
],
};
const result = addGraphQLCustomFields(input, customFieldConfig, false);
expect(printSchema(result)).toMatchSnapshot();
});
it('publicOnly = true', () => {
const input = `
type Product {
id: ID
}
`;
const customFieldConfig: CustomFields = {
Product: [
{ name: 'available', type: 'boolean', public: true },
{ name: 'profitMargin', type: 'float', public: false },
],
};
const result = addGraphQLCustomFields(input, customFieldConfig, true);
expect(printSchema(result)).toMatchSnapshot();
});
it('extends OrderAddress if Address custom fields defined', () => {
const input = `
type Address {
id: ID
streetLine1: String
}
type OrderAddress {
streetLine1: String
}
`;
const customFieldConfig: CustomFields = {
Address: [{ name: 'instructions', type: 'string' }],
};
const result = addGraphQLCustomFields(input, customFieldConfig, true);
expect(printSchema(result)).toMatchSnapshot();
});
});
describe('addOrderLineCustomFieldsInput()', () => {
it('Modifies the schema when the addItemToOrder & adjustOrderLine mutation is present', () => {
const input = `
type Mutation {
addItemToOrder(id: ID!, quantity: Int!): Boolean
adjustOrderLine(id: ID!, quantity: Int): Boolean
}
`;
const customFieldConfig: CustomFieldConfig[] = [
{ name: 'giftWrap', type: 'boolean' },
{ name: 'message', type: 'string' },
];
const result = addOrderLineCustomFieldsInput(input, customFieldConfig);
expect(printSchema(result)).toMatchSnapshot();
});
});
describe('addRegisterCustomerCustomFieldsInput()', () => {
it('add public writable custom fields to RegisterCustomerInput', () => {
const input = `
input RegisterCustomerInput {
emailAddress: String!
title: String
firstName: String
lastName: String
phoneNumber: String
password: String
}
type Mutation {
registerCustomerAccount(input: RegisterCustomerInput!): Boolean!
}
`;
const customFieldConfig: CustomFieldConfig[] = [
{ name: 'isB2B', type: 'boolean', nullable: false },
{ name: 'message', type: 'string' },
{ name: 'rating', type: 'int', public: false },
{ name: 'dbRef', type: 'int', internal: true },
];
const result = addRegisterCustomerCustomFieldsInput(input, customFieldConfig);
expect(printSchema(result)).toMatchSnapshot();
});
});
|
import { assertNever, getGraphQlInputName } from '@vendure/common/lib/shared-utils';
import {
buildSchema,
extendSchema,
GraphQLInputObjectType,
GraphQLList,
GraphQLSchema,
parse,
} from 'graphql';
import { CustomFieldConfig, CustomFields } from '../../config/custom-field/custom-field-types';
import { Logger } from '../../config/logger/vendure-logger';
import { getCustomFieldsConfigWithoutInterfaces } from './get-custom-fields-config-without-interfaces';
/**
* Given a CustomFields config object, generates an SDL string extending the built-in
* types with a customFields property for all entities, translations and inputs for which
* custom fields are defined.
*/
export function addGraphQLCustomFields(
typeDefsOrSchema: string | GraphQLSchema,
customFieldConfig: CustomFields,
publicOnly: boolean,
): GraphQLSchema {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
let customFieldTypeDefs = '';
if (!schema.getType('JSON')) {
customFieldTypeDefs += `
scalar JSON
`;
}
if (!schema.getType('DateTime')) {
customFieldTypeDefs += `
scalar DateTime
`;
}
const customFieldsConfig = getCustomFieldsConfigWithoutInterfaces(customFieldConfig, schema);
for (const [entityName, customFields] of customFieldsConfig) {
const customEntityFields = customFields.filter(config => {
return !config.internal && (publicOnly === true ? config.public !== false : true);
});
for (const fieldDef of customEntityFields) {
if (fieldDef.type === 'relation') {
const graphQlTypeName = fieldDef.graphQLType || fieldDef.entity.name;
if (!schema.getType(graphQlTypeName)) {
const customFieldPath = `${entityName}.${fieldDef.name}`;
const errorMessage = `The GraphQL type "${
graphQlTypeName ?? '(unknown)'
}" specified by the ${customFieldPath} custom field does not exist in the ${publicOnly ? 'Shop API' : 'Admin API'} schema.`;
Logger.warn(errorMessage);
if (publicOnly) {
Logger.warn(
[
`This can be resolved by either:`,
` - setting \`public: false\` in the ${customFieldPath} custom field config`,
` - defining the "${graphQlTypeName}" type in the Shop API schema`,
].join('\n'),
);
}
throw new Error(errorMessage);
}
}
}
const localizedFields = customEntityFields.filter(
field => field.type === 'localeString' || field.type === 'localeText',
);
const nonLocalizedFields = customEntityFields.filter(
field => field.type !== 'localeString' && field.type !== 'localeText',
);
const writeableLocalizedFields = localizedFields.filter(field => !field.readonly);
const writeableNonLocalizedFields = nonLocalizedFields.filter(field => !field.readonly);
const filterableFields = customEntityFields.filter(field => field.type !== 'relation');
if (schema.getType(entityName)) {
if (customEntityFields.length) {
customFieldTypeDefs += `
type ${entityName}CustomFields {
${mapToFields(customEntityFields, wrapListType(getGraphQlType))}
}
extend type ${entityName} {
customFields: ${entityName}CustomFields
}
`;
} else {
customFieldTypeDefs += `
extend type ${entityName} {
customFields: JSON
}
`;
}
}
if (localizedFields.length && schema.getType(`${entityName}Translation`)) {
customFieldTypeDefs += `
type ${entityName}TranslationCustomFields {
${mapToFields(localizedFields, wrapListType(getGraphQlType))}
}
extend type ${entityName}Translation {
customFields: ${entityName}TranslationCustomFields
}
`;
}
if (schema.getType(`Create${entityName}Input`)) {
if (writeableNonLocalizedFields.length) {
customFieldTypeDefs += `
input Create${entityName}CustomFieldsInput {
${mapToFields(
writeableNonLocalizedFields,
wrapListType(getGraphQlInputType),
getGraphQlInputName,
)}
}
extend input Create${entityName}Input {
customFields: Create${entityName}CustomFieldsInput
}
`;
} else {
customFieldTypeDefs += `
extend input Create${entityName}Input {
customFields: JSON
}
`;
}
}
if (schema.getType(`Update${entityName}Input`)) {
if (writeableNonLocalizedFields.length) {
customFieldTypeDefs += `
input Update${entityName}CustomFieldsInput {
${mapToFields(
writeableNonLocalizedFields,
wrapListType(getGraphQlInputType),
getGraphQlInputName,
)}
}
extend input Update${entityName}Input {
customFields: Update${entityName}CustomFieldsInput
}
`;
} else {
customFieldTypeDefs += `
extend input Update${entityName}Input {
customFields: JSON
}
`;
}
}
const customEntityNonListFields = customEntityFields.filter(f => f.list !== true);
if (customEntityNonListFields.length && schema.getType(`${entityName}SortParameter`)) {
// Sorting list fields makes no sense, so we only add "sort" fields
// to non-list fields.
customFieldTypeDefs += `
extend input ${entityName}SortParameter {
${mapToFields(customEntityNonListFields, () => 'SortOrder')}
}
`;
}
if (filterableFields.length && schema.getType(`${entityName}FilterParameter`)) {
customFieldTypeDefs += `
extend input ${entityName}FilterParameter {
${mapToFields(filterableFields, getFilterOperator)}
}
`;
}
if (writeableLocalizedFields) {
const translationInputs = [
`${entityName}TranslationInput`,
`Create${entityName}TranslationInput`,
`Update${entityName}TranslationInput`,
];
for (const inputName of translationInputs) {
if (schema.getType(inputName)) {
if (writeableLocalizedFields.length) {
customFieldTypeDefs += `
input ${inputName}CustomFields {
${mapToFields(writeableLocalizedFields, wrapListType(getGraphQlType))}
}
extend input ${inputName} {
customFields: ${inputName}CustomFields
}
`;
} else {
customFieldTypeDefs += `
extend input ${inputName} {
customFields: JSON
}
`;
}
}
}
}
}
const publicAddressFields = customFieldConfig.Address?.filter(
config => !config.internal && (publicOnly === true ? config.public !== false : true),
);
if (publicAddressFields?.length) {
// For custom fields on the Address entity, we also extend the OrderAddress
// type (which is used to store address snapshots on Orders)
if (schema.getType('OrderAddress')) {
customFieldTypeDefs += `
extend type OrderAddress {
customFields: AddressCustomFields
}
`;
}
if (schema.getType('UpdateOrderAddressInput')) {
customFieldTypeDefs += `
extend input UpdateOrderAddressInput {
customFields: UpdateAddressCustomFieldsInput
}
`;
}
} else {
if (schema.getType('OrderAddress')) {
customFieldTypeDefs += `
extend type OrderAddress {
customFields: JSON
}
`;
}
}
return extendSchema(schema, parse(customFieldTypeDefs));
}
export function addServerConfigCustomFields(
typeDefsOrSchema: string | GraphQLSchema,
customFieldConfig: CustomFields,
) {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
const customFieldTypeDefs = `
"""
This type is deprecated in v2.2 in favor of the EntityCustomFields type,
which allows custom fields to be defined on user-supplies entities.
"""
type CustomFields {
${Object.keys(customFieldConfig).reduce(
(output, name) => output + name + ': [CustomFieldConfig!]!\n',
'',
)}
}
type EntityCustomFields {
entityName: String!
customFields: [CustomFieldConfig!]!
}
extend type ServerConfig {
"""
This field is deprecated in v2.2 in favor of the entityCustomFields field,
which allows custom fields to be defined on user-supplies entities.
"""
customFieldConfig: CustomFields!
entityCustomFields: [EntityCustomFields!]!
}
`;
return extendSchema(schema, parse(customFieldTypeDefs));
}
export function addActiveAdministratorCustomFields(
typeDefsOrSchema: string | GraphQLSchema,
administratorCustomFields: CustomFieldConfig[],
) {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
const writableCustomFields = administratorCustomFields?.filter(field => field.readonly !== true);
const extension = `
extend input UpdateActiveAdministratorInput {
customFields: ${
0 < writableCustomFields?.length ? 'UpdateAdministratorCustomFieldsInput' : 'JSON'
}
}
`;
return extendSchema(schema, parse(extension));
}
/**
* If CustomFields are defined on the Customer entity, then an extra `customFields` field is added to
* the `RegisterCustomerInput` so that public writable custom fields can be set when a new customer
* is registered.
*/
export function addRegisterCustomerCustomFieldsInput(
typeDefsOrSchema: string | GraphQLSchema,
customerCustomFields: CustomFieldConfig[],
): GraphQLSchema {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
if (!customerCustomFields || customerCustomFields.length === 0) {
return schema;
}
const publicWritableCustomFields = customerCustomFields.filter(fieldDef => {
return fieldDef.public !== false && !fieldDef.readonly && !fieldDef.internal;
});
if (publicWritableCustomFields.length < 1) {
return schema;
}
const customFieldTypeDefs = `
input RegisterCustomerCustomFieldsInput {
${mapToFields(publicWritableCustomFields, wrapListType(getGraphQlInputType), getGraphQlInputName)}
}
extend input RegisterCustomerInput {
customFields: RegisterCustomerCustomFieldsInput
}
`;
return extendSchema(schema, parse(customFieldTypeDefs));
}
/**
* If CustomFields are defined on the Order entity, we add a `customFields` field to the ModifyOrderInput
* type.
*/
export function addModifyOrderCustomFields(
typeDefsOrSchema: string | GraphQLSchema,
orderCustomFields: CustomFieldConfig[],
): GraphQLSchema {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
if (!orderCustomFields || orderCustomFields.length === 0) {
return schema;
}
if (schema.getType('ModifyOrderInput') && schema.getType('UpdateOrderCustomFieldsInput')) {
const customFieldTypeDefs = `
extend input ModifyOrderInput {
customFields: UpdateOrderCustomFieldsInput
}
`;
return extendSchema(schema, parse(customFieldTypeDefs));
}
return schema;
}
/**
* If CustomFields are defined on the OrderLine entity, then an extra `customFields` argument
* must be added to the `addItemToOrder` and `adjustOrderLine` mutations, as well as the related
* fields in the `ModifyOrderInput` type.
*/
export function addOrderLineCustomFieldsInput(
typeDefsOrSchema: string | GraphQLSchema,
orderLineCustomFields: CustomFieldConfig[],
): GraphQLSchema {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
const publicCustomFields = orderLineCustomFields.filter(f => f.public !== false);
if (!publicCustomFields || publicCustomFields.length === 0) {
return schema;
}
const schemaConfig = schema.toConfig();
const mutationType = schemaConfig.mutation;
if (!mutationType) {
return schema;
}
const input = new GraphQLInputObjectType({
name: 'OrderLineCustomFieldsInput',
fields: publicCustomFields.reduce((fields, field) => {
const name = getGraphQlInputName(field);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const primitiveType = schema.getType(getGraphQlInputType(field))!;
const type = field.list === true ? new GraphQLList(primitiveType) : primitiveType;
return { ...fields, [name]: { type } };
}, {}),
});
schemaConfig.types = [...schemaConfig.types, input];
const addItemToOrderMutation = mutationType.getFields().addItemToOrder;
const adjustOrderLineMutation = mutationType.getFields().adjustOrderLine;
if (addItemToOrderMutation) {
addItemToOrderMutation.args = [
...addItemToOrderMutation.args,
{
name: 'customFields',
type: input,
description: null,
defaultValue: null,
extensions: {},
astNode: null,
deprecationReason: null,
},
];
}
if (adjustOrderLineMutation) {
adjustOrderLineMutation.args = [
...adjustOrderLineMutation.args,
{
name: 'customFields',
type: input,
description: null,
defaultValue: null,
extensions: {},
astNode: null,
deprecationReason: null,
},
];
}
let extendedSchema = new GraphQLSchema(schemaConfig);
if (schema.getType('AddItemInput')) {
const customFieldTypeDefs = `
extend input AddItemInput {
customFields: OrderLineCustomFieldsInput
}
`;
extendedSchema = extendSchema(extendedSchema, parse(customFieldTypeDefs));
}
if (schema.getType('OrderLineInput')) {
const customFieldTypeDefs = `
extend input OrderLineInput {
customFields: OrderLineCustomFieldsInput
}
`;
extendedSchema = extendSchema(extendedSchema, parse(customFieldTypeDefs));
}
if (schema.getType('AddItemToDraftOrderInput')) {
const customFieldTypeDefs = `
extend input AddItemToDraftOrderInput {
customFields: OrderLineCustomFieldsInput
}
`;
extendedSchema = extendSchema(extendedSchema, parse(customFieldTypeDefs));
}
if (schema.getType('AdjustDraftOrderLineInput')) {
const customFieldTypeDefs = `
extend input AdjustDraftOrderLineInput {
customFields: OrderLineCustomFieldsInput
}
`;
extendedSchema = extendSchema(extendedSchema, parse(customFieldTypeDefs));
}
return extendedSchema;
}
export function addShippingMethodQuoteCustomFields(
typeDefsOrSchema: string | GraphQLSchema,
shippingMethodCustomFields: CustomFieldConfig[],
) {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
let customFieldTypeDefs = '';
const publicCustomFields = shippingMethodCustomFields.filter(f => f.public !== false);
if (0 < publicCustomFields.length) {
customFieldTypeDefs = `
extend type ShippingMethodQuote {
customFields: ShippingMethodCustomFields
}
`;
} else {
customFieldTypeDefs = `
extend type ShippingMethodQuote {
customFields: JSON
}
`;
}
return extendSchema(schema, parse(customFieldTypeDefs));
}
export function addPaymentMethodQuoteCustomFields(
typeDefsOrSchema: string | GraphQLSchema,
paymentMethodCustomFields: CustomFieldConfig[],
) {
const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
let customFieldTypeDefs = '';
const publicCustomFields = paymentMethodCustomFields.filter(f => f.public !== false);
if (0 < publicCustomFields.length) {
customFieldTypeDefs = `
extend type PaymentMethodQuote {
customFields: PaymentMethodCustomFields
}
`;
} else {
customFieldTypeDefs = `
extend type PaymentMethodQuote {
customFields: JSON
}
`;
}
return extendSchema(schema, parse(customFieldTypeDefs));
}
/**
* Maps an array of CustomFieldConfig objects into a string of SDL fields.
*/
function mapToFields(
fieldDefs: CustomFieldConfig[],
typeFn: (def: CustomFieldConfig) => string | undefined,
nameFn?: (def: Pick<CustomFieldConfig, 'name' | 'type' | 'list'>) => string,
): string {
const res = fieldDefs
.map(field => {
const type = typeFn(field);
if (!type) {
return;
}
const name = nameFn ? nameFn(field) : field.name;
return `${name}: ${type}`;
})
.filter(x => x != null);
return res.join('\n');
}
function getFilterOperator(config: CustomFieldConfig): string | undefined {
switch (config.type) {
case 'datetime':
return config.list ? 'DateListOperators' : 'DateOperators';
case 'string':
case 'localeString':
case 'text':
case 'localeText':
return config.list ? 'StringListOperators' : 'StringOperators';
case 'boolean':
return config.list ? 'BooleanListOperators' : 'BooleanOperators';
case 'int':
case 'float':
return config.list ? 'NumberListOperators' : 'NumberOperators';
case 'relation':
return undefined;
default:
assertNever(config);
}
return 'String';
}
function getGraphQlInputType(config: CustomFieldConfig): string {
return config.type === 'relation' ? 'ID' : getGraphQlType(config);
}
function wrapListType(
getTypeFn: (def: CustomFieldConfig) => string | undefined,
): (def: CustomFieldConfig) => string | undefined {
return (def: CustomFieldConfig) => {
const type = getTypeFn(def);
if (!type) {
return;
}
return def.list ? `[${type}!]` : type;
};
}
function getGraphQlType(config: CustomFieldConfig): string {
switch (config.type) {
case 'string':
case 'localeString':
case 'text':
case 'localeText':
return 'String';
case 'datetime':
return 'DateTime';
case 'boolean':
return 'Boolean';
case 'int':
return 'Int';
case 'float':
return 'Float';
case 'relation':
return config.graphQLType || config.entity.name;
default:
assertNever(config);
}
return 'String';
}
|
import { GraphQLError, GraphQLScalarType, Kind, print } from 'graphql';
import { inspect } from 'graphql/jsutils/inspect';
export function isObjectLike(value: unknown): value is { [key: string]: unknown } {
// eslint-disable-next-line eqeqeq
return typeof value == 'object' && value !== null;
}
// Support serializing objects with custom valueOf() or toJSON() functions -
// a common way to represent a complex value which can be represented as
// a string (ex: MongoDB id objects).
function serializeObject(outputValue: unknown): unknown {
if (isObjectLike(outputValue)) {
if (typeof outputValue.valueOf === 'function') {
const valueOfResult = outputValue.valueOf();
if (!isObjectLike(valueOfResult)) {
return valueOfResult;
}
}
if (typeof outputValue.toJSON === 'function') {
return outputValue.toJSON();
}
}
return outputValue;
}
/**
* @description
* The Money scalar is used to represent monetary values in the GraphQL API. It is based on the native `Float` scalar.
*/
export const GraphQLMoney = new GraphQLScalarType<number>({
name: 'Money',
description:
'The `Money` scalar type represents monetary values and supports signed double-precision ' +
'fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).',
serialize(outputValue) {
const coercedValue = serializeObject(outputValue);
if (typeof coercedValue === 'boolean') {
return coercedValue ? 1 : 0;
}
let num = coercedValue;
if (typeof coercedValue === 'string' && coercedValue !== '') {
num = Number(coercedValue);
}
if (typeof num !== 'number' || !Number.isFinite(num)) {
throw new GraphQLError(`Money cannot represent non numeric value: ${inspect(coercedValue)}`);
}
return num;
},
parseValue(inputValue) {
if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) {
throw new GraphQLError(`Money cannot represent non numeric value: ${inspect(inputValue)}`);
}
return inputValue;
},
parseLiteral(valueNode) {
if (valueNode.kind !== Kind.FLOAT && valueNode.kind !== Kind.INT) {
throw new GraphQLError(`Money cannot represent non numeric value: ${print(valueNode)}`, {
nodes: valueNode,
});
}
return parseFloat(valueNode.value);
},
extensions: {
codegenScalarType: 'number',
jsonSchema: {
title: 'Money',
type: 'number',
minimum: Number.MIN_SAFE_INTEGER,
maximum: Number.MAX_SAFE_INTEGER,
},
},
});
|
import { SetMetadata } from '@nestjs/common';
import { Permission } from '@vendure/common/lib/generated-types';
export const PERMISSIONS_METADATA_KEY = '__permissions__';
/**
* @description
* Attaches metadata to the resolver defining which permissions are required to execute the
* operation, using one or more {@link Permission} values.
*
* In a GraphQL context, it can be applied to top-level queries and mutations as well as field resolvers.
*
* For REST controllers, it can be applied to route handler.
*
* ## Allow and Sessions
* The `@Allow()` decorator is closely linked to the way Vendure manages sessions. For any operation or route that is decorated
* with `@Allow()`, there must be an authenticated session in progress, which would have been created during a prior authentication
* step.
*
* The exception to this is when the operation is decorated with `@Allow(Permission.Owner)`. This is a special permission which is designed
* to give access to certain resources to potentially un-authenticated users. For this reason, any operation decorated with this permission
* will always have an anonymous session created if no session is currently in progress.
*
* For more information see [Understanding Permission.Owner](/reference/typescript-api/common/permission/#understanding-permissionowner).
*
* @example
* ```ts
* \@Allow(Permission.SuperAdmin)
* \@Query()
* getAdministrators() {
* // ...
* }
* ```
*
* @docsCategory request
* @docsPage Allow Decorator
*/
export const Allow = (...permissions: Permission[]) => SetMetadata(PERMISSIONS_METADATA_KEY, permissions);
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { GraphQLResolveInfo } from 'graphql';
import { getApiType } from '../common/get-api-type';
/**
* @description
* Resolver param decorator which returns which Api the request came though.
* This is useful because sometimes the same resolver will have different behaviour
* depending whether it is being called from the shop API or the admin API.
*
* Returns a string of type {@link ApiType}.
*
* @example
* ```ts
* \@Query()
* getAdministrators(\@Api() apiType: ApiType) {
* if (apiType === 'admin') {
* // ...
* }
* }
* ```
* @docsCategory request
* @docsPage Api Decorator
*/
export const Api = createParamDecorator((data, ctx: ExecutionContext) => {
const info = ctx.getArgByIndex(3);
return getApiType(info);
});
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { Type } from '@vendure/common/lib/shared-types';
import { unique } from '@vendure/common/lib/unique';
import { getNamedType, GraphQLResolveInfo, GraphQLSchema, isObjectType } from 'graphql';
import { getMetadataArgsStorage } from 'typeorm';
import { CalculatedColumnDefinition, CALCULATED_PROPERTIES } from '../../common/calculated-decorator';
import { InternalServerError } from '../../common/error/errors';
import { TtlCache } from '../../common/ttl-cache';
import { EntityRelationPaths } from '../../common/types/entity-relation-paths';
import { VendureEntity } from '../../entity/base/base.entity';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const graphqlFields = require('graphql-fields');
export type RelationPaths<T extends VendureEntity> = Array<EntityRelationPaths<T>>;
export type FieldsDecoratorConfig<T extends VendureEntity> =
| Type<T>
| {
entity: Type<T>;
depth?: number;
omit?: RelationPaths<T>;
};
const DEFAULT_DEPTH = 3;
const cache = new TtlCache({ cacheSize: 500, ttl: 5 * 60 * 1000 });
/**
* @description
* Resolver param decorator which returns an array of relation paths which can be passed through
* to the TypeORM data layer in order to join only the required relations. This works by inspecting
* the GraphQL `info` object, examining the field selection, and then comparing this with information
* about the return type's relations.
*
* In addition to analyzing the field selection, this decorator also checks for any `@Calculated()`
* properties on the entity, and additionally includes relations from the `relations` array of the calculated
* metadata, if defined.
*
* So if, for example, the query only selects the `id` field of an Order, then no other relations need
* be joined in the resulting SQL query. This can massively speed up execution time for queries which do
* not include many deep nested relations.
*
* @example
* ```ts
* \@Query()
* \@Allow(Permission.ReadOrder)
* orders(
* \@Ctx() ctx: RequestContext,
* \@Args() args: QueryOrdersArgs,
* \@Relations(Order) relations: RelationPaths<Order>,
* ): Promise<PaginatedList<Order>> {
* return this.orderService.findAll(ctx, args.options || undefined, relations);
* }
* ```
*
* In the above example, given the following query:
*
* @example
* ```GraphQL
* {
* orders(options: { take: 10 }) {
* items {
* id
* customer {
* id
* firstName
* lastName
* }
* totalQuantity
* totalWithTax
* }
* }
* }
* ```
* then the value of `relations` will be
*
* ```
* ['customer', 'lines'']
* ```
* The `'customer'` comes from the fact that the query is nesting the "customer" object, and the `'lines'` is taken
* from the `Order` entity's `totalQuantity` property, which uses {@link Calculated} decorator and defines those relations as dependencies
* for deriving the calculated value.
*
* ## Depth
*
* By default, when inspecting the GraphQL query, the Relations decorator will look 3 levels deep in any nested fields. So, e.g. if
* the above `orders` query were changed to:
*
* @example
* ```GraphQL
* {
* orders(options: { take: 10 }) {
* items {
* id
* lines {
* productVariant {
* product {
* featuredAsset {
* preview
* }
* }
* }
* }
* }
* }
* }
* ```
* then the `relations` array would include `'lines'`, `'lines.productVariant'`, & `'lines.productVariant.product'` - 3 levels deep - but it would
* _not_ include `'lines.productVariant.product.featuredAsset'` since that exceeds the default depth. To specify a custom depth, you would
* use the decorator like this:
*
* @example
* ```ts
* \@Relations({ entity: Order, depth: 2 }) relations: RelationPaths<Order>,
* ```
*
* ## Omit
*
* The `omit` option is used to explicitly omit certain relations from the calculated relations array. This is useful in certain
* cases where we know for sure that we need to run the field resolver _anyway_. A good example is the `Collection.productVariants` relation.
* When a GraphQL query comes in for a Collection and also requests its `productVariants` field, there is no point using a lookahead to eagerly
* join that relation, because we will throw that data away anyway when the `productVariants` field resolver executes, since it returns a
* PaginatedList query rather than a simple array.
*
* @example
* ```ts
* \@Relations({ entity: Collection, omit: ['productVariant'] }) relations: RelationPaths<Collection>,
* ```
*
* @docsCategory request
* @docsPage Relations Decorator
* @since 1.6.0
*/
export const Relations: <T extends VendureEntity>(data: FieldsDecoratorConfig<T>) => ParameterDecorator =
createParamDecorator<FieldsDecoratorConfig<any>>((data, ctx: ExecutionContext) => {
const info = ctx.getArgByIndex(3);
if (data == null) {
throw new InternalServerError('The @Relations() decorator requires an entity type argument');
}
if (!isGraphQLResolveInfo(info)) {
return [];
}
const cacheKey = info.fieldName + '__' + (ctx.getArgByIndex(2).req.body.query as string);
const cachedResult = cache.get(cacheKey);
if (cachedResult) {
return cachedResult;
}
const fields = graphqlFields(info);
const targetFields = isPaginatedListQuery(info) ? fields.items ?? {} : fields;
const entity = typeof data === 'function' ? data : data.entity;
const maxDepth = typeof data === 'function' ? DEFAULT_DEPTH : data.depth ?? DEFAULT_DEPTH;
const omit = typeof data === 'function' ? [] : data.omit ?? [];
const relationFields = getRelationPaths(targetFields, entity, maxDepth);
let result = unique(relationFields);
for (const omitPath of omit) {
result = result.filter(resultPath => !resultPath.startsWith(omitPath as string));
}
cache.set(cacheKey, result);
return result;
});
function getRelationPaths(
fields: Record<string, Record<string, any>>,
entity: Type<VendureEntity>,
maxDepth: number,
depth = 1,
): string[] {
const relations = getMetadataArgsStorage().filterRelations(entity);
const metadata = getMetadataArgsStorage();
const relationPaths: string[] = [];
for (const [property, value] of Object.entries(fields)) {
if (property === 'customFields') {
const customFieldEntity = metadata
.filterEmbeddeds(entity)
.find(e => e.propertyName === 'customFields')
?.type();
if (customFieldEntity) {
if (depth < maxDepth) {
depth++;
const subPaths = getRelationPaths(
value,
customFieldEntity as Type<VendureEntity>,
maxDepth,
depth,
);
depth--;
for (const subPath of subPaths) {
relationPaths.push([property, subPath].join('.'));
}
}
}
} else {
const relationMetadata = relations.find(r => r.propertyName === property);
if (relationMetadata) {
relationPaths.push(property);
const relatedEntity =
typeof relationMetadata.type === 'function'
? // https://github.com/microsoft/TypeScript/issues/37663
(relationMetadata.type as any)()
: relationMetadata.type;
if (depth < maxDepth) {
depth++;
const subPaths = getRelationPaths(
value,
relatedEntity as Type<VendureEntity>,
maxDepth,
depth,
);
depth--;
for (const subPath of subPaths) {
relationPaths.push([property, subPath].join('.'));
}
}
}
const calculatedProperties: CalculatedColumnDefinition[] =
Object.getPrototypeOf(new entity())[CALCULATED_PROPERTIES] ?? [];
const selectedFields = new Set(Object.keys(fields));
const dependencyRelations = calculatedProperties
.filter(p => selectedFields.has(p.name as string) && p.listQuery?.relations?.length)
.map(p => p.listQuery?.relations ?? [])
.flat();
relationPaths.push(...dependencyRelations);
}
}
return relationPaths;
}
function isGraphQLResolveInfo(input: unknown): input is GraphQLResolveInfo {
return !!(input && typeof input === 'object' && (input as any).schema instanceof GraphQLSchema);
}
function isPaginatedListQuery(info: GraphQLResolveInfo): boolean {
const returnType = getNamedType(info.returnType);
return isObjectType(returnType) && !!returnType.getInterfaces().find(i => i.name === 'PaginatedList');
}
|
import { ContextType, createParamDecorator, ExecutionContext } from '@nestjs/common';
import { REQUEST_CONTEXT_KEY, REQUEST_CONTEXT_MAP_KEY } from '../../common/constants';
/**
* @description
* Resolver param decorator which extracts the {@link RequestContext} from the incoming
* request object.
*
* @example
* ```ts
* \@Query()
* getAdministrators(\@Ctx() ctx: RequestContext) {
* // ...
* }
* ```
*
* @docsCategory request
* @docsPage Ctx Decorator
*/
export const Ctx = createParamDecorator((data, ctx: ExecutionContext) => {
const getContext = (req: any) => {
// eslint-disable-next-line @typescript-eslint/ban-types
const map: Map<Function, any> | undefined = req[REQUEST_CONTEXT_MAP_KEY];
// If a map contains associated transactional context with this handler
// we have to use it. It means that this handler was wrapped with @Transaction decorator.
// Otherwise use default context.
return map?.get(ctx.getHandler()) || req[REQUEST_CONTEXT_KEY];
};
if (ctx.getType<ContextType | 'graphql'>() === 'graphql') {
// GraphQL request
return getContext(ctx.getArgByIndex(2).req);
} else {
// REST request
return getContext(ctx.switchToHttp().getRequest());
}
});
|
import { applyDecorators, SetMetadata, UseInterceptors } from '@nestjs/common';
import { TransactionInterceptor } from '../middleware/transaction-interceptor';
export const TRANSACTION_MODE_METADATA_KEY = '__transaction_mode__';
/**
* @description
* The Transaction decorator can handle transactions automatically (which is the default) or be set to
* "manual" mode, where the {@link TransactionalConnection} `.startTransaction()` and `.commitOpenTransaction()`
* methods must them be used.
*
* @example
* ```ts
* // in a GraphQL resolver file
*
* \@Transaction('manual')
* async myMutation(\@Ctx() ctx: RequestContext) {
* await this.connection.startTransaction(ctx);
* const result = this.myService.createThing(ctx);
* const thing = this.myService.updateOtherThing(ctx, result.id);
* await this.connection.commitOpenTransaction(ctx);
* return thing;
* }
* ```
* Note that even in manual mode, a rollback will be automatically performed in
* the case that an uncaught error is thrown within the resolver.
*
* @default 'auto'
* @docsCategory request
* @docsPage Transaction Decorator
*/
export type TransactionMode = 'auto' | 'manual';
export const TRANSACTION_ISOLATION_LEVEL_METADATA_KEY = '__transaction_isolation_level__';
/**
* @description
* Transactions can be run at different isolation levels. The default is undefined, which
* falls back to the default of your database. See the documentation of your database for more
* information on available isolation levels.
*
* @default undefined
* @docsCategory request
* @docsPage Transaction Decorator
*/
export type TransactionIsolationLevel =
| 'READ UNCOMMITTED'
| 'READ COMMITTED'
| 'REPEATABLE READ'
| 'SERIALIZABLE';
/**
* @description
* Runs the decorated method in a TypeORM transaction. It works by creating a transactional
* QueryRunner which gets attached to the RequestContext object. When the RequestContext
* is the passed to the {@link TransactionalConnection} `getRepository()` method, this
* QueryRunner is used to execute the queries within this transaction.
*
* Essentially, the entire resolver function is wrapped in a try-catch block which commits the
* transaction on successful completion of the method, or rolls back the transaction in an unhandled
* error is thrown.
*
* @example
* ```ts
* // in a GraphQL resolver file
*
* \@Transaction()
* async myMutation(\@Ctx() ctx: RequestContext) {
* // as long as the `ctx` object is passed in to
* // all database operations, the entire mutation
* // will be run as an atomic transaction, and rolled
* // back if an error is thrown.
* const result = this.myService.createThing(ctx);
* return this.myService.updateOtherThing(ctx, result.id);
* }
* ```
*
* @docsCategory request
* @docsPage Transaction Decorator
* @docsWeight 0
*/
export const Transaction = (
transactionMode: TransactionMode = 'auto',
transactionIsolationLevel?: TransactionIsolationLevel,
) => {
return applyDecorators(
SetMetadata(TRANSACTION_MODE_METADATA_KEY, transactionMode),
SetMetadata(TRANSACTION_ISOLATION_LEVEL_METADATA_KEY, transactionIsolationLevel),
UseInterceptors(TransactionInterceptor),
);
};
|
import { ApolloServerPlugin, GraphQLRequestListener, GraphQLServerContext } from '@apollo/server';
import { DocumentNode, GraphQLNamedType, isUnionType } from 'graphql';
import { AssetStorageStrategy } from '../../config/asset-storage-strategy/asset-storage-strategy';
import { ConfigService } from '../../config/config.service';
import { GraphqlValueTransformer } from '../common/graphql-value-transformer';
/**
* Transforms outputs so that any Asset instances are run through the {@link AssetStorageStrategy.toAbsoluteUrl}
* method before being returned in the response.
*/
export class AssetInterceptorPlugin implements ApolloServerPlugin {
private graphqlValueTransformer: GraphqlValueTransformer;
private readonly toAbsoluteUrl: AssetStorageStrategy['toAbsoluteUrl'] | undefined;
constructor(private configService: ConfigService) {
const { assetOptions } = this.configService;
if (assetOptions.assetStorageStrategy.toAbsoluteUrl) {
this.toAbsoluteUrl = assetOptions.assetStorageStrategy.toAbsoluteUrl.bind(
assetOptions.assetStorageStrategy,
);
}
}
async serverWillStart(service: GraphQLServerContext): Promise<void> {
this.graphqlValueTransformer = new GraphqlValueTransformer(service.schema);
}
async requestDidStart(): Promise<GraphQLRequestListener<any>> {
return {
willSendResponse: async requestContext => {
const { document } = requestContext;
if (document) {
const { body } = requestContext.response;
const req = requestContext.contextValue.req;
if (body.kind === 'single') {
this.prefixAssetUrls(req, document, body.singleResult.data);
}
}
},
};
}
private prefixAssetUrls(request: any, document: DocumentNode, data?: Record<string, unknown> | null) {
const typeTree = this.graphqlValueTransformer.getOutputTypeTree(document);
const toAbsoluteUrl = this.toAbsoluteUrl;
if (!toAbsoluteUrl || !data) {
return;
}
this.graphqlValueTransformer.transformValues(typeTree, data, (value, type) => {
if (!type) {
return value;
}
const isAssetType = this.isAssetType(type);
const isUnionWithAssetType = isUnionType(type) && type.getTypes().find(t => this.isAssetType(t));
if (isAssetType || isUnionWithAssetType) {
if (value && !Array.isArray(value)) {
if (value.preview) {
value.preview = toAbsoluteUrl(request, value.preview);
}
if (value.source) {
value.source = toAbsoluteUrl(request, value.source);
}
}
}
return value;
});
}
private isAssetType(type: GraphQLNamedType): boolean {
const assetTypeNames = ['Asset', 'SearchResultAsset'];
return assetTypeNames.includes(type.name);
}
}
|
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Permission } from '@vendure/common/lib/generated-types';
import { Request, Response } from 'express';
import { GraphQLResolveInfo } from 'graphql';
import { REQUEST_CONTEXT_KEY } from '../../common/constants';
import { ForbiddenError } from '../../common/error/errors';
import { ConfigService } from '../../config/config.service';
import { LogLevel } from '../../config/logger/vendure-logger';
import { CachedSession } from '../../config/session-cache/session-cache-strategy';
import { Customer } from '../../entity/customer/customer.entity';
import { RequestContextService } from '../../service/helpers/request-context/request-context.service';
import { ChannelService } from '../../service/services/channel.service';
import { CustomerService } from '../../service/services/customer.service';
import { SessionService } from '../../service/services/session.service';
import { extractSessionToken } from '../common/extract-session-token';
import { parseContext } from '../common/parse-context';
import { RequestContext } from '../common/request-context';
import { setSessionToken } from '../common/set-session-token';
import { PERMISSIONS_METADATA_KEY } from '../decorators/allow.decorator';
/**
* @description
* A guard which:
*
* 1. checks for the existence of a valid session token in the request and if found,
* attaches the current User entity to the request.
* 2. enforces any permissions required by the target handler (resolver, field resolver or route),
* and throws a ForbiddenError if those permissions are not present.
*/
@Injectable()
export class AuthGuard implements CanActivate {
strategy: any;
constructor(
private reflector: Reflector,
private configService: ConfigService,
private requestContextService: RequestContextService,
private sessionService: SessionService,
private customerService: CustomerService,
private channelService: ChannelService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const { req, res, info } = parseContext(context);
const isFieldResolver = this.isFieldResolver(info);
const permissions = this.reflector.get<Permission[]>(PERMISSIONS_METADATA_KEY, context.getHandler());
if (isFieldResolver && !permissions) {
return true;
}
const authDisabled = this.configService.authOptions.disableAuth;
const isPublic = !!permissions && permissions.includes(Permission.Public);
const hasOwnerPermission = !!permissions && permissions.includes(Permission.Owner);
let requestContext: RequestContext;
if (isFieldResolver) {
requestContext = (req as any)[REQUEST_CONTEXT_KEY];
} else {
const session = await this.getSession(req, res, hasOwnerPermission);
requestContext = await this.requestContextService.fromRequest(req, info, permissions, session);
const requestContextShouldBeReinitialized = await this.setActiveChannel(requestContext, session);
if (requestContextShouldBeReinitialized) {
requestContext = await this.requestContextService.fromRequest(
req,
info,
permissions,
session,
);
}
(req as any)[REQUEST_CONTEXT_KEY] = requestContext;
}
if (authDisabled || !permissions || isPublic) {
return true;
} else {
const canActivate =
requestContext.userHasPermissions(permissions) || requestContext.authorizedAsOwnerOnly;
if (!canActivate) {
throw new ForbiddenError(LogLevel.Verbose);
} else {
return canActivate;
}
}
}
private async setActiveChannel(
requestContext: RequestContext,
session?: CachedSession,
): Promise<boolean> {
if (!session) {
return false;
}
// In case the session does not have an activeChannelId or the activeChannelId
// does not correspond to the current channel, the activeChannelId on the session is set
const activeChannelShouldBeSet =
!session.activeChannelId || session.activeChannelId !== requestContext.channelId;
if (activeChannelShouldBeSet) {
await this.sessionService.setActiveChannel(session, requestContext.channel);
if (requestContext.activeUserId) {
const customer = await this.customerService.findOneByUserId(
requestContext,
requestContext.activeUserId,
false,
);
// To avoid assigning the customer to the active channel on every request,
// it is only done on the first request and whenever the channel changes
if (customer) {
try {
await this.channelService.assignToChannels(requestContext, Customer, customer.id, [
requestContext.channelId,
]);
} catch (e: any) {
const isDuplicateError =
e.code === 'ER_DUP_ENTRY' /* mySQL/MariaDB */ ||
e.code === '23505'; /* postgres */
if (isDuplicateError) {
// For a duplicate error, this means that concurrent requests have resulted in attempting to
// assign the Customer to the channel more than once. In this case we can safely ignore the
// error as the Customer was successfully assigned in the earlier call.
// See https://github.com/vendure-ecommerce/vendure/issues/834
} else {
throw e;
}
}
}
}
return true;
}
return false;
}
private async getSession(
req: Request,
res: Response,
hasOwnerPermission: boolean,
): Promise<CachedSession | undefined> {
const sessionToken = extractSessionToken(req, this.configService.authOptions.tokenMethod);
let serializedSession: CachedSession | undefined;
if (sessionToken) {
serializedSession = await this.sessionService.getSessionFromToken(sessionToken);
if (serializedSession) {
return serializedSession;
}
// if there is a token but it cannot be validated to a Session,
// then the token is no longer valid and should be unset.
setSessionToken({
req,
res,
authOptions: this.configService.authOptions,
rememberMe: false,
sessionToken: '',
});
}
if (hasOwnerPermission && !serializedSession) {
serializedSession = await this.sessionService.createAnonymousSession();
setSessionToken({
sessionToken: serializedSession.token,
rememberMe: true,
authOptions: this.configService.authOptions,
req,
res,
});
}
return serializedSession;
}
/**
* Returns true is this guard is being called on a FieldResolver, i.e. not a top-level
* Query or Mutation resolver.
*/
private isFieldResolver(info?: GraphQLResolveInfo): boolean {
if (!info) {
return false;
}
const parentType = info?.parentType?.name;
return parentType !== 'Query' && parentType !== 'Mutation' && parentType !== 'Subscription';
}
}
|
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import { ConfigService, Logger, LogLevel } from '../../config';
import { HEALTH_CHECK_ROUTE } from '../../health-check/constants';
import { I18nError } from '../../i18n/i18n-error';
import { parseContext } from '../common/parse-context';
/**
* Logs thrown I18nErrors via the configured VendureLogger.
*/
@Catch()
export class ExceptionLoggerFilter implements ExceptionFilter {
constructor(private configService: ConfigService) {}
catch(exception: Error, host: ArgumentsHost) {
for (const handler of this.configService.systemOptions.errorHandlers) {
void handler.handleServerError(exception, { host });
}
const { req, res, info, isGraphQL } = parseContext(host);
let message = '';
let statusCode = 500;
if (exception instanceof I18nError) {
const { code, message: msg, logLevel } = exception;
message = `${code || 'Error'}: ${msg}`;
statusCode = this.errorCodeToStatusCode(code);
switch (logLevel) {
case LogLevel.Error:
Logger.error(
JSON.stringify({ message, variables: exception.variables }, null, 2),
undefined,
exception.stack,
);
break;
case LogLevel.Warn:
Logger.warn(message);
break;
case LogLevel.Info:
Logger.info(message);
break;
case LogLevel.Debug:
Logger.debug(message);
break;
case LogLevel.Verbose:
Logger.verbose(message);
break;
}
if (exception.stack) {
Logger.debug(exception.stack);
}
if (isGraphQL) {
return exception;
}
} else if (exception instanceof HttpException) {
// Handle other Nestjs errors
statusCode = exception.getStatus();
message = exception.message;
if (statusCode === 404) {
Logger.verbose(exception.message);
} else {
Logger.error(message, undefined, exception.stack);
}
} else {
Logger.error(exception.message, undefined, exception.stack);
}
if (exception instanceof HttpException && req.path.startsWith('/' + HEALTH_CHECK_ROUTE)) {
// Special case for the health check error, since we want to display the response only
// so it matches the format of the success case.
res.status(exception.getStatus()).send(exception.getResponse());
} else if (!isGraphQL) {
// In the GraphQL context, we can let the error pass
// through to the next layer, where Apollo Server will
// return a response for us. But when in the REST context,
// we must explicitly send the response, otherwise the server
// will hang.
res.status(statusCode).json({
statusCode,
message,
timestamp: new Date().toISOString(),
path: req.url,
});
}
}
/**
* For a given I18nError.code, returns a corresponding HTTP
* status code.
*/
private errorCodeToStatusCode(errorCode: string | undefined): number {
switch (errorCode) {
case 'FORBIDDEN':
return 403;
case 'UNAUTHORIZED':
return 401;
case 'USER_INPUT_ERROR':
case 'ILLEGAL_OPERATION':
return 400;
default:
return 500;
}
}
}
|
import { ApolloServerPlugin, GraphQLRequestListener, GraphQLServerContext } from '@apollo/server';
import { isObject } from '@vendure/common/lib/shared-utils';
import { DocumentNode } from 'graphql';
import { GraphqlValueTransformer } from '../common/graphql-value-transformer';
import { IdCodecService } from '../common/id-codec.service';
/**
* Encodes the ids of outgoing responses according to the configured EntityIdStrategy.
*
* This is done here and not via a Nest Interceptor because it's not possible
* according to https://github.com/nestjs/graphql/issues/320
*/
export class IdCodecPlugin implements ApolloServerPlugin {
private graphqlValueTransformer: GraphqlValueTransformer;
constructor(private idCodecService: IdCodecService) {}
async serverWillStart(service: GraphQLServerContext): Promise<void> {
this.graphqlValueTransformer = new GraphqlValueTransformer(service.schema);
}
async requestDidStart(): Promise<GraphQLRequestListener<any>> {
return {
willSendResponse: async requestContext => {
const { document } = requestContext;
if (document) {
const { body } = requestContext.response;
if (body.kind === 'single') {
this.encodeIdFields(document, body.singleResult.data);
}
}
},
};
}
private encodeIdFields(document: DocumentNode, data?: Record<string, unknown> | null) {
if (!data) {
return;
}
const typeTree = this.graphqlValueTransformer.getOutputTypeTree(document);
this.graphqlValueTransformer.transformValues(typeTree, data, (value, type) => {
const isIdType = type && type.name === 'ID';
if (type && type.name === 'JSON' && isObject(value)) {
return this.idCodecService.encode(value, [
'paymentId',
'fulfillmentId',
'orderItemIds',
'orderLineId',
'promotionId',
'refundId',
'groupId',
'modificationId',
'previousCustomerId',
'newCustomerId',
]);
}
return isIdType ? this.idCodecService.encode(value) : value;
});
}
}
|
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { IdOperators } from '@vendure/common/lib/generated-types';
import { GraphQLNamedType, GraphQLSchema, OperationDefinitionNode } from 'graphql';
import { Observable } from 'rxjs';
import { GraphqlValueTransformer } from '../common/graphql-value-transformer';
import { IdCodecService } from '../common/id-codec.service';
import { parseContext } from '../common/parse-context';
export const ID_CODEC_TRANSFORM_KEYS = 'idCodecTransformKeys';
type TypeTreeNode = {
type: GraphQLNamedType | undefined;
parent: TypeTreeNode | null;
isList: boolean;
children: { [name: string]: TypeTreeNode };
};
/**
* This interceptor automatically decodes incoming requests so that any
* ID values are transformed correctly as per the configured EntityIdStrategy.
*
* ID values are defined as properties with the name "id", or properties with names matching any
* arguments passed to the {@link Decode} decorator.
*/
@Injectable()
export class IdInterceptor implements NestInterceptor {
private graphQlValueTransformers = new WeakMap<GraphQLSchema, GraphqlValueTransformer>();
constructor(private idCodecService: IdCodecService) {}
intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> {
const { isGraphQL, req, info } = parseContext(context);
if (isGraphQL && info) {
const args = GqlExecutionContext.create(context).getArgs();
const transformer = this.getTransformerForSchema(info.schema);
this.decodeIdArguments(transformer, info.operation, args);
}
return next.handle();
}
private getTransformerForSchema(schema: GraphQLSchema): GraphqlValueTransformer {
const existing = this.graphQlValueTransformers.get(schema);
if (existing) {
return existing;
}
const transformer = new GraphqlValueTransformer(schema);
this.graphQlValueTransformers.set(schema, transformer);
return transformer;
}
private decodeIdArguments(
graphqlValueTransformer: GraphqlValueTransformer,
definition: OperationDefinitionNode,
variables: Record<string, any> = {},
) {
const typeTree = graphqlValueTransformer.getInputTypeTree(definition);
graphqlValueTransformer.transformValues(typeTree, variables, (value, type) => {
if (type?.name === 'ID') {
return this.idCodecService.decode(value);
}
if (type?.name === 'IDOperators') {
const keys: Array<keyof IdOperators> = ['eq', 'notEq', 'in', 'notIn'];
return this.idCodecService.decode(value, keys);
}
return value;
});
return variables;
}
}
|
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable, of } from 'rxjs';
import { RequestContext } from '..';
import { REQUEST_CONTEXT_KEY, REQUEST_CONTEXT_MAP_KEY } from '../../common/constants';
import { TransactionWrapper } from '../../connection/transaction-wrapper';
import { TransactionalConnection } from '../../connection/transactional-connection';
import { parseContext } from '../common/parse-context';
import {
TransactionMode,
TRANSACTION_MODE_METADATA_KEY,
TransactionIsolationLevel,
TRANSACTION_ISOLATION_LEVEL_METADATA_KEY,
} from '../decorators/transaction.decorator';
/**
* @description
* Used by the {@link Transaction} decorator to create a transactional query runner
* and attach it to the RequestContext.
*/
@Injectable()
export class TransactionInterceptor implements NestInterceptor {
constructor(
private connection: TransactionalConnection,
private transactionWrapper: TransactionWrapper,
private reflector: Reflector,
) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const { isGraphQL, req } = parseContext(context);
const ctx: RequestContext | undefined = (req as any)[REQUEST_CONTEXT_KEY];
if (ctx) {
const transactionMode = this.reflector.get<TransactionMode>(
TRANSACTION_MODE_METADATA_KEY,
context.getHandler(),
);
const transactionIsolationLevel = this.reflector.get<TransactionIsolationLevel | undefined>(
TRANSACTION_ISOLATION_LEVEL_METADATA_KEY,
context.getHandler(),
);
return of(
this.transactionWrapper.executeInTransaction(
ctx,
_ctx => {
this.registerTransactionalContext(_ctx, context.getHandler(), req);
return next.handle();
},
transactionMode,
transactionIsolationLevel,
this.connection.rawConnection,
),
);
} else {
return next.handle();
}
}
/**
* Registers transactional request context associated with execution handler function
*
* @param ctx transactional request context
* @param handler handler function from ExecutionContext
* @param req Request object
*/
// eslint-disable-next-line @typescript-eslint/ban-types
registerTransactionalContext(ctx: RequestContext, handler: Function, req: any) {
// eslint-disable-next-line @typescript-eslint/ban-types
const map: Map<Function, RequestContext> = req[REQUEST_CONTEXT_MAP_KEY] || new Map();
map.set(handler, ctx);
req[REQUEST_CONTEXT_MAP_KEY] = map;
}
}
|
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { ErrorResult as AdminErrorResult } from '../../common/error/generated-graphql-admin-errors';
import { ErrorResult as ShopErrorResult } from '../../common/error/generated-graphql-shop-errors';
import { I18nService } from '../../i18n/i18n.service';
import { parseContext } from '../common/parse-context';
/**
* @description
* Translates any top-level ErrorResult message
*/
@Injectable()
export class TranslateErrorResultInterceptor implements NestInterceptor {
constructor(private i18nService: I18nService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const { isGraphQL, req } = parseContext(context);
return next.handle().pipe(
switchMap(result => Promise.resolve(result)),
map(result => {
if (Array.isArray(result)) {
for (const item of result) {
this.translateResult(req, item);
}
} else {
this.translateResult(req, result);
}
return result;
}),
);
}
private translateResult(req: any, result: unknown) {
if (result instanceof AdminErrorResult || result instanceof ShopErrorResult) {
this.i18nService.translateErrorResult(req, result as any);
}
}
}
|
import { ApolloServerPlugin, GraphQLRequestListener } from '@apollo/server';
import { I18nService } from '../../i18n/i18n.service';
/**
* This plugin intercepts outgoing responses and translates any error messages into the
* current request language.
*/
export class TranslateErrorsPlugin implements ApolloServerPlugin {
constructor(private i18nService: I18nService) {}
async requestDidStart(): Promise<GraphQLRequestListener<any>> {
return {
willSendResponse: async requestContext => {
const { errors, contextValue } = requestContext;
const { body } = requestContext.response;
if (errors && body.kind === 'single') {
body.singleResult.errors = errors.map(err => {
return this.i18nService.translateError(contextValue.req, err) as any;
});
}
},
};
}
}
|
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { GqlExecutionContext } from '@nestjs/graphql';
import { LanguageCode } from '@vendure/common/lib/generated-types';
import { getGraphQlInputName } from '@vendure/common/lib/shared-utils';
import {
GraphQLInputType,
GraphQLList,
GraphQLNonNull,
GraphQLSchema,
OperationDefinitionNode,
TypeNode,
} from 'graphql';
import { REQUEST_CONTEXT_KEY } from '../../common/constants';
import { Injector } from '../../common/injector';
import { ConfigService } from '../../config/config.service';
import { CustomFieldConfig, CustomFields } from '../../config/custom-field/custom-field-types';
import { parseContext } from '../common/parse-context';
import { RequestContext } from '../common/request-context';
import { validateCustomFieldValue } from '../common/validate-custom-field-value';
/**
* This interceptor is responsible for enforcing the validation constraints defined for any CustomFields.
* For example, if a custom 'int' field has a "min" value of 0, and a mutation attempts to set its value
* to a negative integer, then that mutation will fail with an error.
*/
@Injectable()
export class ValidateCustomFieldsInterceptor implements NestInterceptor {
private readonly inputsWithCustomFields: Set<string>;
constructor(private configService: ConfigService, private moduleRef: ModuleRef) {
this.inputsWithCustomFields = Object.keys(configService.customFields).reduce((inputs, entityName) => {
inputs.add(`Create${entityName}Input`);
inputs.add(`Update${entityName}Input`);
return inputs;
}, new Set<string>());
this.inputsWithCustomFields.add('OrderLineCustomFieldsInput');
}
async intercept(context: ExecutionContext, next: CallHandler<any>) {
const parsedContext = parseContext(context);
const injector = new Injector(this.moduleRef);
if (parsedContext.isGraphQL) {
const gqlExecutionContext = GqlExecutionContext.create(context);
const { operation, schema } = parsedContext.info;
const variables = gqlExecutionContext.getArgs();
const ctx: RequestContext = (parsedContext.req as any)[REQUEST_CONTEXT_KEY];
if (operation.operation === 'mutation') {
const inputTypeNames = this.getArgumentMap(operation, schema);
for (const [inputName, typeName] of Object.entries(inputTypeNames)) {
if (this.inputsWithCustomFields.has(typeName)) {
if (variables[inputName]) {
const inputVariables: Array<Record<string, any>> = Array.isArray(
variables[inputName],
)
? variables[inputName]
: [variables[inputName]];
for (const inputVariable of inputVariables) {
await this.validateInput(typeName, ctx, injector, inputVariable);
}
}
}
}
}
}
return next.handle();
}
private async validateInput(
typeName: string,
ctx: RequestContext,
injector: Injector,
variableValues?: { [key: string]: any },
) {
if (variableValues) {
const entityName = typeName.replace(/(Create|Update)(.+)Input/, '$2');
const customFieldConfig = this.configService.customFields[entityName as keyof CustomFields];
if (typeName === 'OrderLineCustomFieldsInput') {
// special case needed to handle custom fields passed via addItemToOrder or adjustOrderLine
// mutations.
await this.validateCustomFieldsObject(
this.configService.customFields.OrderLine,
ctx,
variableValues,
injector,
);
}
if (variableValues.customFields) {
await this.validateCustomFieldsObject(
customFieldConfig,
ctx,
variableValues.customFields,
injector,
);
}
const translations = variableValues.translations;
if (Array.isArray(translations)) {
for (const translation of translations) {
if (translation.customFields) {
await this.validateCustomFieldsObject(
customFieldConfig,
ctx,
translation.customFields,
injector,
);
}
}
}
}
}
private async validateCustomFieldsObject(
customFieldConfig: CustomFieldConfig[],
ctx: RequestContext,
customFieldsObject: { [key: string]: any },
injector: Injector,
) {
for (const [key, value] of Object.entries(customFieldsObject)) {
const config = customFieldConfig.find(c => getGraphQlInputName(c) === key);
if (config) {
await validateCustomFieldValue(config, value, injector, ctx);
}
}
}
private getArgumentMap(
operation: OperationDefinitionNode,
schema: GraphQLSchema,
): { [inputName: string]: string } {
const mutationType = schema.getMutationType();
if (!mutationType) {
return {};
}
const map: { [inputName: string]: string } = {};
for (const selection of operation.selectionSet.selections) {
if (selection.kind === 'Field') {
const name = selection.name.value;
const inputType = mutationType.getFields()[name];
if (!inputType) continue;
for (const arg of inputType.args) {
map[arg.name] = this.getInputTypeName(arg.type);
}
}
}
return map;
}
private getNamedTypeName(type: TypeNode): string {
if (type.kind === 'NonNullType' || type.kind === 'ListType') {
return this.getNamedTypeName(type.type);
} else {
return type.name.value;
}
}
private getInputTypeName(type: GraphQLInputType): string {
if (type instanceof GraphQLNonNull) {
return this.getInputTypeName(type.ofType);
}
if (type instanceof GraphQLList) {
return this.getInputTypeName(type.ofType);
}
return type.name;
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationAssignRoleToAdministratorArgs,
MutationCreateAdministratorArgs,
MutationDeleteAdministratorArgs,
MutationDeleteAdministratorsArgs,
MutationUpdateActiveAdministratorArgs,
MutationUpdateAdministratorArgs,
Permission,
QueryAdministratorArgs,
QueryAdministratorsArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Administrator } from '../../../entity/administrator/administrator.entity';
import { AdministratorService } from '../../../service/services/administrator.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Administrator')
export class AdministratorResolver {
constructor(private administratorService: AdministratorService) {}
@Query()
@Allow(Permission.ReadAdministrator)
administrators(
@Ctx() ctx: RequestContext,
@Args() args: QueryAdministratorsArgs,
@Relations(Administrator) relations: RelationPaths<Administrator>,
): Promise<PaginatedList<Administrator>> {
return this.administratorService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadAdministrator)
administrator(
@Ctx() ctx: RequestContext,
@Args() args: QueryAdministratorArgs,
@Relations(Administrator) relations: RelationPaths<Administrator>,
): Promise<Administrator | undefined> {
return this.administratorService.findOne(ctx, args.id, relations);
}
@Query()
@Allow(Permission.Owner)
async activeAdministrator(@Ctx() ctx: RequestContext): Promise<Administrator | undefined> {
if (ctx.activeUserId) {
return this.administratorService.findOneByUserId(ctx, ctx.activeUserId);
}
}
@Transaction()
@Mutation()
@Allow(Permission.CreateAdministrator)
createAdministrator(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateAdministratorArgs,
): Promise<Administrator> {
const { input } = args;
return this.administratorService.create(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateAdministrator)
updateAdministrator(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateAdministratorArgs,
): Promise<Administrator> {
const { input } = args;
return this.administratorService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.Owner)
async updateActiveAdministrator(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateActiveAdministratorArgs,
): Promise<Administrator | undefined> {
if (ctx.activeUserId) {
const { input } = args;
const administrator = await this.administratorService.findOneByUserId(ctx, ctx.activeUserId);
if (administrator) {
return this.administratorService.update(ctx, { ...input, id: administrator.id });
}
}
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateAdministrator)
assignRoleToAdministrator(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignRoleToAdministratorArgs,
): Promise<Administrator> {
return this.administratorService.assignRole(ctx, args.administratorId, args.roleId);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteAdministrator)
deleteAdministrator(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteAdministratorArgs,
): Promise<DeletionResponse> {
const { id } = args;
return this.administratorService.softDelete(ctx, id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteAdministrator)
deleteAdministrators(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteAdministratorsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.administratorService.softDelete(ctx, id)));
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
CreateAssetResult,
MutationAssignAssetsToChannelArgs,
MutationCreateAssetsArgs,
MutationDeleteAssetArgs,
MutationDeleteAssetsArgs,
MutationUpdateAssetArgs,
Permission,
QueryAssetArgs,
QueryAssetsArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Administrator } from '../../../entity/administrator/administrator.entity';
import { Asset } from '../../../entity/asset/asset.entity';
import { AssetService } from '../../../service/services/asset.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Asset')
export class AssetResolver {
constructor(private assetService: AssetService) {}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadAsset)
async asset(
@Ctx() ctx: RequestContext,
@Args() args: QueryAssetArgs,
@Relations(Asset) relations: RelationPaths<Asset>,
): Promise<Asset | undefined> {
return this.assetService.findOne(ctx, args.id, relations);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadAsset)
async assets(
@Ctx() ctx: RequestContext,
@Args() args: QueryAssetsArgs,
@Relations(Asset) relations: RelationPaths<Asset>,
): Promise<PaginatedList<Asset>> {
return this.assetService.findAll(ctx, args.options || undefined, relations);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateAsset)
async createAssets(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateAssetsArgs,
): Promise<CreateAssetResult[]> {
// TODO: Is there some way to parellelize this while still preserving
// the order of files in the upload? Non-deterministic IDs mess up the e2e test snapshots.
const assets: CreateAssetResult[] = [];
for (const input of args.input) {
const asset = await this.assetService.create(ctx, input);
assets.push(asset);
}
return assets;
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateAsset)
async updateAsset(@Ctx() ctx: RequestContext, @Args() { input }: MutationUpdateAssetArgs) {
return this.assetService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteAsset)
async deleteAsset(
@Ctx() ctx: RequestContext,
@Args() { input: { assetId, force, deleteFromAllChannels } }: MutationDeleteAssetArgs,
) {
return this.assetService.delete(
ctx,
[assetId],
force || undefined,
deleteFromAllChannels || undefined,
);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteAsset)
async deleteAssets(
@Ctx() ctx: RequestContext,
@Args() { input: { assetIds, force, deleteFromAllChannels } }: MutationDeleteAssetsArgs,
) {
return this.assetService.delete(
ctx,
assetIds,
force || undefined,
deleteFromAllChannels || undefined,
);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateAsset)
async assignAssetsToChannel(
@Ctx() ctx: RequestContext,
@Args() { input }: MutationAssignAssetsToChannelArgs,
) {
return this.assetService.assignToChannel(ctx, input);
}
}
|
import { Args, Context, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
AuthenticationResult,
MutationAuthenticateArgs,
MutationLoginArgs,
NativeAuthenticationResult,
Permission,
Success,
} from '@vendure/common/lib/generated-types';
import { Request, Response } from 'express';
import { NativeAuthStrategyError } from '../../../common/error/generated-graphql-admin-errors';
import { NATIVE_AUTH_STRATEGY_NAME } from '../../../config/auth/native-authentication-strategy';
import { ConfigService } from '../../../config/config.service';
import { Logger } from '../../../config/logger/vendure-logger';
import { AdministratorService } from '../../../service/services/administrator.service';
import { AuthService } from '../../../service/services/auth.service';
import { ChannelService } from '../../../service/services/channel.service';
import { CustomerService } from '../../../service/services/customer.service';
import { UserService } from '../../../service/services/user.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
import { BaseAuthResolver } from '../base/base-auth.resolver';
@Resolver()
export class AuthResolver extends BaseAuthResolver {
constructor(
authService: AuthService,
userService: UserService,
configService: ConfigService,
administratorService: AdministratorService,
) {
super(authService, userService, administratorService, configService);
}
@Transaction()
@Mutation()
@Allow(Permission.Public)
async login(
@Args() args: MutationLoginArgs,
@Ctx() ctx: RequestContext,
@Context('req') req: Request,
@Context('res') res: Response,
): Promise<NativeAuthenticationResult> {
const nativeAuthStrategyError = this.requireNativeAuthStrategy();
if (nativeAuthStrategyError) {
return nativeAuthStrategyError;
}
return (await super.baseLogin(args, ctx, req, res)) as AuthenticationResult;
}
@Transaction()
@Mutation()
@Allow(Permission.Public)
async authenticate(
@Args() args: MutationAuthenticateArgs,
@Ctx() ctx: RequestContext,
@Context('req') req: Request,
@Context('res') res: Response,
): Promise<AuthenticationResult> {
return (await this.authenticateAndCreateSession(ctx, args, req, res)) as AuthenticationResult;
}
@Transaction()
@Mutation()
@Allow(Permission.Public)
logout(
@Ctx() ctx: RequestContext,
@Context('req') req: Request,
@Context('res') res: Response,
): Promise<Success> {
return super.logout(ctx, req, res);
}
@Query()
@Allow(Permission.Authenticated, Permission.Owner)
me(@Ctx() ctx: RequestContext) {
return super.me(ctx, 'admin');
}
protected requireNativeAuthStrategy() {
const { adminAuthenticationStrategy } = this.configService.authOptions;
const nativeAuthStrategyIsConfigured = !!adminAuthenticationStrategy.find(
strategy => strategy.name === NATIVE_AUTH_STRATEGY_NAME,
);
if (!nativeAuthStrategyIsConfigured) {
const authStrategyNames = adminAuthenticationStrategy.map(s => s.name).join(', ');
const errorMessage =
'This GraphQL operation requires that the NativeAuthenticationStrategy be configured for the Admin API.\n' +
`Currently the following AuthenticationStrategies are enabled: ${authStrategyNames}`;
Logger.error(errorMessage);
return new NativeAuthStrategyError();
}
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
CreateChannelResult,
DeletionResponse,
MutationCreateChannelArgs,
MutationDeleteChannelArgs,
MutationDeleteChannelsArgs,
MutationUpdateChannelArgs,
Permission,
QueryChannelArgs,
QueryChannelsArgs,
UpdateChannelResult,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { ErrorResultUnion, isGraphQlErrorResult } from '../../../common/error/error-result';
import { Channel } from '../../../entity/channel/channel.entity';
import { ChannelService } from '../../../service/services/channel.service';
import { RoleService } from '../../../service/services/role.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Channel')
export class ChannelResolver {
constructor(private channelService: ChannelService, private roleService: RoleService) {}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadChannel)
async channels(
@Ctx() ctx: RequestContext,
@Args() args: QueryChannelsArgs,
): Promise<PaginatedList<Channel>> {
return this.channelService.findAll(ctx, args.options || undefined);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadChannel)
async channel(@Ctx() ctx: RequestContext, @Args() args: QueryChannelArgs): Promise<Channel | undefined> {
return this.channelService.findOne(ctx, args.id);
}
@Query()
@Allow(Permission.Authenticated)
async activeChannel(@Ctx() ctx: RequestContext): Promise<Channel> {
return ctx.channel;
}
@Transaction()
@Mutation()
@Allow(Permission.SuperAdmin, Permission.CreateChannel)
async createChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateChannelArgs,
): Promise<ErrorResultUnion<CreateChannelResult, Channel>> {
const result = await this.channelService.create(ctx, args.input);
if (isGraphQlErrorResult(result)) {
return result;
}
const superAdminRole = await this.roleService.getSuperAdminRole(ctx);
const customerRole = await this.roleService.getCustomerRole(ctx);
await this.roleService.assignRoleToChannel(ctx, superAdminRole.id, result.id);
await this.roleService.assignRoleToChannel(ctx, customerRole.id, result.id);
return result;
}
@Transaction()
@Mutation()
@Allow(Permission.SuperAdmin, Permission.UpdateChannel)
async updateChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateChannelArgs,
): Promise<ErrorResultUnion<UpdateChannelResult, Channel>> {
const result = await this.channelService.update(ctx, args.input);
if (isGraphQlErrorResult(result)) {
return result;
}
return result;
}
@Transaction()
@Mutation()
@Allow(Permission.SuperAdmin, Permission.DeleteChannel)
async deleteChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteChannelArgs,
): Promise<DeletionResponse> {
return this.channelService.delete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.SuperAdmin, Permission.DeleteChannel)
async deleteChannels(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteChannelsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.channelService.delete(ctx, id)));
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
ConfigurableOperationDefinition,
DeletionResponse,
MutationAssignCollectionsToChannelArgs,
MutationCreateCollectionArgs,
MutationDeleteCollectionArgs,
MutationDeleteCollectionsArgs,
MutationMoveCollectionArgs,
MutationRemoveCollectionsFromChannelArgs,
MutationUpdateCollectionArgs,
Permission,
QueryCollectionArgs,
QueryCollectionsArgs,
QueryPreviewCollectionVariantsArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { UserInputError } from '../../../common/error/errors';
import { Translated } from '../../../common/types/locale-types';
import { CollectionFilter } from '../../../config/catalog/collection-filter';
import { Collection } from '../../../entity/collection/collection.entity';
import { CollectionService } from '../../../service/services/collection.service';
import { FacetValueService } from '../../../service/services/facet-value.service';
import { ConfigurableOperationCodec } from '../../common/configurable-operation-codec';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class CollectionResolver {
constructor(
private collectionService: CollectionService,
private facetValueService: FacetValueService,
private configurableOperationCodec: ConfigurableOperationCodec,
) {}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadCollection)
async collectionFilters(
@Ctx() ctx: RequestContext,
@Args() args: QueryCollectionsArgs,
): Promise<ConfigurableOperationDefinition[]> {
return this.collectionService.getAvailableFilters(ctx);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadCollection)
async collections(
@Ctx() ctx: RequestContext,
@Args() args: QueryCollectionsArgs,
@Relations({
entity: Collection,
omit: ['productVariants', 'assets', 'parent.productVariants', 'children.productVariants'],
})
relations: RelationPaths<Collection>,
): Promise<PaginatedList<Translated<Collection>>> {
return this.collectionService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadCollection)
async collection(
@Ctx() ctx: RequestContext,
@Args() args: QueryCollectionArgs,
@Relations({
entity: Collection,
omit: ['productVariants', 'assets', 'parent.productVariants', 'children.productVariants'],
})
relations: RelationPaths<Collection>,
): Promise<Translated<Collection> | undefined> {
let collection: Translated<Collection> | undefined;
if (args.id) {
collection = await this.collectionService.findOne(ctx, args.id, relations);
if (args.slug && collection && collection.slug !== args.slug) {
throw new UserInputError('error.collection-id-slug-mismatch');
}
} else if (args.slug) {
collection = await this.collectionService.findOneBySlug(ctx, args.slug, relations);
} else {
throw new UserInputError('error.collection-id-or-slug-must-be-provided');
}
return collection;
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadCollection)
previewCollectionVariants(@Ctx() ctx: RequestContext, @Args() args: QueryPreviewCollectionVariantsArgs) {
this.configurableOperationCodec.decodeConfigurableOperationIds(CollectionFilter, args.input.filters);
return this.collectionService.previewCollectionVariants(ctx, args.input, args.options || undefined);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateCollection)
async createCollection(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateCollectionArgs,
): Promise<Translated<Collection>> {
const { input } = args;
this.configurableOperationCodec.decodeConfigurableOperationIds(CollectionFilter, input.filters);
const collection = await this.collectionService.create(ctx, input);
return collection;
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateCollection)
async updateCollection(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateCollectionArgs,
): Promise<Translated<Collection>> {
const { input } = args;
this.configurableOperationCodec.decodeConfigurableOperationIds(CollectionFilter, input.filters || []);
return this.collectionService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateCollection)
async moveCollection(
@Ctx() ctx: RequestContext,
@Args() args: MutationMoveCollectionArgs,
): Promise<Translated<Collection>> {
const { input } = args;
return this.collectionService.move(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteCollection)
async deleteCollection(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCollectionArgs,
): Promise<DeletionResponse> {
return this.collectionService.delete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteCollection)
async deleteCollections(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCollectionsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.collectionService.delete(ctx, id)));
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateCollection)
async assignCollectionsToChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignCollectionsToChannelArgs,
): Promise<Array<Translated<Collection>>> {
return await this.collectionService.assignCollectionsToChannel(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteCollection)
async removeCollectionsFromChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveCollectionsFromChannelArgs,
): Promise<Array<Translated<Collection>>> {
return await this.collectionService.removeCollectionsFromChannel(ctx, args.input);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationCreateCountryArgs,
MutationDeleteCountriesArgs,
MutationDeleteCountryArgs,
MutationUpdateCountryArgs,
Permission,
QueryCountriesArgs,
QueryCountryArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Translated } from '../../../common/types/locale-types';
import { Country } from '../../../entity/region/country.entity';
import { CountryService } from '../../../service/services/country.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Country')
export class CountryResolver {
constructor(private countryService: CountryService) {}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadCountry)
countries(
@Ctx() ctx: RequestContext,
@Args() args: QueryCountriesArgs,
@Relations(Country) relations: RelationPaths<Country>,
): Promise<PaginatedList<Translated<Country>>> {
return this.countryService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadCountry)
async country(
@Ctx() ctx: RequestContext,
@Args() args: QueryCountryArgs,
@Relations(Country) relations: RelationPaths<Country>,
): Promise<Translated<Country> | undefined> {
return this.countryService.findOne(ctx, args.id, relations);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateSettings, Permission.CreateCountry)
async createCountry(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateCountryArgs,
): Promise<Translated<Country>> {
return this.countryService.create(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateCountry)
async updateCountry(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateCountryArgs,
): Promise<Translated<Country>> {
return this.countryService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteCountry)
async deleteCountry(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCountryArgs,
): Promise<DeletionResponse> {
return this.countryService.delete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteCountry)
async deleteCountries(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCountriesArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.countryService.delete(ctx, id)));
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationAddCustomersToGroupArgs,
MutationCreateCustomerGroupArgs,
MutationDeleteCustomerGroupArgs,
MutationRemoveCustomersFromGroupArgs,
MutationUpdateCustomerGroupArgs,
MutationDeleteCustomerGroupsArgs,
Permission,
QueryCustomerGroupArgs,
QueryCustomerGroupsArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { CustomerGroup } from '../../../entity/customer-group/customer-group.entity';
import { CustomerGroupService } from '../../../service/services/customer-group.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('CustomerGroup')
export class CustomerGroupResolver {
constructor(private customerGroupService: CustomerGroupService) {}
@Query()
@Allow(Permission.ReadCustomer, Permission.ReadCustomerGroup)
customerGroups(
@Ctx() ctx: RequestContext,
@Args() args: QueryCustomerGroupsArgs,
@Relations(CustomerGroup) relations: RelationPaths<CustomerGroup>,
): Promise<PaginatedList<CustomerGroup>> {
return this.customerGroupService.findAll(ctx, args.options || undefined);
}
@Query()
@Allow(Permission.ReadCustomer, Permission.ReadCustomerGroup)
async customerGroup(
@Ctx() ctx: RequestContext,
@Args() args: QueryCustomerGroupArgs,
@Relations(CustomerGroup) relations: RelationPaths<CustomerGroup>,
): Promise<CustomerGroup | undefined> {
return this.customerGroupService.findOne(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCustomerGroup)
async createCustomerGroup(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateCustomerGroupArgs,
): Promise<CustomerGroup> {
return this.customerGroupService.create(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCustomerGroup)
async updateCustomerGroup(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateCustomerGroupArgs,
): Promise<CustomerGroup> {
return this.customerGroupService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCustomerGroup)
async deleteCustomerGroup(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCustomerGroupArgs,
): Promise<DeletionResponse> {
return this.customerGroupService.delete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCustomerGroup)
async deleteCustomerGroups(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCustomerGroupsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.customerGroupService.delete(ctx, id)));
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCustomerGroup)
async addCustomersToGroup(
@Ctx() ctx: RequestContext,
@Args() args: MutationAddCustomersToGroupArgs,
): Promise<CustomerGroup> {
return this.customerGroupService.addCustomersToGroup(ctx, args);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCustomerGroup)
async removeCustomersFromGroup(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveCustomersFromGroupArgs,
): Promise<CustomerGroup> {
return this.customerGroupService.removeCustomersFromGroup(ctx, args);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
CreateCustomerResult,
DeletionResponse,
MutationAddNoteToCustomerArgs,
MutationCreateCustomerAddressArgs,
MutationCreateCustomerArgs,
MutationDeleteCustomerAddressArgs,
MutationDeleteCustomerArgs,
MutationDeleteCustomerNoteArgs,
MutationDeleteCustomersArgs,
MutationUpdateCustomerAddressArgs,
MutationUpdateCustomerArgs,
MutationUpdateCustomerNoteArgs,
Permission,
QueryCustomerArgs,
QueryCustomersArgs,
Success,
UpdateCustomerResult,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { ErrorResultUnion } from '../../../common/error/error-result';
import { Address } from '../../../entity/address/address.entity';
import { Customer } from '../../../entity/customer/customer.entity';
import { CustomerGroupService } from '../../../service/services/customer-group.service';
import { CustomerService } from '../../../service/services/customer.service';
import { OrderService } from '../../../service/services/order.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class CustomerResolver {
constructor(
private customerService: CustomerService,
private customerGroupService: CustomerGroupService,
private orderService: OrderService,
) {}
@Query()
@Allow(Permission.ReadCustomer)
async customers(
@Ctx() ctx: RequestContext,
@Args() args: QueryCustomersArgs,
@Relations({ entity: Customer, omit: ['orders'] }) relations: RelationPaths<Customer>,
): Promise<PaginatedList<Customer>> {
return this.customerService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadCustomer)
async customer(
@Ctx() ctx: RequestContext,
@Args() args: QueryCustomerArgs,
@Relations({ entity: Customer, omit: ['orders'] }) relations: RelationPaths<Customer>,
): Promise<Customer | undefined> {
return this.customerService.findOne(ctx, args.id, relations);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCustomer)
async createCustomer(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateCustomerArgs,
): Promise<ErrorResultUnion<CreateCustomerResult, Customer>> {
const { input, password } = args;
return this.customerService.create(ctx, input, password || undefined);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCustomer)
async updateCustomer(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateCustomerArgs,
): Promise<ErrorResultUnion<UpdateCustomerResult, Customer>> {
const { input } = args;
return this.customerService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCustomer)
async createCustomerAddress(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateCustomerAddressArgs,
): Promise<Address> {
const { customerId, input } = args;
return this.customerService.createAddress(ctx, customerId, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCustomer)
async updateCustomerAddress(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateCustomerAddressArgs,
): Promise<Address> {
const { input } = args;
return this.customerService.updateAddress(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCustomer)
async deleteCustomerAddress(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCustomerAddressArgs,
): Promise<Success> {
const { id } = args;
const success = await this.customerService.deleteAddress(ctx, id);
return { success };
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCustomer)
async deleteCustomer(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCustomerArgs,
): Promise<DeletionResponse> {
const groups = await this.customerService.getCustomerGroups(ctx, args.id);
for (const group of groups) {
await this.customerGroupService.removeCustomersFromGroup(ctx, {
customerGroupId: group.id,
customerIds: [args.id],
});
}
return this.customerService.softDelete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCustomer)
async deleteCustomers(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteCustomersArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.deleteCustomer(ctx, { id })));
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCustomer)
async addNoteToCustomer(@Ctx() ctx: RequestContext, @Args() args: MutationAddNoteToCustomerArgs) {
return this.customerService.addNoteToCustomer(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCustomer)
async updateCustomerNote(@Ctx() ctx: RequestContext, @Args() args: MutationUpdateCustomerNoteArgs) {
return this.customerService.updateCustomerNote(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCustomer)
async deleteCustomerNote(@Ctx() ctx: RequestContext, @Args() args: MutationDeleteCustomerNoteArgs) {
return this.customerService.deleteCustomerNote(ctx, args.id);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
ActiveOrderResult,
ApplyCouponCodeResult,
RemoveOrderItemsResult,
SetOrderShippingMethodResult,
UpdateOrderItemsResult,
} from '@vendure/common/lib/generated-shop-types';
import {
DeletionResponse,
DeletionResult,
MutationAddItemToDraftOrderArgs,
MutationAdjustDraftOrderLineArgs,
MutationApplyCouponCodeToDraftOrderArgs,
MutationDeleteDraftOrderArgs,
MutationRemoveCouponCodeFromDraftOrderArgs,
MutationRemoveDraftOrderLineArgs,
MutationSetCustomerForDraftOrderArgs,
MutationSetDraftOrderBillingAddressArgs,
MutationSetDraftOrderShippingAddressArgs,
MutationSetDraftOrderShippingMethodArgs,
Permission,
QueryEligibleShippingMethodsForDraftOrderArgs,
ShippingMethodQuote,
} from '@vendure/common/lib/generated-types';
import { ErrorResultUnion, isGraphQlErrorResult } from '../../../common/error/error-result';
import { UserInputError } from '../../../common/error/errors';
import { TransactionalConnection } from '../../../connection/index';
import { Customer } from '../../../entity/customer/customer.entity';
import { Order } from '../../../entity/order/order.entity';
import { CustomerService } from '../../../service/services/customer.service';
import { OrderService } from '../../../service/services/order.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class DraftOrderResolver {
constructor(
private orderService: OrderService,
private customerService: CustomerService,
private connection: TransactionalConnection,
) {}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async createDraftOrder(@Ctx() ctx: RequestContext): Promise<Order> {
return this.orderService.createDraft(ctx);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteOrder)
async deleteDraftOrder(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteDraftOrderArgs,
): Promise<DeletionResponse> {
const order = await this.orderService.findOne(ctx, args.orderId);
if (!order || order.state !== 'Draft') {
return {
result: DeletionResult.NOT_DELETED,
message: `No draft Order with the ID ${args.orderId} was found`,
};
}
try {
await this.orderService.deleteOrder(ctx, args.orderId);
return {
result: DeletionResult.DELETED,
};
} catch (e: any) {
return {
result: DeletionResult.NOT_DELETED,
message: e.message,
};
}
}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async addItemToDraftOrder(
@Ctx() ctx: RequestContext,
@Args() { orderId, input }: MutationAddItemToDraftOrderArgs,
): Promise<ErrorResultUnion<UpdateOrderItemsResult, Order>> {
return this.orderService.addItemToOrder(
ctx,
orderId,
input.productVariantId,
input.quantity,
(input as any).customFields,
);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder, Permission.Owner)
async adjustDraftOrderLine(
@Ctx() ctx: RequestContext,
@Args() { orderId, input }: MutationAdjustDraftOrderLineArgs,
): Promise<ErrorResultUnion<UpdateOrderItemsResult, Order>> {
if (input.quantity === 0) {
return this.removeDraftOrderLine(ctx, { orderId, orderLineId: input.orderLineId });
}
return this.orderService.adjustOrderLine(
ctx,
orderId,
input.orderLineId,
input.quantity,
(input as any).customFields,
);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async removeDraftOrderLine(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveDraftOrderLineArgs,
): Promise<ErrorResultUnion<RemoveOrderItemsResult, Order>> {
return this.orderService.removeItemFromOrder(ctx, args.orderId, args.orderLineId);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async setCustomerForDraftOrder(
@Ctx() ctx: RequestContext,
@Args() args: MutationSetCustomerForDraftOrderArgs,
): Promise<ErrorResultUnion</* SetCustomerForDraftOrderResult*/ any, Order>> {
let customer: Customer;
if (args.customerId) {
const result = await this.customerService.findOne(ctx, args.customerId);
if (!result) {
throw new UserInputError(
`No customer with the id "${args.customerId}" was found in this Channel`,
);
}
customer = result;
} else if (args.input) {
const result = await this.customerService.createOrUpdate(ctx, args.input, true);
if (isGraphQlErrorResult(result)) {
return result as any;
}
customer = result;
} else {
throw new UserInputError(
'Either "customerId" or "input" must be supplied to setCustomerForDraftOrder',
);
}
return this.orderService.addCustomerToOrder(ctx, args.orderId, customer);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async setDraftOrderShippingAddress(
@Ctx() ctx: RequestContext,
@Args() args: MutationSetDraftOrderShippingAddressArgs,
): Promise<Order> {
return this.orderService.setShippingAddress(ctx, args.orderId, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async setDraftOrderBillingAddress(
@Ctx() ctx: RequestContext,
@Args() args: MutationSetDraftOrderBillingAddressArgs,
): Promise<ErrorResultUnion<ActiveOrderResult, Order>> {
return this.orderService.setBillingAddress(ctx, args.orderId, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async applyCouponCodeToDraftOrder(
@Ctx() ctx: RequestContext,
@Args() args: MutationApplyCouponCodeToDraftOrderArgs,
): Promise<ErrorResultUnion<ApplyCouponCodeResult, Order>> {
return this.orderService.applyCouponCode(ctx, args.orderId, args.couponCode);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async removeCouponCodeFromDraftOrder(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveCouponCodeFromDraftOrderArgs,
): Promise<Order> {
return this.orderService.removeCouponCode(ctx, args.orderId, args.couponCode);
}
@Query()
@Allow(Permission.CreateOrder)
async eligibleShippingMethodsForDraftOrder(
@Ctx() ctx: RequestContext,
@Args() args: QueryEligibleShippingMethodsForDraftOrderArgs,
): Promise<ShippingMethodQuote[]> {
return this.orderService.getEligibleShippingMethods(ctx, args.orderId);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateOrder)
async setDraftOrderShippingMethod(
@Ctx() ctx: RequestContext,
@Args() args: MutationSetDraftOrderShippingMethodArgs,
): Promise<ErrorResultUnion<SetOrderShippingMethodResult, Order>> {
return this.orderService.setShippingMethod(ctx, args.orderId, [args.shippingMethodId]);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DuplicateEntityResult,
MutationDuplicateEntityArgs,
Permission,
} from '@vendure/common/lib/generated-types';
import { EntityDuplicatorService } from '../../../service/helpers/entity-duplicator/entity-duplicator.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class DuplicateEntityResolver {
constructor(private entityDuplicatorService: EntityDuplicatorService) {}
@Query()
@Allow(Permission.Authenticated)
async entityDuplicators(@Ctx() ctx: RequestContext) {
return this.entityDuplicatorService.getEntityDuplicators(ctx);
}
@Mutation()
@Transaction()
@Allow(Permission.Authenticated)
async duplicateEntity(
@Ctx() ctx: RequestContext,
@Args() args: MutationDuplicateEntityArgs,
): Promise<DuplicateEntityResult> {
return this.entityDuplicatorService.duplicateEntity(ctx, args.input);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationAssignFacetsToChannelArgs,
MutationCreateFacetArgs,
MutationCreateFacetValuesArgs,
MutationDeleteFacetArgs,
MutationDeleteFacetsArgs,
MutationDeleteFacetValuesArgs,
MutationRemoveFacetsFromChannelArgs,
MutationUpdateFacetArgs,
MutationUpdateFacetValuesArgs,
Permission,
QueryFacetArgs,
QueryFacetsArgs,
QueryFacetValuesArgs,
RemoveFacetFromChannelResult,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { EntityNotFoundError } from '../../../common/error/errors';
import { ErrorResultUnion } from '../../../common/error/error-result';
import { Translated } from '../../../common/types/locale-types';
import { ConfigService } from '../../../config/config.service';
import { Facet } from '../../../entity/facet/facet.entity';
import { FacetValue } from '../../../entity/facet-value/facet-value.entity';
import { FacetValueService } from '../../../service/services/facet-value.service';
import { FacetService } from '../../../service/services/facet.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Facet')
export class FacetResolver {
constructor(
private facetService: FacetService,
private facetValueService: FacetValueService,
private configService: ConfigService,
) {}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct, Permission.ReadFacet)
facets(
@Ctx() ctx: RequestContext,
@Args() args: QueryFacetsArgs,
@Relations(Facet) relations: RelationPaths<Facet>,
): Promise<PaginatedList<Translated<Facet>>> {
return this.facetService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct, Permission.ReadFacet)
async facet(
@Ctx() ctx: RequestContext,
@Args() args: QueryFacetArgs,
@Relations(Facet) relations: RelationPaths<Facet>,
): Promise<Translated<Facet> | undefined> {
return this.facetService.findOne(ctx, args.id, relations);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct, Permission.ReadFacet)
facetValues(
@Ctx() ctx: RequestContext,
@Args() args: QueryFacetValuesArgs,
@Relations(FacetValue) relations: RelationPaths<FacetValue>,
): Promise<PaginatedList<Translated<FacetValue>>> {
return this.facetValueService.findAllList(ctx, args.options || undefined, relations);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateFacet)
async createFacet(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateFacetArgs,
): Promise<Translated<Facet>> {
const { input } = args;
const facet = await this.facetService.create(ctx, args.input);
if (input.values && input.values.length) {
for (const value of input.values) {
const newValue = await this.facetValueService.create(ctx, facet, value);
facet.values.push(newValue);
}
}
return facet;
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateFacet)
async updateFacet(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateFacetArgs,
): Promise<Translated<Facet>> {
const { input } = args;
return this.facetService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteFacet)
async deleteFacet(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteFacetArgs,
): Promise<DeletionResponse> {
return this.facetService.delete(ctx, args.id, args.force || false);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteFacet)
async deleteFacets(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteFacetsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.facetService.delete(ctx, id, args.force || false)));
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateFacet)
async createFacetValues(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateFacetValuesArgs,
): Promise<Array<Translated<FacetValue>>> {
const { input } = args;
const facetId = input[0].facetId;
const facet = await this.facetService.findOne(ctx, facetId);
if (!facet) {
throw new EntityNotFoundError('Facet', facetId);
}
const facetValues: Array<Translated<FacetValue>> = [];
for (const facetValue of input) {
const res = await this.facetValueService.create(ctx, facet, facetValue);
facetValues.push(res);
}
return facetValues;
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateFacet)
async updateFacetValues(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateFacetValuesArgs,
): Promise<Array<Translated<FacetValue>>> {
const { input } = args;
return Promise.all(input.map(facetValue => this.facetValueService.update(ctx, facetValue)));
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteFacet)
async deleteFacetValues(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteFacetValuesArgs,
): Promise<DeletionResponse[]> {
const results: DeletionResponse[] = [];
for (const id of args.ids) {
results.push(await this.facetValueService.delete(ctx, id, args.force || false));
}
return results;
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateFacet)
async assignFacetsToChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignFacetsToChannelArgs,
): Promise<Facet[]> {
return await this.facetService.assignFacetsToChannel(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteFacet)
async removeFacetsFromChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveFacetsFromChannelArgs,
): Promise<Array<ErrorResultUnion<RemoveFacetFromChannelResult, Facet>>> {
return await this.facetService.removeFacetsFromChannel(ctx, args.input);
}
}
|
import { Args, Info, Mutation, Query, ResolveField, Resolver } from '@nestjs/graphql';
import {
CustomFields as GraphQLCustomFields,
CustomFieldConfig as GraphQLCustomFieldConfig,
RelationCustomFieldConfig as GraphQLRelationCustomFieldConfig,
EntityCustomFields,
MutationUpdateGlobalSettingsArgs,
Permission,
ServerConfig,
UpdateGlobalSettingsResult,
} from '@vendure/common/lib/generated-types';
import { notNullOrUndefined } from '@vendure/common/lib/shared-utils';
import {
GraphQLOutputType,
GraphQLResolveInfo,
isEnumType,
isInterfaceType,
isListType,
isNonNullType,
isObjectType,
isScalarType,
} from 'graphql';
import { getAllPermissionsMetadata } from '../../../common/constants';
import { ErrorResultUnion } from '../../../common/error/error-result';
import { ChannelDefaultLanguageError } from '../../../common/error/generated-graphql-admin-errors';
import { ConfigService } from '../../../config/config.service';
import {
CustomFieldConfig,
CustomFields,
RelationCustomFieldConfig,
} from '../../../config/custom-field/custom-field-types';
import { GlobalSettings } from '../../../entity/global-settings/global-settings.entity';
import { ChannelService } from '../../../service/services/channel.service';
import { GlobalSettingsService } from '../../../service/services/global-settings.service';
import { OrderService } from '../../../service/services/order.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('GlobalSettings')
export class GlobalSettingsResolver {
constructor(
private configService: ConfigService,
private globalSettingsService: GlobalSettingsService,
private channelService: ChannelService,
private orderService: OrderService,
) {}
@Query()
@Allow(Permission.Authenticated)
async globalSettings(@Ctx() ctx: RequestContext) {
return this.globalSettingsService.getSettings(ctx);
}
/**
* Exposes a subset of the VendureConfig which may be of use to clients.
*/
@ResolveField()
serverConfig(@Info() info: GraphQLResolveInfo): ServerConfig {
const permissions = getAllPermissionsMetadata(
this.configService.authOptions.customPermissions,
).filter(p => !p.internal);
return {
customFieldConfig: this.generateCustomFieldConfig(info),
entityCustomFields: this.generateEntityCustomFieldConfig(info),
orderProcess: this.orderService.getOrderProcessStates(),
permittedAssetTypes: this.configService.assetOptions.permittedFileTypes,
permissions,
moneyStrategyPrecision: this.configService.entityOptions.moneyStrategy.precision ?? 2,
};
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateGlobalSettings)
async updateGlobalSettings(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateGlobalSettingsArgs,
): Promise<ErrorResultUnion<UpdateGlobalSettingsResult, GlobalSettings>> {
// This validation is performed here in the resolver rather than at the service
// layer to avoid a circular dependency [ChannelService <> GlobalSettingsService]
const { availableLanguages } = args.input;
if (availableLanguages) {
const channels = await this.channelService.findAll(ctx);
const unavailableDefaults = channels.items.filter(
c => !availableLanguages.includes(c.defaultLanguageCode),
);
if (unavailableDefaults.length) {
return new ChannelDefaultLanguageError({
language: unavailableDefaults.map(c => c.defaultLanguageCode).join(', '),
channelCode: unavailableDefaults.map(c => c.code).join(', '),
});
}
}
return this.globalSettingsService.updateSettings(ctx, args.input);
}
// TODO: Remove in v3
private generateCustomFieldConfig(info: GraphQLResolveInfo): GraphQLCustomFields {
const exposedCustomFieldConfig: CustomFields = {};
for (const [entityType, customFields] of Object.entries(this.configService.customFields)) {
exposedCustomFieldConfig[entityType as keyof CustomFields] = customFields
// Do not expose custom fields marked as "internal".
?.filter(c => !c.internal)
.map(c => ({ ...c, list: !!c.list as any }))
.map((c: any) => {
// In the VendureConfig, the relation entity is specified
// as the class, but the GraphQL API exposes it as a string.
if (c.type === 'relation') {
c.entity = c.entity.name;
c.scalarFields = this.getScalarFieldsOfType(info, c.graphQLType || c.entity);
}
return c;
});
}
return exposedCustomFieldConfig as GraphQLCustomFields;
}
private generateEntityCustomFieldConfig(info: GraphQLResolveInfo): EntityCustomFields[] {
return Object.entries(this.configService.customFields)
.map(([entityType, customFields]) => {
if (!customFields || !customFields.length) {
return;
}
const customFieldsConfig = customFields
// Do not expose custom fields marked as "internal".
.filter(c => !c.internal)
.map(c => ({ ...c, list: !!c.list as any }))
.map(c => {
const { requiresPermission } = c;
c.requiresPermission = Array.isArray(requiresPermission)
? requiresPermission
: !!requiresPermission
? [requiresPermission]
: [];
return c;
})
.map(c => {
// In the VendureConfig, the relation entity is specified
// as the class, but the GraphQL API exposes it as a string.
const customFieldConfig: GraphQLCustomFieldConfig = { ...c } as any;
if (this.isRelationGraphQLType(customFieldConfig) && this.isRelationConfigType(c)) {
customFieldConfig.entity = c.entity.name;
customFieldConfig.scalarFields = this.getScalarFieldsOfType(
info,
c.graphQLType || c.entity.name,
);
}
return customFieldConfig;
});
return { entityName: entityType, customFields: customFieldsConfig };
})
.filter(notNullOrUndefined);
}
private isRelationGraphQLType(
config: GraphQLCustomFieldConfig,
): config is GraphQLRelationCustomFieldConfig {
return config.type === 'relation';
}
private isRelationConfigType(config: CustomFieldConfig): config is RelationCustomFieldConfig {
return config.type === 'relation';
}
private getScalarFieldsOfType(info: GraphQLResolveInfo, typeName: string): string[] {
const type = info.schema.getType(typeName);
if (type && (isObjectType(type) || isInterfaceType(type))) {
return Object.values(type.getFields())
.filter(field => {
const namedType = this.getNamedType(field.type);
return isScalarType(namedType) || isEnumType(namedType);
})
.map(field => field.name);
} else {
return [];
}
}
private getNamedType(type: GraphQLOutputType): GraphQLOutputType {
if (isNonNullType(type) || isListType(type)) {
return this.getNamedType(type.ofType);
} else {
return type;
}
}
}
|
import { Args, Mutation, Resolver } from '@nestjs/graphql';
import { MutationImportProductsArgs, Permission } from '@vendure/common/lib/generated-types';
import { Importer } from '../../../data-import/providers/importer/importer';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Import')
export class ImportResolver {
constructor(private importer: Importer) {}
@Mutation()
@Allow(Permission.SuperAdmin)
async importProducts(@Ctx() ctx: RequestContext, @Args() args: MutationImportProductsArgs) {
const { createReadStream, filename, mimetype, encoding } = await args.csvFile;
const stream = createReadStream();
return this.importer.parseAndImport(stream, ctx).toPromise();
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
JobQueue,
MutationCancelJobArgs,
MutationFlushBufferedJobsArgs,
MutationRemoveSettledJobsArgs,
Permission,
QueryJobArgs,
QueryJobBufferSizeArgs,
QueryJobsArgs,
QueryJobsByIdArgs,
} from '@vendure/common/lib/generated-types';
import { ConfigService, InspectableJobQueueStrategy, isInspectableJobQueueStrategy } from '../../../config';
import { JobQueueService } from '../../../job-queue';
import { JobBufferService } from '../../../job-queue/job-buffer/job-buffer.service';
import { Allow } from '../../decorators/allow.decorator';
@Resolver()
export class JobResolver {
constructor(
private configService: ConfigService,
private jobService: JobQueueService,
private jobBufferService: JobBufferService,
) {}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadSystem)
async job(@Args() args: QueryJobArgs) {
const strategy = this.requireInspectableJobQueueStrategy();
if (!strategy) {
return;
}
return strategy.findOne(args.jobId);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadSystem)
async jobs(@Args() args: QueryJobsArgs) {
const strategy = this.requireInspectableJobQueueStrategy();
if (!strategy) {
return {
items: [],
totalItems: 0,
};
}
return strategy.findMany(args.options || undefined);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadSystem)
async jobsById(@Args() args: QueryJobsByIdArgs) {
const strategy = this.requireInspectableJobQueueStrategy();
if (!strategy) {
return [];
}
return strategy.findManyById(args.jobIds || undefined);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadSystem)
jobQueues(): JobQueue[] {
return this.jobService.getJobQueues();
}
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteSystem)
async removeSettledJobs(@Args() args: MutationRemoveSettledJobsArgs) {
const strategy = this.requireInspectableJobQueueStrategy();
if (!strategy) {
return 0;
}
return strategy.removeSettledJobs(args.queueNames || [], args.olderThan);
}
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteSystem)
async cancelJob(@Args() args: MutationCancelJobArgs) {
const strategy = this.requireInspectableJobQueueStrategy();
if (!strategy) {
return;
}
return strategy.cancelJob(args.jobId);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadSystem)
async jobBufferSize(@Args() args: QueryJobBufferSizeArgs) {
const bufferSizes = await this.jobBufferService.bufferSize(args.bufferIds);
return Object.entries(bufferSizes).map(([bufferId, size]) => ({ bufferId, size }));
}
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateSystem)
async flushBufferedJobs(@Args() args: MutationFlushBufferedJobsArgs) {
await this.jobBufferService.flush(args.bufferIds);
return { success: true };
}
private requireInspectableJobQueueStrategy(): InspectableJobQueueStrategy | undefined {
if (!isInspectableJobQueueStrategy(this.configService.jobQueueOptions.jobQueueStrategy)) {
return;
}
return this.configService.jobQueueOptions.jobQueueStrategy;
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
AddFulfillmentToOrderResult,
CancelOrderResult,
CancelPaymentResult,
MutationAddFulfillmentToOrderArgs,
MutationAddManualPaymentToOrderArgs,
MutationAddNoteToOrderArgs,
MutationCancelOrderArgs,
MutationCancelPaymentArgs,
MutationDeleteOrderNoteArgs,
MutationModifyOrderArgs,
MutationRefundOrderArgs,
MutationSetOrderCustomerArgs,
MutationSetOrderCustomFieldsArgs,
MutationSettlePaymentArgs,
MutationSettleRefundArgs,
MutationTransitionFulfillmentToStateArgs,
MutationTransitionOrderToStateArgs,
MutationTransitionPaymentToStateArgs,
MutationUpdateOrderNoteArgs,
Permission,
QueryOrderArgs,
QueryOrdersArgs,
RefundOrderResult,
SettlePaymentResult,
TransitionPaymentToStateResult,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { ErrorResultUnion, isGraphQlErrorResult } from '../../../common/error/error-result';
import { TransactionalConnection } from '../../../connection';
import { Fulfillment } from '../../../entity/fulfillment/fulfillment.entity';
import { Order } from '../../../entity/order/order.entity';
import { Payment } from '../../../entity/payment/payment.entity';
import { Refund } from '../../../entity/refund/refund.entity';
import { FulfillmentState } from '../../../service/helpers/fulfillment-state-machine/fulfillment-state';
import { OrderState } from '../../../service/helpers/order-state-machine/order-state';
import { PaymentState } from '../../../service/helpers/payment-state-machine/payment-state';
import { OrderService } from '../../../service/services/order.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class OrderResolver {
constructor(private orderService: OrderService, private connection: TransactionalConnection) {}
@Query()
@Allow(Permission.ReadOrder)
orders(
@Ctx() ctx: RequestContext,
@Args() args: QueryOrdersArgs,
@Relations(Order) relations: RelationPaths<Order>,
): Promise<PaginatedList<Order>> {
return this.orderService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadOrder)
async order(
@Ctx() ctx: RequestContext,
@Args() args: QueryOrderArgs,
@Relations(Order) relations: RelationPaths<Order>,
): Promise<Order | undefined> {
return this.orderService.findOne(ctx, args.id, relations);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async settlePayment(
@Ctx() ctx: RequestContext,
@Args() args: MutationSettlePaymentArgs,
): Promise<ErrorResultUnion<SettlePaymentResult, Payment>> {
return this.orderService.settlePayment(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async cancelPayment(
@Ctx() ctx: RequestContext,
@Args() args: MutationCancelPaymentArgs,
): Promise<ErrorResultUnion<CancelPaymentResult, Payment>> {
return this.orderService.cancelPayment(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async addFulfillmentToOrder(
@Ctx() ctx: RequestContext,
@Args() args: MutationAddFulfillmentToOrderArgs,
): Promise<ErrorResultUnion<AddFulfillmentToOrderResult, Fulfillment>> {
return this.orderService.createFulfillment(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async cancelOrder(
@Ctx() ctx: RequestContext,
@Args() args: MutationCancelOrderArgs,
): Promise<ErrorResultUnion<CancelOrderResult, Order>> {
return this.orderService.cancelOrder(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async refundOrder(
@Ctx() ctx: RequestContext,
@Args() args: MutationRefundOrderArgs,
): Promise<ErrorResultUnion<RefundOrderResult, Refund>> {
return this.orderService.refundOrder(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async settleRefund(@Ctx() ctx: RequestContext, @Args() args: MutationSettleRefundArgs) {
return this.orderService.settleRefund(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async addNoteToOrder(@Ctx() ctx: RequestContext, @Args() args: MutationAddNoteToOrderArgs) {
return this.orderService.addNoteToOrder(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async updateOrderNote(@Ctx() ctx: RequestContext, @Args() args: MutationUpdateOrderNoteArgs) {
return this.orderService.updateOrderNote(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async deleteOrderNote(@Ctx() ctx: RequestContext, @Args() args: MutationDeleteOrderNoteArgs) {
return this.orderService.deleteOrderNote(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async setOrderCustomFields(@Ctx() ctx: RequestContext, @Args() args: MutationSetOrderCustomFieldsArgs) {
return this.orderService.updateCustomFields(ctx, args.input.id, args.input.customFields);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async setOrderCustomer(@Ctx() ctx: RequestContext, @Args() { input }: MutationSetOrderCustomerArgs) {
return this.orderService.updateOrderCustomer(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async transitionOrderToState(
@Ctx() ctx: RequestContext,
@Args() args: MutationTransitionOrderToStateArgs,
) {
return this.orderService.transitionToState(ctx, args.id, args.state as OrderState);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async transitionFulfillmentToState(
@Ctx() ctx: RequestContext,
@Args() args: MutationTransitionFulfillmentToStateArgs,
) {
return this.orderService.transitionFulfillmentToState(ctx, args.id, args.state as FulfillmentState);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async transitionPaymentToState(
@Ctx() ctx: RequestContext,
@Args() args: MutationTransitionPaymentToStateArgs,
): Promise<ErrorResultUnion<TransitionPaymentToStateResult, Payment>> {
return this.orderService.transitionPaymentToState(ctx, args.id, args.state as PaymentState);
}
@Transaction('manual')
@Mutation()
@Allow(Permission.UpdateOrder)
async modifyOrder(@Ctx() ctx: RequestContext, @Args() args: MutationModifyOrderArgs) {
await this.connection.startTransaction(ctx);
const result = await this.orderService.modifyOrder(ctx, args.input);
if (args.input.dryRun || isGraphQlErrorResult(result)) {
await this.connection.rollBackTransaction(ctx);
} else {
await this.connection.commitOpenTransaction(ctx);
}
return result;
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateOrder)
async addManualPaymentToOrder(
@Ctx() ctx: RequestContext,
@Args() args: MutationAddManualPaymentToOrderArgs,
) {
return this.orderService.addManualPaymentToOrder(ctx, args.input);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
ConfigurableOperationDefinition,
DeletionResponse,
MutationAssignPaymentMethodsToChannelArgs,
MutationCreatePaymentMethodArgs,
MutationDeletePaymentMethodArgs,
MutationDeletePaymentMethodsArgs,
MutationRemovePaymentMethodsFromChannelArgs,
MutationUpdatePaymentMethodArgs,
Permission,
QueryPaymentMethodArgs,
QueryPaymentMethodsArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Translated } from '../../../common/types/locale-types';
import { PaymentMethod } from '../../../entity/payment-method/payment-method.entity';
import { PaymentMethodService } from '../../../service/services/payment-method.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('PaymentMethod')
export class PaymentMethodResolver {
constructor(private paymentMethodService: PaymentMethodService) {}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadPaymentMethod)
paymentMethods(
@Ctx() ctx: RequestContext,
@Args() args: QueryPaymentMethodsArgs,
@Relations(PaymentMethod) relations: RelationPaths<PaymentMethod>,
): Promise<PaginatedList<PaymentMethod>> {
return this.paymentMethodService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadPaymentMethod)
paymentMethod(
@Ctx() ctx: RequestContext,
@Args() args: QueryPaymentMethodArgs,
@Relations(PaymentMethod) relations: RelationPaths<PaymentMethod>,
): Promise<PaymentMethod | undefined> {
return this.paymentMethodService.findOne(ctx, args.id, relations);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateSettings, Permission.CreatePaymentMethod)
createPaymentMethod(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreatePaymentMethodArgs,
): Promise<PaymentMethod> {
return this.paymentMethodService.create(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdatePaymentMethod)
updatePaymentMethod(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdatePaymentMethodArgs,
): Promise<PaymentMethod> {
return this.paymentMethodService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeletePaymentMethod)
deletePaymentMethod(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeletePaymentMethodArgs,
): Promise<DeletionResponse> {
return this.paymentMethodService.delete(ctx, args.id, args.force);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeletePaymentMethod)
deletePaymentMethods(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeletePaymentMethodsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.paymentMethodService.delete(ctx, id, args.force)));
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadPaymentMethod)
paymentMethodHandlers(@Ctx() ctx: RequestContext): ConfigurableOperationDefinition[] {
return this.paymentMethodService.getPaymentMethodHandlers(ctx);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadPaymentMethod)
paymentMethodEligibilityCheckers(@Ctx() ctx: RequestContext): ConfigurableOperationDefinition[] {
return this.paymentMethodService.getPaymentMethodEligibilityCheckers(ctx);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdatePaymentMethod)
async assignPaymentMethodsToChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignPaymentMethodsToChannelArgs,
): Promise<Array<Translated<PaymentMethod>>> {
return await this.paymentMethodService.assignPaymentMethodsToChannel(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeletePaymentMethod)
async removePaymentMethodsFromChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemovePaymentMethodsFromChannelArgs,
): Promise<Array<Translated<PaymentMethod>>> {
return await this.paymentMethodService.removePaymentMethodsFromChannel(ctx, args.input);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
DeletionResult,
MutationCreateProductOptionArgs,
MutationCreateProductOptionGroupArgs,
MutationDeleteProductOptionArgs,
MutationUpdateProductOptionArgs,
MutationUpdateProductOptionGroupArgs,
Permission,
QueryProductOptionGroupArgs,
QueryProductOptionGroupsArgs,
} from '@vendure/common/lib/generated-types';
import { Translated } from '../../../common/types/locale-types';
import { ProductOption } from '../../../entity/product-option/product-option.entity';
import { ProductOptionGroup } from '../../../entity/product-option-group/product-option-group.entity';
import { ProductOptionGroupService } from '../../../service/services/product-option-group.service';
import { ProductOptionService } from '../../../service/services/product-option.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class ProductOptionResolver {
constructor(
private productOptionGroupService: ProductOptionGroupService,
private productOptionService: ProductOptionService,
) {}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct)
productOptionGroups(
@Ctx() ctx: RequestContext,
@Args() args: QueryProductOptionGroupsArgs,
@Relations(ProductOptionGroup) relations: RelationPaths<ProductOptionGroup>,
): Promise<Array<Translated<ProductOptionGroup>>> {
return this.productOptionGroupService.findAll(ctx, args.filterTerm || undefined);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct)
productOptionGroup(
@Ctx() ctx: RequestContext,
@Args() args: QueryProductOptionGroupArgs,
@Relations(ProductOptionGroup) relations: RelationPaths<ProductOptionGroup>,
): Promise<Translated<ProductOptionGroup> | undefined> {
return this.productOptionGroupService.findOne(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateProduct)
async createProductOptionGroup(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateProductOptionGroupArgs,
): Promise<Translated<ProductOptionGroup>> {
const { input } = args;
const group = await this.productOptionGroupService.create(ctx, input);
if (input.options && input.options.length) {
for (const option of input.options) {
const newOption = await this.productOptionService.create(ctx, group, option);
group.options.push(newOption);
}
}
return group;
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async updateProductOptionGroup(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateProductOptionGroupArgs,
): Promise<Translated<ProductOptionGroup>> {
const { input } = args;
return this.productOptionGroupService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateProduct)
async createProductOption(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateProductOptionArgs,
): Promise<Translated<ProductOption>> {
const { input } = args;
return this.productOptionService.create(ctx, input.productOptionGroupId, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async updateProductOption(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateProductOptionArgs,
): Promise<Translated<ProductOption>> {
const { input } = args;
return this.productOptionService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteProduct)
async deleteProductOption(
@Ctx() ctx: RequestContext,
@Args() { id }: MutationDeleteProductOptionArgs,
): Promise<DeletionResponse> {
return this.productOptionService.delete(ctx, id);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationAddOptionGroupToProductArgs,
MutationAssignProductsToChannelArgs,
MutationAssignProductVariantsToChannelArgs,
MutationCreateProductArgs,
MutationCreateProductVariantsArgs,
MutationDeleteProductArgs,
MutationDeleteProductsArgs,
MutationDeleteProductVariantArgs,
MutationDeleteProductVariantsArgs,
MutationRemoveOptionGroupFromProductArgs,
MutationRemoveProductsFromChannelArgs,
MutationRemoveProductVariantsFromChannelArgs,
MutationUpdateProductArgs,
MutationUpdateProductsArgs,
MutationUpdateProductVariantsArgs,
Permission,
QueryProductArgs,
QueryProductsArgs,
QueryProductVariantArgs,
QueryProductVariantsArgs,
RemoveOptionGroupFromProductResult,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { ErrorResultUnion } from '../../../common/error/error-result';
import { UserInputError } from '../../../common/error/errors';
import { Translated } from '../../../common/types/locale-types';
import { Product } from '../../../entity/product/product.entity';
import { ProductVariant } from '../../../entity/product-variant/product-variant.entity';
import { FacetValueService } from '../../../service/services/facet-value.service';
import { ProductVariantService } from '../../../service/services/product-variant.service';
import { ProductService } from '../../../service/services/product.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class ProductResolver {
constructor(
private productService: ProductService,
private productVariantService: ProductVariantService,
private facetValueService: FacetValueService,
) {}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct)
async products(
@Ctx() ctx: RequestContext,
@Args() args: QueryProductsArgs,
@Relations({ entity: Product, omit: ['variants', 'assets'] }) relations: RelationPaths<Product>,
): Promise<PaginatedList<Translated<Product>>> {
return this.productService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct)
async product(
@Ctx() ctx: RequestContext,
@Args() args: QueryProductArgs,
@Relations({ entity: Product, omit: ['variants', 'assets'] }) relations: RelationPaths<Product>,
): Promise<Translated<Product> | undefined> {
if (args.id) {
const product = await this.productService.findOne(ctx, args.id, relations);
if (args.slug && product && product.slug !== args.slug) {
throw new UserInputError('error.product-id-slug-mismatch');
}
return product;
} else if (args.slug) {
return this.productService.findOneBySlug(ctx, args.slug, relations);
} else {
throw new UserInputError('error.product-id-or-slug-must-be-provided');
}
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct)
async productVariants(
@Ctx() ctx: RequestContext,
@Args() args: QueryProductVariantsArgs,
@Relations({ entity: ProductVariant, omit: ['assets'] }) relations: RelationPaths<ProductVariant>,
): Promise<PaginatedList<Translated<ProductVariant>>> {
if (args.productId) {
return this.productVariantService.getVariantsByProductId(
ctx,
args.productId,
args.options || undefined,
relations,
);
}
return this.productVariantService.findAll(ctx, args.options || undefined);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct)
async productVariant(
@Ctx() ctx: RequestContext,
@Args() args: QueryProductVariantArgs,
): Promise<Translated<ProductVariant> | undefined> {
return this.productVariantService.findOne(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateCatalog, Permission.CreateProduct)
async createProduct(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateProductArgs,
): Promise<Translated<Product>> {
const { input } = args;
return this.productService.create(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async updateProduct(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateProductArgs,
): Promise<Translated<Product>> {
const { input } = args;
return await this.productService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async updateProducts(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateProductsArgs,
): Promise<Array<Translated<Product>>> {
const { input } = args;
return await Promise.all(args.input.map(i => this.productService.update(ctx, i)));
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteProduct)
async deleteProduct(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteProductArgs,
): Promise<DeletionResponse> {
return this.productService.softDelete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteProduct)
async deleteProducts(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteProductsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.productService.softDelete(ctx, id)));
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async addOptionGroupToProduct(
@Ctx() ctx: RequestContext,
@Args() args: MutationAddOptionGroupToProductArgs,
): Promise<Translated<Product>> {
const { productId, optionGroupId } = args;
return this.productService.addOptionGroupToProduct(ctx, productId, optionGroupId);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async removeOptionGroupFromProduct(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveOptionGroupFromProductArgs,
): Promise<ErrorResultUnion<RemoveOptionGroupFromProductResult, Translated<Product>>> {
const { productId, optionGroupId, force } = args;
return this.productService.removeOptionGroupFromProduct(ctx, productId, optionGroupId, force);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async createProductVariants(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateProductVariantsArgs,
): Promise<Array<Translated<ProductVariant>>> {
const { input } = args;
return this.productVariantService.create(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async updateProductVariants(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateProductVariantsArgs,
): Promise<Array<Translated<ProductVariant>>> {
const { input } = args;
return this.productVariantService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteProduct)
async deleteProductVariant(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteProductVariantArgs,
): Promise<DeletionResponse> {
return this.productVariantService.softDelete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteCatalog, Permission.DeleteProduct)
async deleteProductVariants(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteProductVariantsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.productVariantService.softDelete(ctx, id)));
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async assignProductsToChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignProductsToChannelArgs,
): Promise<Array<Translated<Product>>> {
return this.productService.assignProductsToChannel(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async removeProductsFromChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveProductsFromChannelArgs,
): Promise<Array<Translated<Product>>> {
return this.productService.removeProductsFromChannel(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async assignProductVariantsToChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignProductVariantsToChannelArgs,
): Promise<Array<Translated<ProductVariant>>> {
return this.productVariantService.assignProductVariantsToChannel(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async removeProductVariantsFromChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveProductVariantsFromChannelArgs,
): Promise<Array<Translated<ProductVariant>>> {
return this.productVariantService.removeProductVariantsFromChannel(ctx, args.input);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
CreatePromotionResult,
DeletionResponse,
MutationAssignPromotionsToChannelArgs,
MutationCreatePromotionArgs,
MutationDeletePromotionArgs,
MutationDeletePromotionsArgs,
MutationRemovePromotionsFromChannelArgs,
MutationUpdatePromotionArgs,
Permission,
QueryPromotionArgs,
QueryPromotionsArgs,
UpdatePromotionResult,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { ErrorResultUnion } from '../../../common/error/error-result';
import { PromotionItemAction, PromotionOrderAction } from '../../../config/promotion/promotion-action';
import { PromotionCondition } from '../../../config/promotion/promotion-condition';
import { Promotion } from '../../../entity/promotion/promotion.entity';
import { PromotionService } from '../../../service/services/promotion.service';
import { ConfigurableOperationCodec } from '../../common/configurable-operation-codec';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Promotion')
export class PromotionResolver {
constructor(
private promotionService: PromotionService,
private configurableOperationCodec: ConfigurableOperationCodec,
) {}
@Query()
@Allow(Permission.ReadPromotion)
promotions(
@Ctx() ctx: RequestContext,
@Args() args: QueryPromotionsArgs,
@Relations(Promotion) relations: RelationPaths<Promotion>,
): Promise<PaginatedList<Promotion>> {
return this.promotionService.findAll(ctx, args.options || undefined, relations).then(res => {
res.items.forEach(this.encodeConditionsAndActions);
return res;
});
}
@Query()
@Allow(Permission.ReadPromotion)
promotion(
@Ctx() ctx: RequestContext,
@Args() args: QueryPromotionArgs,
@Relations(Promotion) relations: RelationPaths<Promotion>,
): Promise<Promotion | undefined> {
return this.promotionService.findOne(ctx, args.id, relations).then(this.encodeConditionsAndActions);
}
@Query()
@Allow(Permission.ReadPromotion)
promotionConditions(@Ctx() ctx: RequestContext) {
return this.promotionService.getPromotionConditions(ctx);
}
@Query()
@Allow(Permission.ReadPromotion)
promotionActions(@Ctx() ctx: RequestContext) {
return this.promotionService.getPromotionActions(ctx);
}
@Transaction()
@Mutation()
@Allow(Permission.CreatePromotion)
createPromotion(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreatePromotionArgs,
): Promise<ErrorResultUnion<CreatePromotionResult, Promotion>> {
this.configurableOperationCodec.decodeConfigurableOperationIds(
PromotionOrderAction,
args.input.actions,
);
this.configurableOperationCodec.decodeConfigurableOperationIds(
PromotionCondition,
args.input.conditions,
);
return this.promotionService.createPromotion(ctx, args.input).then(this.encodeConditionsAndActions);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdatePromotion)
updatePromotion(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdatePromotionArgs,
): Promise<ErrorResultUnion<UpdatePromotionResult, Promotion>> {
this.configurableOperationCodec.decodeConfigurableOperationIds(
PromotionOrderAction,
args.input.actions || [],
);
this.configurableOperationCodec.decodeConfigurableOperationIds(
PromotionItemAction,
args.input.actions || [],
);
this.configurableOperationCodec.decodeConfigurableOperationIds(
PromotionCondition,
args.input.conditions || [],
);
return this.promotionService.updatePromotion(ctx, args.input).then(this.encodeConditionsAndActions);
}
@Transaction()
@Mutation()
@Allow(Permission.DeletePromotion)
deletePromotion(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeletePromotionArgs,
): Promise<DeletionResponse> {
return this.promotionService.softDeletePromotion(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeletePromotion)
deletePromotions(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeletePromotionsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.promotionService.softDeletePromotion(ctx, id)));
}
@Transaction()
@Mutation()
@Allow(Permission.UpdatePromotion)
assignPromotionsToChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignPromotionsToChannelArgs,
): Promise<Promotion[]> {
return this.promotionService.assignPromotionsToChannel(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdatePromotion)
removePromotionsFromChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemovePromotionsFromChannelArgs,
): Promise<Promotion[]> {
return this.promotionService.removePromotionsFromChannel(ctx, args.input);
}
/**
* Encodes any entity IDs used in the filter arguments.
*/
private encodeConditionsAndActions = <
T extends ErrorResultUnion<CreatePromotionResult, Promotion> | undefined,
>(
maybePromotion: T,
): T => {
if (maybePromotion instanceof Promotion) {
this.configurableOperationCodec.encodeConfigurableOperationIds(
PromotionOrderAction,
maybePromotion.actions,
);
this.configurableOperationCodec.encodeConfigurableOperationIds(
PromotionCondition,
maybePromotion.conditions,
);
}
return maybePromotion;
};
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationCreateRoleArgs,
MutationDeleteRoleArgs,
MutationDeleteRolesArgs,
MutationUpdateRoleArgs,
Permission,
QueryRoleArgs,
QueryRolesArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Role } from '../../../entity/role/role.entity';
import { RoleService } from '../../../service/services/role.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Roles')
export class RoleResolver {
constructor(private roleService: RoleService) {}
@Query()
@Allow(Permission.ReadAdministrator)
roles(
@Ctx() ctx: RequestContext,
@Args() args: QueryRolesArgs,
@Relations(Role) relations: RelationPaths<Role>,
): Promise<PaginatedList<Role>> {
return this.roleService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadAdministrator)
role(
@Ctx() ctx: RequestContext,
@Args() args: QueryRoleArgs,
@Relations(Role) relations: RelationPaths<Role>,
): Promise<Role | undefined> {
return this.roleService.findOne(ctx, args.id, relations);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateAdministrator)
createRole(@Ctx() ctx: RequestContext, @Args() args: MutationCreateRoleArgs): Promise<Role> {
const { input } = args;
return this.roleService.create(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateAdministrator)
updateRole(@Ctx() ctx: RequestContext, @Args() args: MutationUpdateRoleArgs): Promise<Role> {
const { input } = args;
return this.roleService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteAdministrator)
deleteRole(@Ctx() ctx: RequestContext, @Args() args: MutationDeleteRoleArgs): Promise<DeletionResponse> {
const { id } = args;
return this.roleService.delete(ctx, id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteAdministrator)
deleteRoles(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteRolesArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.roleService.delete(ctx, id)));
}
}
|
import { Mutation, Query, ResolveField, Resolver } from '@nestjs/graphql';
import { Permission, SearchResponse } from '@vendure/common/lib/generated-types';
import { Omit } from '@vendure/common/lib/omit';
import { InternalServerError } from '../../../common/error/errors';
import { Translated } from '../../../common/types/locale-types';
import { Collection, FacetValue } from '../../../entity';
import { Allow } from '../../decorators/allow.decorator';
@Resolver()
export class SearchResolver {
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct)
async search(...args: any): Promise<Omit<SearchResponse, 'facetValues' | 'collections'>> {
throw new InternalServerError('error.no-search-plugin-configured');
}
@ResolveField()
async facetValues(...args: any[]): Promise<Array<{ facetValue: FacetValue; count: number }>> {
throw new InternalServerError('error.no-search-plugin-configured');
}
@ResolveField()
async collections(...args: any[]): Promise<Array<{ collection: Collection; count: number }>> {
throw new InternalServerError('error.no-search-plugin-configured');
}
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async reindex(...args: any[]): Promise<any> {
throw new InternalServerError('error.no-search-plugin-configured');
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadProduct)
async pendingSearchIndexUpdates(...args: any[]): Promise<any> {
throw new InternalServerError('error.no-search-plugin-configured');
}
@Mutation()
@Allow(Permission.UpdateCatalog, Permission.UpdateProduct)
async runPendingSearchIndexUpdates(...args: any[]): Promise<any> {
throw new InternalServerError('error.no-search-plugin-configured');
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationCreateSellerArgs,
MutationDeleteSellerArgs,
MutationDeleteSellersArgs,
MutationUpdateSellerArgs,
Permission,
QuerySellerArgs,
QuerySellersArgs,
SellerList,
} from '@vendure/common/lib/generated-types';
import { Seller } from '../../../entity/seller/seller.entity';
import { SellerService } from '../../../service/services/seller.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Seller')
export class SellerResolver {
constructor(private sellerService: SellerService) {}
@Query()
@Allow(Permission.ReadSeller)
async sellers(@Ctx() ctx: RequestContext, @Args() args: QuerySellersArgs): Promise<SellerList> {
return this.sellerService.findAll(ctx, args.options);
}
@Query()
@Allow(Permission.ReadSeller)
async seller(@Ctx() ctx: RequestContext, @Args() args: QuerySellerArgs): Promise<Seller | undefined> {
return this.sellerService.findOne(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateSeller)
async createSeller(@Ctx() ctx: RequestContext, @Args() args: MutationCreateSellerArgs): Promise<Seller> {
return this.sellerService.create(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSeller)
async updateSeller(@Ctx() ctx: RequestContext, @Args() args: MutationUpdateSellerArgs): Promise<Seller> {
return this.sellerService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSeller)
async deleteSeller(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteSellerArgs,
): Promise<DeletionResponse> {
return this.sellerService.delete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSeller)
async deleteSellers(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteSellersArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.sellerService.delete(ctx, id)));
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
ConfigurableOperationDefinition,
DeletionResponse,
MutationAssignShippingMethodsToChannelArgs,
MutationCreateShippingMethodArgs,
MutationDeleteShippingMethodArgs,
MutationDeleteShippingMethodsArgs,
MutationRemoveShippingMethodsFromChannelArgs,
MutationUpdateShippingMethodArgs,
Permission,
QueryShippingMethodArgs,
QueryShippingMethodsArgs,
QueryTestEligibleShippingMethodsArgs,
QueryTestShippingMethodArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Translated } from '../../../common/types/locale-types';
import { ShippingMethod } from '../../../entity/shipping-method/shipping-method.entity';
import { OrderTestingService } from '../../../service/services/order-testing.service';
import { ShippingMethodService } from '../../../service/services/shipping-method.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('ShippingMethod')
export class ShippingMethodResolver {
constructor(
private shippingMethodService: ShippingMethodService,
private orderTestingService: OrderTestingService,
) {}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadShippingMethod)
shippingMethods(
@Ctx() ctx: RequestContext,
@Args() args: QueryShippingMethodsArgs,
@Relations(ShippingMethod) relations: RelationPaths<ShippingMethod>,
): Promise<PaginatedList<ShippingMethod>> {
return this.shippingMethodService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadShippingMethod)
shippingMethod(
@Ctx() ctx: RequestContext,
@Args() args: QueryShippingMethodArgs,
@Relations(ShippingMethod) relations: RelationPaths<ShippingMethod>,
): Promise<ShippingMethod | undefined> {
return this.shippingMethodService.findOne(ctx, args.id, false, relations);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadOrder, Permission.ReadShippingMethod)
shippingEligibilityCheckers(@Ctx() ctx: RequestContext): ConfigurableOperationDefinition[] {
return this.shippingMethodService.getShippingEligibilityCheckers(ctx);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadOrder, Permission.ReadShippingMethod)
shippingCalculators(@Ctx() ctx: RequestContext): ConfigurableOperationDefinition[] {
return this.shippingMethodService.getShippingCalculators(ctx);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadOrder, Permission.ReadShippingMethod)
fulfillmentHandlers(@Ctx() ctx: RequestContext): ConfigurableOperationDefinition[] {
return this.shippingMethodService.getFulfillmentHandlers(ctx);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateSettings, Permission.CreateShippingMethod)
createShippingMethod(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateShippingMethodArgs,
): Promise<ShippingMethod> {
const { input } = args;
return this.shippingMethodService.create(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateShippingMethod)
updateShippingMethod(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateShippingMethodArgs,
): Promise<ShippingMethod> {
const { input } = args;
return this.shippingMethodService.update(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteShippingMethod)
deleteShippingMethod(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteShippingMethodArgs,
): Promise<DeletionResponse> {
const { id } = args;
return this.shippingMethodService.softDelete(ctx, id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteShippingMethod)
deleteShippingMethods(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteShippingMethodsArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids?.map(id => this.shippingMethodService.softDelete(ctx, id)) ?? []);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadShippingMethod)
testShippingMethod(@Ctx() ctx: RequestContext, @Args() args: QueryTestShippingMethodArgs) {
const { input } = args;
return this.orderTestingService.testShippingMethod(ctx, input);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadShippingMethod)
testEligibleShippingMethods(
@Ctx() ctx: RequestContext,
@Args() args: QueryTestEligibleShippingMethodsArgs,
) {
const { input } = args;
return this.orderTestingService.testEligibleShippingMethods(ctx, input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateShippingMethod)
async assignShippingMethodsToChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignShippingMethodsToChannelArgs,
): Promise<Array<Translated<ShippingMethod>>> {
return await this.shippingMethodService.assignShippingMethodsToChannel(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteShippingMethod)
async removeShippingMethodsFromChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveShippingMethodsFromChannelArgs,
): Promise<Array<Translated<ShippingMethod>>> {
return await this.shippingMethodService.removeShippingMethodsFromChannel(ctx, args.input);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
MutationAssignStockLocationsToChannelArgs,
MutationCreateStockLocationArgs,
MutationDeleteStockLocationArgs,
MutationDeleteStockLocationsArgs,
MutationRemoveStockLocationsFromChannelArgs,
MutationUpdateStockLocationArgs,
Permission,
QueryStockLocationArgs,
QueryStockLocationsArgs,
} from '@vendure/common/lib/generated-types';
import { StockLocationService } from '../../../service/services/stock-location.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class StockLocationResolver {
constructor(private stockLocationService: StockLocationService) {}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadStockLocation)
stockLocation(@Ctx() ctx: RequestContext, @Args() args: QueryStockLocationArgs) {
return this.stockLocationService.findOne(ctx, args.id);
}
@Query()
@Allow(Permission.ReadCatalog, Permission.ReadStockLocation)
stockLocations(@Ctx() ctx: RequestContext, @Args() args: QueryStockLocationsArgs) {
return this.stockLocationService.findAll(ctx, args.options);
}
@Mutation()
@Transaction()
@Allow(Permission.CreateStockLocation)
createStockLocation(@Ctx() ctx: RequestContext, @Args() args: MutationCreateStockLocationArgs) {
return this.stockLocationService.create(ctx, args.input);
}
@Mutation()
@Transaction()
@Allow(Permission.UpdateStockLocation)
updateStockLocation(@Ctx() ctx: RequestContext, @Args() args: MutationUpdateStockLocationArgs) {
return this.stockLocationService.update(ctx, args.input);
}
@Mutation()
@Transaction()
@Allow(Permission.DeleteStockLocation)
deleteStockLocation(@Ctx() ctx: RequestContext, @Args() args: MutationDeleteStockLocationArgs) {
return this.stockLocationService.delete(ctx, args.input);
}
@Mutation()
@Transaction()
@Allow(Permission.DeleteStockLocation)
deleteStockLocations(@Ctx() ctx: RequestContext, @Args() args: MutationDeleteStockLocationsArgs) {
return Promise.all(args.input.map(input => this.stockLocationService.delete(ctx, input)));
}
@Mutation()
@Transaction()
@Allow(Permission.CreateStockLocation)
assignStockLocationsToChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationAssignStockLocationsToChannelArgs,
) {
return this.stockLocationService.assignStockLocationsToChannel(ctx, args.input);
}
@Mutation()
@Transaction()
@Allow(Permission.DeleteStockLocation)
removeStockLocationsFromChannel(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveStockLocationsFromChannelArgs,
) {
return this.stockLocationService.removeStockLocationsFromChannel(ctx, args.input);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationCreateTagArgs,
MutationDeleteTagArgs,
MutationUpdateTagArgs,
Permission,
QueryTagArgs,
QueryTagsArgs,
TagList,
} from '@vendure/common/lib/generated-types';
import { Tag } from '../../../entity/tag/tag.entity';
import { TagService } from '../../../service/services/tag.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('Tag')
export class TagResolver {
constructor(private tagService: TagService) {}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadTag, Permission.ReadAsset)
async tags(@Ctx() ctx: RequestContext, @Args() args: QueryTagsArgs): Promise<TagList> {
return this.tagService.findAll(ctx, args.options);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadTag, Permission.ReadAsset)
async tag(@Ctx() ctx: RequestContext, @Args() args: QueryTagArgs): Promise<Tag | undefined> {
return this.tagService.findOne(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateSettings, Permission.CreateTag)
async createTag(@Ctx() ctx: RequestContext, @Args() args: MutationCreateTagArgs): Promise<Tag> {
return this.tagService.create(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateTag)
async updateTag(@Ctx() ctx: RequestContext, @Args() args: MutationUpdateTagArgs): Promise<Tag> {
return this.tagService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteTag)
async deleteTag(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteTagArgs,
): Promise<DeletionResponse> {
return this.tagService.delete(ctx, args.id);
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationCreateTaxCategoryArgs,
MutationDeleteTaxCategoryArgs,
MutationUpdateTaxCategoryArgs,
MutationDeleteTaxCategoriesArgs,
Permission,
QueryTaxCategoriesArgs,
QueryTaxCategoryArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { TaxCategory } from '../../../entity/tax-category/tax-category.entity';
import { TaxCategoryService } from '../../../service/services/tax-category.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('TaxCategory')
export class TaxCategoryResolver {
constructor(private taxCategoryService: TaxCategoryService) {}
@Query()
@Allow(
Permission.ReadSettings,
Permission.ReadCatalog,
Permission.ReadProduct,
Permission.ReadTaxCategory,
)
async taxCategories(
@Ctx() ctx: RequestContext,
@Args() args: QueryTaxCategoriesArgs,
): Promise<PaginatedList<TaxCategory>> {
return this.taxCategoryService.findAll(ctx, args.options || undefined);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadTaxCategory)
async taxCategory(
@Ctx() ctx: RequestContext,
@Args() args: QueryTaxCategoryArgs,
): Promise<TaxCategory | undefined> {
return this.taxCategoryService.findOne(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateSettings, Permission.CreateTaxCategory)
async createTaxCategory(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateTaxCategoryArgs,
): Promise<TaxCategory> {
return this.taxCategoryService.create(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateTaxCategory)
async updateTaxCategory(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateTaxCategoryArgs,
): Promise<TaxCategory> {
return this.taxCategoryService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteTaxCategory)
async deleteTaxCategory(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteTaxCategoryArgs,
): Promise<DeletionResponse> {
return this.taxCategoryService.delete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteTaxCategory)
async deleteTaxCategories(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteTaxCategoriesArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.taxCategoryService.delete(ctx, id)));
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationCreateTaxRateArgs,
MutationDeleteTaxRateArgs,
MutationUpdateTaxRateArgs,
MutationDeleteTaxRatesArgs,
Permission,
QueryTaxRateArgs,
QueryTaxRatesArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { TaxRate } from '../../../entity/tax-rate/tax-rate.entity';
import { TaxRateService } from '../../../service/services/tax-rate.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver('TaxRate')
export class TaxRateResolver {
constructor(private taxRateService: TaxRateService) {}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadCatalog, Permission.ReadProduct, Permission.ReadTaxRate)
async taxRates(
@Ctx() ctx: RequestContext,
@Args() args: QueryTaxRatesArgs,
@Relations(TaxRate) relations: RelationPaths<TaxRate>,
): Promise<PaginatedList<TaxRate>> {
return this.taxRateService.findAll(ctx, args.options || undefined, relations);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadCatalog, Permission.ReadTaxRate)
async taxRate(
@Ctx() ctx: RequestContext,
@Args() args: QueryTaxRateArgs,
@Relations(TaxRate) relations: RelationPaths<TaxRate>,
): Promise<TaxRate | undefined> {
return this.taxRateService.findOne(ctx, args.id, relations);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateSettings, Permission.CreateTaxRate)
async createTaxRate(
@Ctx() ctx: RequestContext,
@Args() args: MutationCreateTaxRateArgs,
): Promise<TaxRate> {
return this.taxRateService.create(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateTaxRate)
async updateTaxRate(
@Ctx() ctx: RequestContext,
@Args() args: MutationUpdateTaxRateArgs,
): Promise<TaxRate> {
return this.taxRateService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteTaxRate)
async deleteTaxRate(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteTaxRateArgs,
): Promise<DeletionResponse> {
return this.taxRateService.delete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteTaxRate)
async deleteTaxRates(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteTaxRatesArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.taxRateService.delete(ctx, id)));
}
}
|
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import {
DeletionResponse,
MutationAddMembersToZoneArgs,
MutationCreateZoneArgs,
MutationDeleteZoneArgs,
MutationDeleteZonesArgs,
MutationRemoveMembersFromZoneArgs,
MutationUpdateZoneArgs,
Permission,
QueryZoneArgs,
QueryZonesArgs,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Zone } from '../../../entity/zone/zone.entity';
import { ZoneService } from '../../../service/services/zone.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
import { Transaction } from '../../decorators/transaction.decorator';
@Resolver()
export class ZoneResolver {
constructor(private zoneService: ZoneService) {}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadZone)
zones(@Ctx() ctx: RequestContext, @Args() args: QueryZonesArgs): Promise<PaginatedList<Zone>> {
return this.zoneService.findAll(ctx, args.options || undefined);
}
@Query()
@Allow(Permission.ReadSettings, Permission.ReadZone)
async zone(@Ctx() ctx: RequestContext, @Args() args: QueryZoneArgs): Promise<Zone | undefined> {
return this.zoneService.findOne(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.CreateSettings, Permission.CreateZone)
async createZone(@Ctx() ctx: RequestContext, @Args() args: MutationCreateZoneArgs): Promise<Zone> {
return this.zoneService.create(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateZone)
async updateZone(@Ctx() ctx: RequestContext, @Args() args: MutationUpdateZoneArgs): Promise<Zone> {
return this.zoneService.update(ctx, args.input);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteZone)
async deleteZone(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteZoneArgs,
): Promise<DeletionResponse> {
return this.zoneService.delete(ctx, args.id);
}
@Transaction()
@Mutation()
@Allow(Permission.DeleteSettings, Permission.DeleteZone)
async deleteZones(
@Ctx() ctx: RequestContext,
@Args() args: MutationDeleteZonesArgs,
): Promise<DeletionResponse[]> {
return Promise.all(args.ids.map(id => this.zoneService.delete(ctx, id)));
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateZone)
async addMembersToZone(
@Ctx() ctx: RequestContext,
@Args() args: MutationAddMembersToZoneArgs,
): Promise<Zone> {
return this.zoneService.addMembersToZone(ctx, args);
}
@Transaction()
@Mutation()
@Allow(Permission.UpdateSettings, Permission.UpdateZone)
async removeMembersFromZone(
@Ctx() ctx: RequestContext,
@Args() args: MutationRemoveMembersFromZoneArgs,
): Promise<Zone> {
return this.zoneService.removeMembersFromZone(ctx, args);
}
}
|
import {
AuthenticationResult as ShopAuthenticationResult,
PasswordValidationError,
} from '@vendure/common/lib/generated-shop-types';
import {
AuthenticationResult as AdminAuthenticationResult,
CurrentUser,
CurrentUserChannel,
MutationAuthenticateArgs,
MutationLoginArgs,
Success,
} from '@vendure/common/lib/generated-types';
import { Request, Response } from 'express';
import { isGraphQlErrorResult } from '../../../common/error/error-result';
import { ForbiddenError } from '../../../common/error/errors';
import {
InvalidCredentialsError,
NotVerifiedError,
} from '../../../common/error/generated-graphql-shop-errors';
import { NATIVE_AUTH_STRATEGY_NAME } from '../../../config/auth/native-authentication-strategy';
import { ConfigService } from '../../../config/config.service';
import { LogLevel } from '../../../config/logger/vendure-logger';
import { User } from '../../../entity/user/user.entity';
import { getUserChannelsPermissions } from '../../../service/helpers/utils/get-user-channels-permissions';
import { AdministratorService } from '../../../service/services/administrator.service';
import { AuthService } from '../../../service/services/auth.service';
import { UserService } from '../../../service/services/user.service';
import { extractSessionToken } from '../../common/extract-session-token';
import { ApiType } from '../../common/get-api-type';
import { RequestContext } from '../../common/request-context';
import { setSessionToken } from '../../common/set-session-token';
export class BaseAuthResolver {
constructor(
protected authService: AuthService,
protected userService: UserService,
protected administratorService: AdministratorService,
protected configService: ConfigService,
) {}
/**
* Attempts a login given the username and password of a user. If successful, returns
* the user data and returns the token either in a cookie or in the response body.
*/
async baseLogin(
args: MutationLoginArgs,
ctx: RequestContext,
req: Request,
res: Response,
): Promise<AdminAuthenticationResult | ShopAuthenticationResult | NotVerifiedError> {
return await this.authenticateAndCreateSession(
ctx,
{
input: { [NATIVE_AUTH_STRATEGY_NAME]: args },
rememberMe: args.rememberMe,
},
req,
res,
);
}
async logout(ctx: RequestContext, req: Request, res: Response): Promise<Success> {
const token = extractSessionToken(req, this.configService.authOptions.tokenMethod);
if (!token) {
return { success: false };
}
await this.authService.destroyAuthenticatedSession(ctx, token);
setSessionToken({
req,
res,
authOptions: this.configService.authOptions,
rememberMe: false,
sessionToken: '',
});
return { success: true };
}
/**
* Returns information about the current authenticated user.
*/
async me(ctx: RequestContext, apiType: ApiType) {
const userId = ctx.activeUserId;
if (!userId) {
throw new ForbiddenError(LogLevel.Verbose);
}
if (apiType === 'admin') {
const administrator = await this.administratorService.findOneByUserId(ctx, userId);
if (!administrator) {
throw new ForbiddenError(LogLevel.Verbose);
}
}
const user = userId && (await this.userService.getUserById(ctx, userId));
return user ? this.publiclyAccessibleUser(user) : null;
}
/**
* Creates an authenticated session and sets the session token.
*/
protected async authenticateAndCreateSession(
ctx: RequestContext,
args: MutationAuthenticateArgs,
req: Request,
res: Response,
): Promise<AdminAuthenticationResult | ShopAuthenticationResult | NotVerifiedError> {
const [method, data] = Object.entries(args.input)[0];
const { apiType } = ctx;
const session = await this.authService.authenticate(ctx, apiType, method, data);
if (isGraphQlErrorResult(session)) {
return session;
}
if (apiType && apiType === 'admin') {
const administrator = await this.administratorService.findOneByUserId(ctx, session.user.id);
if (!administrator) {
return new InvalidCredentialsError({ authenticationError: '' });
}
}
setSessionToken({
req,
res,
authOptions: this.configService.authOptions,
rememberMe: args.rememberMe || false,
sessionToken: session.token,
});
return this.publiclyAccessibleUser(session.user);
}
/**
* Updates the password of an existing User.
*/
protected async updatePassword(
ctx: RequestContext,
currentPassword: string,
newPassword: string,
): Promise<boolean | InvalidCredentialsError | PasswordValidationError> {
const { activeUserId } = ctx;
if (!activeUserId) {
throw new ForbiddenError();
}
return this.userService.updatePassword(ctx, activeUserId, currentPassword, newPassword);
}
/**
* Exposes a subset of the User properties which we want to expose to the public API.
*/
protected publiclyAccessibleUser(user: User): CurrentUser {
return {
id: user.id,
identifier: user.identifier,
channels: getUserChannelsPermissions(user) as CurrentUserChannel[],
};
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { TransactionalConnection } from '../../../connection/transactional-connection';
import { Administrator } from '../../../entity/administrator/administrator.entity';
import { User } from '../../../entity/user/user.entity';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Administrator')
export class AdministratorEntityResolver {
constructor(private connection: TransactionalConnection) {}
@ResolveField()
async user(@Ctx() ctx: RequestContext, @Parent() administrator: Administrator): Promise<User> {
if (administrator.user) {
return administrator.user;
}
const { user } = await this.connection.getEntityOrThrow(ctx, Administrator, administrator.id, {
relations: {
user: { roles: true },
},
});
return user;
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Asset } from '../../../entity/asset/asset.entity';
import { Tag } from '../../../entity/tag/tag.entity';
import { TagService } from '../../../service/services/tag.service';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Asset')
export class AssetEntityResolver {
constructor(private tagService: TagService) {}
@ResolveField()
async tags(@Ctx() ctx: RequestContext, @Parent() asset: Asset): Promise<Tag[]> {
if (asset.tags) {
return asset.tags;
}
return this.tagService.getTagsForEntity(ctx, Asset, asset.id);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Channel } from '../../../entity/channel/channel.entity';
import { Seller } from '../../../entity/seller/seller.entity';
import { SellerService } from '../../../service/services/seller.service';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Channel')
export class ChannelEntityResolver {
constructor(private sellerService: SellerService) {}
@ResolveField()
async seller(@Ctx() ctx: RequestContext, @Parent() channel: Channel): Promise<Seller | undefined> {
return channel.sellerId
? channel.seller ?? (await this.sellerService.findOne(ctx, channel.sellerId))
: undefined;
}
@ResolveField()
currencyCode(@Ctx() ctx: RequestContext, @Parent() channel: Channel): string {
return channel.defaultCurrencyCode;
}
}
|
import { Logger } from '@nestjs/common';
import { Args, Parent, ResolveField, Resolver } from '@nestjs/graphql';
import {
CollectionBreadcrumb,
ConfigurableOperation,
ProductVariantListOptions,
} from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { ListQueryOptions } from '../../../common/types/common-types';
import { Translated } from '../../../common/types/locale-types';
import { CollectionFilter } from '../../../config/catalog/collection-filter';
import { Asset, Collection, Product, ProductVariant } from '../../../entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { AssetService } from '../../../service/services/asset.service';
import { CollectionService } from '../../../service/services/collection.service';
import { ProductVariantService } from '../../../service/services/product-variant.service';
import { ConfigurableOperationCodec } from '../../common/configurable-operation-codec';
import { ApiType } from '../../common/get-api-type';
import { RequestContext } from '../../common/request-context';
import { Api } from '../../decorators/api.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Collection')
export class CollectionEntityResolver {
constructor(
private productVariantService: ProductVariantService,
private collectionService: CollectionService,
private assetService: AssetService,
private localeStringHydrator: LocaleStringHydrator,
private configurableOperationCodec: ConfigurableOperationCodec,
) {}
@ResolveField()
name(@Ctx() ctx: RequestContext, @Parent() collection: Collection): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, collection, 'name');
}
@ResolveField()
slug(@Ctx() ctx: RequestContext, @Parent() collection: Collection): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, collection, 'slug');
}
@ResolveField()
description(@Ctx() ctx: RequestContext, @Parent() collection: Collection): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, collection, 'description');
}
@ResolveField()
languageCode(@Ctx() ctx: RequestContext, @Parent() collection: Collection): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, collection, 'languageCode');
}
@ResolveField()
async productVariants(
@Ctx() ctx: RequestContext,
@Parent() collection: Collection,
@Args() args: { options: ProductVariantListOptions },
@Api() apiType: ApiType,
@Relations({ entity: ProductVariant, omit: ['assets'] }) relations: RelationPaths<ProductVariant>,
): Promise<PaginatedList<Translated<ProductVariant>>> {
let options: ListQueryOptions<Product> = args.options;
if (apiType === 'shop') {
options = {
...args.options,
filter: {
...(args.options ? args.options.filter : {}),
enabled: { eq: true },
},
};
}
return this.productVariantService.getVariantsByCollectionId(ctx, collection.id, options, relations);
}
@ResolveField()
async breadcrumbs(
@Ctx() ctx: RequestContext,
@Parent() collection: Collection,
): Promise<CollectionBreadcrumb[]> {
return this.collectionService.getBreadcrumbs(ctx, collection) as any;
}
@ResolveField()
async parent(
@Ctx() ctx: RequestContext,
@Parent() collection: Collection,
@Api() apiType: ApiType,
): Promise<Collection | undefined> {
let parent: Collection | undefined;
if (collection.parent) {
parent = collection.parent;
} else {
parent = await this.collectionService.getParent(ctx, collection.id);
}
return apiType === 'shop' && parent?.isPrivate ? undefined : parent;
}
@ResolveField()
async children(
@Ctx() ctx: RequestContext,
@Parent() collection: Collection,
@Api() apiType: ApiType,
): Promise<Collection[]> {
let children: Collection[] = [];
if (collection.children) {
children = collection.children.sort((a, b) => a.position - b.position);
} else {
children = (await this.collectionService.getChildren(ctx, collection.id)) as any;
}
return children.filter(c => (apiType === 'shop' ? !c.isPrivate : true));
}
@ResolveField()
async featuredAsset(
@Ctx() ctx: RequestContext,
@Parent() collection: Collection,
): Promise<Asset | undefined> {
if (collection.featuredAsset) {
return collection.featuredAsset;
}
return this.assetService.getFeaturedAsset(ctx, collection);
}
@ResolveField()
async assets(@Ctx() ctx: RequestContext, @Parent() collection: Collection): Promise<Asset[] | undefined> {
return this.assetService.getEntityAssets(ctx, collection);
}
@ResolveField()
filters(@Ctx() ctx: RequestContext, @Parent() collection: Collection): ConfigurableOperation[] {
try {
return this.configurableOperationCodec.encodeConfigurableOperationIds(
CollectionFilter,
collection.filters,
);
} catch (e: any) {
Logger.error(
`Could not decode the collection filter arguments for "${collection.name}" (id: ${
collection.id
}). Error message: ${JSON.stringify(e.message)}`,
);
return [];
}
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Country } from '../../../entity/region/country.entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Country')
export class CountryEntityResolver {
constructor(private localeStringHydrator: LocaleStringHydrator) {}
@ResolveField()
name(@Ctx() ctx: RequestContext, @Parent() country: Country): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, country, 'name');
}
@ResolveField()
languageCode(@Ctx() ctx: RequestContext, @Parent() country: Country): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, country, 'languageCode');
}
}
|
import { Args, Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { HistoryEntryListOptions, QueryOrdersArgs, SortOrder } from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Address } from '../../../entity/address/address.entity';
import { Customer } from '../../../entity/customer/customer.entity';
import { Order } from '../../../entity/order/order.entity';
import { CustomerService } from '../../../service/services/customer.service';
import { HistoryService } from '../../../service/services/history.service';
import { OrderService } from '../../../service/services/order.service';
import { UserService } from '../../../service/services/user.service';
import { ApiType } from '../../common/get-api-type';
import { RequestContext } from '../../common/request-context';
import { Api } from '../../decorators/api.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Customer')
export class CustomerEntityResolver {
constructor(
private customerService: CustomerService,
private orderService: OrderService,
private userService: UserService,
) {}
@ResolveField()
async addresses(
@Ctx() ctx: RequestContext,
@Parent() customer: Customer,
@Api() apiType: ApiType,
): Promise<Address[]> {
if (apiType === 'shop' && !ctx.activeUserId) {
// Guest customers should not be able to see this data
return [];
}
return this.customerService.findAddressesByCustomerId(ctx, customer.id);
}
@ResolveField()
async orders(
@Ctx() ctx: RequestContext,
@Parent() customer: Customer,
@Args() args: QueryOrdersArgs,
@Api() apiType: ApiType,
@Relations(Order) relations: RelationPaths<Order>,
): Promise<PaginatedList<Order>> {
if (apiType === 'shop' && !ctx.activeUserId) {
// Guest customers should not be able to see this data
return { items: [], totalItems: 0 };
}
return this.orderService.findByCustomerId(ctx, customer.id, args.options || undefined, relations);
}
@ResolveField()
user(@Ctx() ctx: RequestContext, @Parent() customer: Customer) {
if (customer.user) {
return customer.user;
}
return this.userService.getUserByEmailAddress(ctx, customer.emailAddress, 'customer');
}
}
@Resolver('Customer')
export class CustomerAdminEntityResolver {
constructor(private customerService: CustomerService, private historyService: HistoryService) {}
@ResolveField()
groups(@Ctx() ctx: RequestContext, @Parent() customer: Customer) {
if (customer.groups) {
return customer.groups;
}
return this.customerService.getCustomerGroups(ctx, customer.id);
}
@ResolveField()
async history(
@Ctx() ctx: RequestContext,
@Api() apiType: ApiType,
@Parent() order: Order,
@Args() args: any,
) {
const publicOnly = apiType === 'shop';
const options: HistoryEntryListOptions = { ...args.options };
if (!options.sort) {
options.sort = { createdAt: SortOrder.ASC };
}
return this.historyService.getHistoryForCustomer(ctx, order.id, publicOnly, options);
}
}
|
import { Args, Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Permission, QueryCustomersArgs } from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Customer } from '../../../entity/customer/customer.entity';
import { CustomerGroup } from '../../../entity/customer-group/customer-group.entity';
import { CustomerGroupService } from '../../../service/services/customer-group.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('CustomerGroup')
export class CustomerGroupEntityResolver {
constructor(private customerGroupService: CustomerGroupService) {}
@Allow(Permission.ReadCustomer)
@ResolveField()
async customers(
@Ctx() ctx: RequestContext,
@Parent() customerGroup: CustomerGroup,
@Args() args: QueryCustomersArgs,
): Promise<PaginatedList<Customer>> {
return this.customerGroupService.getGroupCustomers(ctx, customerGroup.id, args.options || undefined);
}
}
|
import { Args, Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { FacetValueListOptions } from '@vendure/common/lib/generated-types';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { RequestContextCacheService } from '../../../cache/request-context-cache.service';
import { Facet } from '../../../entity/facet/facet.entity';
import { FacetValue } from '../../../entity/facet-value/facet-value.entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { FacetValueService } from '../../../service/services/facet-value.service';
import { RequestContext } from '../../common/request-context';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Facet')
export class FacetEntityResolver {
constructor(
private facetValueService: FacetValueService,
private localeStringHydrator: LocaleStringHydrator,
private requestContextCache: RequestContextCacheService,
) {}
@ResolveField()
name(@Ctx() ctx: RequestContext, @Parent() facetValue: FacetValue): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, facetValue, 'name');
}
@ResolveField()
languageCode(@Ctx() ctx: RequestContext, @Parent() facetValue: FacetValue): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, facetValue, 'languageCode');
}
@ResolveField()
async values(@Ctx() ctx: RequestContext, @Parent() facet: Facet): Promise<FacetValue[]> {
if (facet.values) {
return facet.values;
}
return this.requestContextCache.get(ctx, `FacetEntityResolver.values(${facet.id})`, () =>
this.facetValueService.findByFacetId(ctx, facet.id),
);
}
@ResolveField()
async valueList(
@Ctx() ctx: RequestContext,
@Parent() facet: Facet,
@Args() args: { options: FacetValueListOptions },
@Relations({ entity: FacetValue }) relations: RelationPaths<FacetValue>,
): Promise<PaginatedList<FacetValue>> {
return this.facetValueService.findByFacetIdList(ctx, facet.id, args.options, relations);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { RequestContextCacheService } from '../../../cache/request-context-cache.service';
import { Facet } from '../../../entity/facet/facet.entity';
import { FacetValue } from '../../../entity/facet-value/facet-value.entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { FacetService } from '../../../service/services/facet.service';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('FacetValue')
export class FacetValueEntityResolver {
constructor(
private facetService: FacetService,
private localeStringHydrator: LocaleStringHydrator,
private requestContextCache: RequestContextCacheService,
) {}
@ResolveField()
name(@Ctx() ctx: RequestContext, @Parent() facetValue: FacetValue): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, facetValue, 'name');
}
@ResolveField()
languageCode(@Ctx() ctx: RequestContext, @Parent() facetValue: FacetValue): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, facetValue, 'languageCode');
}
@ResolveField()
async facet(@Ctx() ctx: RequestContext, @Parent() facetValue: FacetValue): Promise<Facet | undefined> {
if (facetValue.facet) {
return facetValue.facet;
}
return this.requestContextCache.get(ctx, `FacetValueEntityResolver.facet(${facetValue.id})`, () =>
this.facetService.findByFacetValueId(ctx, facetValue.id),
);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { RequestContextCacheService } from '../../../cache/request-context-cache.service';
import { Fulfillment } from '../../../entity/fulfillment/fulfillment.entity';
import { FulfillmentService } from '../../../service/services/fulfillment.service';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Fulfillment')
export class FulfillmentEntityResolver {
constructor(
private fulfillmentService: FulfillmentService,
private requestContextCache: RequestContextCacheService,
) {}
@ResolveField()
async lines(@Ctx() ctx: RequestContext, @Parent() fulfillment: Fulfillment) {
return this.requestContextCache.get(ctx, `FulfillmentEntityResolver.lines(${fulfillment.id})`, () =>
this.fulfillmentService.getFulfillmentLines(ctx, fulfillment.id),
);
}
@ResolveField()
async summary(@Ctx() ctx: RequestContext, @Parent() fulfillment: Fulfillment) {
return this.requestContextCache.get(ctx, `FulfillmentEntityResolver.lines(${fulfillment.id})`, () =>
this.fulfillmentService.getFulfillmentLines(ctx, fulfillment.id),
);
}
}
@Resolver('Fulfillment')
export class FulfillmentAdminEntityResolver {
constructor(private fulfillmentService: FulfillmentService) {}
@ResolveField()
async nextStates(@Parent() fulfillment: Fulfillment) {
return this.fulfillmentService.getNextStates(fulfillment);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { TransactionalConnection } from '../../../connection/transactional-connection';
import { Fulfillment } from '../../../entity/fulfillment/fulfillment.entity';
import { OrderLine } from '../../../entity/order-line/order-line.entity';
import { FulfillmentLine } from '../../../entity/order-line-reference/fulfillment-line.entity';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('FulfillmentLine')
export class FulfillmentLineEntityResolver {
constructor(private connection: TransactionalConnection) {}
@ResolveField()
async orderLine(@Ctx() ctx: RequestContext, @Parent() fulfillmentLine: FulfillmentLine) {
return this.connection
.getRepository(ctx, OrderLine)
.findOne({ where: { id: fulfillmentLine.orderLineId } });
}
@ResolveField()
async fulfillment(@Ctx() ctx: RequestContext, @Parent() fulfillmentLine: FulfillmentLine) {
return this.connection
.getRepository(ctx, Fulfillment)
.findOne({ where: { id: fulfillmentLine.fulfillmentId } });
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { omit } from '@vendure/common/lib/omit';
import { pick } from '@vendure/common/lib/pick';
import { Job } from '../../../job-queue/job';
import { RequestContext, SerializedRequestContext } from '../../common/request-context';
@Resolver('Job')
export class JobEntityResolver {
private readonly graphQlMaxInt = 2 ** 31 - 1;
@ResolveField()
async duration(@Parent() job: Job) {
return Math.min(job.duration, this.graphQlMaxInt);
}
@ResolveField()
async data(@Parent() job: Job) {
const ctx = job.data.ctx;
if (this.isSerializedRequestContext(ctx)) {
// The job data includes a serialized RequestContext object
// This can be very large, so we will manually prune it before
// returning
const prunedCtx = {
...pick(ctx, [
'_apiType',
'_languageCode',
'_authorizedAsOwnerOnly',
'_isAuthorized',
'_channel',
]),
_session: ctx._session
? {
...ctx._session,
user: ctx._session.user ? omit(ctx._session.user, ['channelPermissions']) : {},
}
: {},
};
job.data.ctx = prunedCtx;
}
return job.data;
}
private isSerializedRequestContext(input: unknown): input is SerializedRequestContext {
if (typeof input !== 'object' || input == null) {
return false;
}
return (
typeof input === 'object' &&
input.hasOwnProperty('_apiType') &&
input.hasOwnProperty('_channel') &&
input.hasOwnProperty('_languageCode')
);
}
}
|
import { Args, Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { HistoryEntryListOptions, OrderHistoryArgs, SortOrder } from '@vendure/common/lib/generated-types';
import { assertFound, idsAreEqual } from '../../../common/utils';
import { Order } from '../../../entity/order/order.entity';
import { CustomerService, TranslatorService } from '../../../service/index';
import { HistoryService } from '../../../service/services/history.service';
import { OrderService } from '../../../service/services/order.service';
import { ApiType } from '../../common/get-api-type';
import { RequestContext } from '../../common/request-context';
import { Api } from '../../decorators/api.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Order')
export class OrderEntityResolver {
constructor(
private orderService: OrderService,
private customerService: CustomerService,
private historyService: HistoryService,
private translator: TranslatorService,
) {}
@ResolveField()
async payments(@Ctx() ctx: RequestContext, @Parent() order: Order) {
if (order.payments) {
return order.payments;
}
return this.orderService.getOrderPayments(ctx, order.id);
}
@ResolveField()
async fulfillments(@Ctx() ctx: RequestContext, @Parent() order: Order) {
if (order.fulfillments) {
return order.fulfillments;
}
return this.orderService.getOrderFulfillments(ctx, order);
}
@ResolveField()
async surcharges(@Ctx() ctx: RequestContext, @Parent() order: Order) {
if (order.surcharges) {
return order.surcharges;
}
return this.orderService.getOrderSurcharges(ctx, order.id);
}
@ResolveField()
async customer(@Ctx() ctx: RequestContext, @Parent() order: Order) {
if (order.customer) {
return order.customer;
}
if (order.customerId) {
return this.customerService.findOne(ctx, order.customerId);
}
}
@ResolveField()
async lines(@Ctx() ctx: RequestContext, @Parent() order: Order) {
if (order.lines) {
return order.lines;
}
const { lines } = await assertFound(this.orderService.findOne(ctx, order.id));
return lines;
}
@ResolveField()
async history(
@Ctx() ctx: RequestContext,
@Api() apiType: ApiType,
@Parent() order: Order,
@Args() args: OrderHistoryArgs,
) {
const publicOnly = apiType === 'shop';
const options: HistoryEntryListOptions = { ...args.options };
if (!options.sort) {
options.sort = { createdAt: SortOrder.ASC };
}
return this.historyService.getHistoryForOrder(ctx, order.id, publicOnly, options);
}
@ResolveField()
async promotions(@Ctx() ctx: RequestContext, @Parent() order: Order) {
// If the order has been hydrated with the promotions, then we can just return those
// as long as they have the translations joined.
if (
order.promotions &&
(order.promotions.length === 0 ||
(order.promotions.length > 0 && order.promotions[0].translations))
) {
return order.promotions.map(p => this.translator.translate(p, ctx));
}
return this.orderService.getOrderPromotions(ctx, order.id);
}
}
@Resolver('Order')
export class OrderAdminEntityResolver {
constructor(private orderService: OrderService) {}
@ResolveField()
async channels(@Ctx() ctx: RequestContext, @Parent() order: Order) {
const channels = order.channels ?? (await this.orderService.getOrderChannels(ctx, order));
return channels.filter(channel =>
ctx.session?.user?.channelPermissions.find(cp => idsAreEqual(cp.id, channel.id)),
);
}
@ResolveField()
async modifications(@Ctx() ctx: RequestContext, @Parent() order: Order) {
if (order.modifications) {
return order.modifications;
}
return this.orderService.getOrderModifications(ctx, order.id);
}
@ResolveField()
async nextStates(@Parent() order: Order) {
return this.orderService.getNextOrderStates(order);
}
@ResolveField()
async sellerOrders(@Ctx() ctx: RequestContext, @Parent() order: Order) {
const sellerOrders = await this.orderService.getSellerOrders(ctx, order);
// Only return seller orders on those channels to which the active user has access.
const userChannelIds = ctx.session?.user?.channelPermissions.map(cp => cp.id) ?? [];
return sellerOrders.filter(sellerOrder =>
sellerOrder.channels.find(c => userChannelIds.includes(c.id)),
);
}
@ResolveField()
async aggregateOrder(@Ctx() ctx: RequestContext, @Parent() order: Order) {
const aggregateOrder = await this.orderService.getAggregateOrder(ctx, order);
const userChannelIds = ctx.session?.user?.channelPermissions.map(cp => cp.id) ?? [];
// Only return the aggregate order if the active user has permissions on that channel
return aggregateOrder &&
userChannelIds.find(id => aggregateOrder.channels.find(channel => idsAreEqual(channel.id, id)))
? aggregateOrder
: undefined;
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Asset, FulfillmentLine, Order, OrderLine, ProductVariant } from '../../../entity';
import { AssetService, FulfillmentService, OrderService, ProductVariantService } from '../../../service';
import { RequestContext } from '../../common/request-context';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('OrderLine')
export class OrderLineEntityResolver {
constructor(
private productVariantService: ProductVariantService,
private assetService: AssetService,
private orderService: OrderService,
private fulfillmentService: FulfillmentService,
) {}
@ResolveField()
async productVariant(
@Ctx() ctx: RequestContext,
@Parent() orderLine: OrderLine,
): Promise<ProductVariant> {
if (orderLine.productVariant) {
return orderLine.productVariant;
}
return this.productVariantService.getVariantByOrderLineId(ctx, orderLine.id);
}
@ResolveField()
async featuredAsset(
@Ctx() ctx: RequestContext,
@Parent() orderLine: OrderLine,
): Promise<Asset | undefined> {
if (orderLine.featuredAsset) {
return orderLine.featuredAsset;
} else {
return this.assetService.getFeaturedAsset(ctx, orderLine);
}
}
@ResolveField()
async order(
@Ctx() ctx: RequestContext,
@Parent() orderLine: OrderLine,
@Relations(Order) relations: RelationPaths<Order>,
): Promise<Order | undefined> {
return this.orderService.findOneByOrderLineId(ctx, orderLine.id, relations);
}
@ResolveField()
async fulfillmentLines(
@Ctx() ctx: RequestContext,
@Parent() orderLine: OrderLine,
@Relations(Order) relations: RelationPaths<Order>,
): Promise<FulfillmentLine[]> {
return this.fulfillmentService.getFulfillmentsLinesForOrderLine(ctx, orderLine.id);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { pick } from '@vendure/common/lib/pick';
import { RequestContextCacheService } from '../../../cache/request-context-cache.service';
import { PaymentMetadata } from '../../../common/types/common-types';
import { Payment } from '../../../entity/payment/payment.entity';
import { Refund } from '../../../entity/refund/refund.entity';
import { PaymentService } from '../../../service';
import { OrderService } from '../../../service/services/order.service';
import { ApiType } from '../../common/get-api-type';
import { RequestContext } from '../../common/request-context';
import { Api } from '../../decorators/api.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Payment')
export class PaymentEntityResolver {
constructor(
private orderService: OrderService,
private requestContextCache: RequestContextCacheService,
) {}
@ResolveField()
async refunds(@Ctx() ctx: RequestContext, @Parent() payment: Payment): Promise<Refund[]> {
if (payment.refunds) {
return payment.refunds;
} else {
return this.requestContextCache.get(ctx, `PaymentEntityResolver.refunds(${payment.id})`, () =>
this.orderService.getPaymentRefunds(ctx, payment.id),
);
}
}
@ResolveField()
metadata(@Api() apiType: ApiType, @Parent() payment: Payment): PaymentMetadata {
return apiType === 'admin' ? payment.metadata : pick(payment.metadata, ['public']);
}
}
@Resolver('Payment')
export class PaymentAdminEntityResolver {
constructor(private paymentService: PaymentService) {}
@ResolveField()
async nextStates(@Parent() payment: Payment) {
return this.paymentService.getNextStates(payment);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { ConfigurableOperationDefinition } from '@vendure/common/lib/generated-types';
import { PaymentMethod } from '../../../entity/payment-method/payment-method.entity';
import { PaymentMethodService } from '../../../service/services/payment-method.service';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('PaymentMethod')
export class PaymentMethodEntityResolver {
constructor(private paymentMethodService: PaymentMethodService) {}
}
|
import { Args, Info, Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { ProductVariantListOptions } from '@vendure/common/lib/generated-types';
import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { Translated } from '../../../common/types/locale-types';
import { idsAreEqual } from '../../../common/utils';
import { Asset } from '../../../entity/asset/asset.entity';
import { Channel } from '../../../entity/channel/channel.entity';
import { Collection } from '../../../entity/collection/collection.entity';
import { FacetValue } from '../../../entity/facet-value/facet-value.entity';
import { Product } from '../../../entity/product/product.entity';
import { ProductOptionGroup } from '../../../entity/product-option-group/product-option-group.entity';
import { ProductVariant } from '../../../entity/product-variant/product-variant.entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { AssetService } from '../../../service/services/asset.service';
import { CollectionService } from '../../../service/services/collection.service';
import { FacetValueService } from '../../../service/services/facet-value.service';
import { ProductOptionGroupService } from '../../../service/services/product-option-group.service';
import { ProductVariantService } from '../../../service/services/product-variant.service';
import { ProductService } from '../../../service/services/product.service';
import { ApiType } from '../../common/get-api-type';
import { RequestContext } from '../../common/request-context';
import { Api } from '../../decorators/api.decorator';
import { RelationPaths, Relations } from '../../decorators/relations.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Product')
export class ProductEntityResolver {
constructor(
private productVariantService: ProductVariantService,
private collectionService: CollectionService,
private productOptionGroupService: ProductOptionGroupService,
private assetService: AssetService,
private productService: ProductService,
private facetValueService: FacetValueService,
private localeStringHydrator: LocaleStringHydrator,
) {}
@ResolveField()
name(@Ctx() ctx: RequestContext, @Parent() product: Product): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, product, 'name');
}
@ResolveField()
slug(@Ctx() ctx: RequestContext, @Parent() product: Product): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, product, 'slug');
}
@ResolveField()
description(@Ctx() ctx: RequestContext, @Parent() product: Product): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, product, 'description');
}
@ResolveField()
languageCode(@Ctx() ctx: RequestContext, @Parent() product: Product): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, product, 'languageCode');
}
@ResolveField()
async variants(
@Ctx() ctx: RequestContext,
@Parent() product: Product,
@Relations({ entity: ProductVariant, omit: ['assets'] }) relations: RelationPaths<ProductVariant>,
): Promise<Array<Translated<ProductVariant>>> {
const { items: variants } = await this.productVariantService.getVariantsByProductId(
ctx,
product.id,
{},
relations,
);
return variants;
}
@ResolveField()
async variantList(
@Ctx() ctx: RequestContext,
@Parent() product: Product,
@Args() args: { options: ProductVariantListOptions },
@Relations({ entity: ProductVariant, omit: ['assets'] }) relations: RelationPaths<ProductVariant>,
): Promise<PaginatedList<ProductVariant>> {
return this.productVariantService.getVariantsByProductId(ctx, product.id, args.options, relations);
}
@ResolveField()
async collections(
@Ctx() ctx: RequestContext,
@Parent() product: Product,
@Api() apiType: ApiType,
): Promise<Array<Translated<Collection>>> {
return this.collectionService.getCollectionsByProductId(ctx, product.id, apiType === 'shop');
}
@ResolveField()
async optionGroups(
@Info() info: any,
@Ctx() ctx: RequestContext,
@Parent() product: Product,
): Promise<Array<Translated<ProductOptionGroup>>> {
return this.productOptionGroupService.getOptionGroupsByProductId(ctx, product.id);
}
@ResolveField()
async facetValues(
@Ctx() ctx: RequestContext,
@Parent() product: Product,
@Api() apiType: ApiType,
): Promise<Array<Translated<FacetValue>>> {
if (product.facetValues?.length === 0) {
return [];
}
let facetValues: Array<Translated<FacetValue>>;
if (product.facetValues?.[0]?.channels) {
facetValues = product.facetValues as Array<Translated<FacetValue>>;
} else {
facetValues = await this.productService.getFacetValuesForProduct(ctx, product.id);
}
const filteredFacetValues = await this.facetValueService.findByIds(
ctx,
facetValues.map(facetValue => facetValue.id),
);
if (apiType === 'shop') {
return filteredFacetValues.filter(fv => !fv.facet.isPrivate);
} else {
return filteredFacetValues;
}
}
@ResolveField()
async featuredAsset(@Ctx() ctx: RequestContext, @Parent() product: Product): Promise<Asset | undefined> {
if (product.featuredAsset) {
return product.featuredAsset;
}
return this.assetService.getFeaturedAsset(ctx, product);
}
@ResolveField()
async assets(@Ctx() ctx: RequestContext, @Parent() product: Product): Promise<Asset[] | undefined> {
return this.assetService.getEntityAssets(ctx, product);
}
}
@Resolver('Product')
export class ProductAdminEntityResolver {
constructor(private productService: ProductService) {}
@ResolveField()
async channels(@Ctx() ctx: RequestContext, @Parent() product: Product): Promise<Channel[]> {
const isDefaultChannel = ctx.channel.code === DEFAULT_CHANNEL_CODE;
const channels = product.channels || (await this.productService.getProductChannels(ctx, product.id));
return channels.filter(channel => (isDefaultChannel ? true : idsAreEqual(channel.id, ctx.channelId)));
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Permission } from '@vendure/common/lib/generated-types';
import { RequestContextCacheService } from '../../../cache/request-context-cache.service';
import { Translated } from '../../../common/types/locale-types';
import { assertFound } from '../../../common/utils';
import { ProductOption } from '../../../entity/product-option/product-option.entity';
import { ProductOptionGroup } from '../../../entity/product-option-group/product-option-group.entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { ProductOptionGroupService } from '../../../service/services/product-option-group.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('ProductOption')
export class ProductOptionEntityResolver {
constructor(
private productOptionGroupService: ProductOptionGroupService,
private localeStringHydrator: LocaleStringHydrator,
private requestContextCache: RequestContextCacheService,
) {}
@ResolveField()
name(@Ctx() ctx: RequestContext, @Parent() productOption: ProductOption): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, productOption, 'name');
}
@ResolveField()
languageCode(@Ctx() ctx: RequestContext, @Parent() productOption: ProductOption): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, productOption, 'languageCode');
}
@ResolveField()
@Allow(Permission.ReadCatalog, Permission.Public, Permission.ReadProduct)
async group(
@Ctx() ctx: RequestContext,
@Parent() option: Translated<ProductOption>,
): Promise<ProductOptionGroup> {
if (option.group) {
return option.group;
}
return this.requestContextCache.get(ctx, `ProductOptionEntityResolver.group(${option.groupId})`, () =>
assertFound(this.productOptionGroupService.findOne(ctx, option.groupId)),
);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Permission } from '@vendure/common/lib/generated-types';
import { Translated } from '../../../common/types/locale-types';
import { ProductOption } from '../../../entity/product-option/product-option.entity';
import { ProductOptionGroup } from '../../../entity/product-option-group/product-option-group.entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { ProductOptionGroupService } from '../../../service/services/product-option-group.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('ProductOptionGroup')
export class ProductOptionGroupEntityResolver {
constructor(
private productOptionGroupService: ProductOptionGroupService,
private localeStringHydrator: LocaleStringHydrator,
) {}
@ResolveField()
name(@Ctx() ctx: RequestContext, @Parent() optionGroup: ProductOptionGroup): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, optionGroup, 'name');
}
@ResolveField()
languageCode(@Ctx() ctx: RequestContext, @Parent() optionGroup: ProductOptionGroup): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, optionGroup, 'languageCode');
}
@ResolveField()
@Allow(Permission.ReadCatalog, Permission.Public, Permission.ReadProduct)
async options(
@Ctx() ctx: RequestContext,
@Parent() optionGroup: Translated<ProductOptionGroup>,
): Promise<Array<Translated<ProductOption>>> {
let options: Array<Translated<ProductOption>>;
if (optionGroup.options) {
options = optionGroup.options;
} else {
const group = await this.productOptionGroupService.findOne(ctx, optionGroup.id);
options = group?.options ?? [];
}
return options.filter(o => !o.deletedAt);
}
}
|
import { Args, Parent, ResolveField, Resolver } from '@nestjs/graphql';
import {
CurrencyCode,
ProductVariantPrice,
StockMovementListOptions,
} from '@vendure/common/lib/generated-types';
import { DEFAULT_CHANNEL_CODE } from '@vendure/common/lib/shared-constants';
import { PaginatedList } from '@vendure/common/lib/shared-types';
import { RequestContextCacheService } from '../../../cache/request-context-cache.service';
import { Translated } from '../../../common/types/locale-types';
import { idsAreEqual } from '../../../common/utils';
import { Asset, Channel, FacetValue, Product, ProductOption, StockLevel, TaxRate } from '../../../entity';
import { ProductVariant } from '../../../entity/product-variant/product-variant.entity';
import { StockMovement } from '../../../entity/stock-movement/stock-movement.entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { StockLevelService } from '../../../service/services/stock-level.service';
import { AssetService } from '../../../service/services/asset.service';
import { ProductVariantService } from '../../../service/services/product-variant.service';
import { StockMovementService } from '../../../service/services/stock-movement.service';
import { ApiType } from '../../common/get-api-type';
import { RequestContext } from '../../common/request-context';
import { Api } from '../../decorators/api.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('ProductVariant')
export class ProductVariantEntityResolver {
constructor(
private productVariantService: ProductVariantService,
private assetService: AssetService,
private localeStringHydrator: LocaleStringHydrator,
private requestContextCache: RequestContextCacheService,
) {}
@ResolveField()
async name(@Ctx() ctx: RequestContext, @Parent() productVariant: ProductVariant): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, productVariant, 'name');
}
@ResolveField()
async languageCode(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, productVariant, 'languageCode');
}
@ResolveField()
async price(@Ctx() ctx: RequestContext, @Parent() productVariant: ProductVariant): Promise<number> {
return this.productVariantService.hydratePriceFields(ctx, productVariant, 'price');
}
@ResolveField()
async priceWithTax(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<number> {
return this.productVariantService.hydratePriceFields(ctx, productVariant, 'priceWithTax');
}
@ResolveField()
async currencyCode(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<CurrencyCode> {
return this.productVariantService.hydratePriceFields(ctx, productVariant, 'currencyCode');
}
@ResolveField()
async taxRateApplied(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<TaxRate> {
return this.productVariantService.hydratePriceFields(ctx, productVariant, 'taxRateApplied');
}
@ResolveField()
async product(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<Product | undefined> {
if (productVariant.product?.name) {
return productVariant.product;
}
return this.requestContextCache.get(
ctx,
`ProductVariantEntityResolver.product(${productVariant.productId})`,
() => this.productVariantService.getProductForVariant(ctx, productVariant),
);
}
@ResolveField()
async assets(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<Asset[] | undefined> {
return this.assetService.getEntityAssets(ctx, productVariant);
}
@ResolveField()
async featuredAsset(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<Asset | undefined> {
if (productVariant.featuredAsset) {
return productVariant.featuredAsset;
}
return this.assetService.getFeaturedAsset(ctx, productVariant);
}
@ResolveField()
async options(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<Array<Translated<ProductOption>>> {
if (productVariant.options) {
return productVariant.options as Array<Translated<ProductOption>>;
}
return this.productVariantService.getOptionsForVariant(ctx, productVariant.id);
}
@ResolveField()
async facetValues(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
@Api() apiType: ApiType,
): Promise<Array<Translated<FacetValue>>> {
if (productVariant.facetValues?.length === 0) {
return [];
}
let facetValues: Array<Translated<FacetValue>>;
if (productVariant.facetValues?.[0]?.channels) {
facetValues = productVariant.facetValues as Array<Translated<FacetValue>>;
} else {
facetValues = await this.productVariantService.getFacetValuesForVariant(ctx, productVariant.id);
}
return facetValues.filter(fv => {
if (!fv.channels.find(c => idsAreEqual(c.id, ctx.channelId))) {
return false;
}
if (apiType === 'shop' && fv.facet.isPrivate) {
return false;
}
return true;
});
}
@ResolveField()
async stockLevel(@Ctx() ctx: RequestContext, @Parent() productVariant: ProductVariant): Promise<string> {
return this.productVariantService.getDisplayStockLevel(ctx, productVariant);
}
}
@Resolver('ProductVariant')
export class ProductVariantAdminEntityResolver {
constructor(
private productVariantService: ProductVariantService,
private stockMovementService: StockMovementService,
private stockLevelService: StockLevelService,
) {}
@ResolveField()
async stockMovements(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
@Args() args: { options: StockMovementListOptions },
): Promise<PaginatedList<StockMovement>> {
return this.stockMovementService.getStockMovementsByProductVariantId(
ctx,
productVariant.id,
args.options,
);
}
@ResolveField()
async stockOnHand(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
@Args() args: { options: StockMovementListOptions },
): Promise<number> {
const { stockOnHand } = await this.stockLevelService.getAvailableStock(ctx, productVariant.id);
return stockOnHand;
}
@ResolveField()
async stockAllocated(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
@Args() args: { options: StockMovementListOptions },
): Promise<number> {
const { stockAllocated } = await this.stockLevelService.getAvailableStock(ctx, productVariant.id);
return stockAllocated;
}
@ResolveField()
async channels(@Ctx() ctx: RequestContext, @Parent() productVariant: ProductVariant): Promise<Channel[]> {
const isDefaultChannel = ctx.channel.code === DEFAULT_CHANNEL_CODE;
const channels = await this.productVariantService.getProductVariantChannels(ctx, productVariant.id);
return channels.filter(channel => (isDefaultChannel ? true : idsAreEqual(channel.id, ctx.channelId)));
}
@ResolveField()
async stockLevels(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<StockLevel[]> {
return this.stockLevelService.getStockLevelsForVariant(ctx, productVariant.id);
}
@ResolveField()
async prices(
@Ctx() ctx: RequestContext,
@Parent() productVariant: ProductVariant,
): Promise<ProductVariantPrice[]> {
if (productVariant.productVariantPrices) {
return productVariant.productVariantPrices.filter(pvp =>
idsAreEqual(pvp.channelId, ctx.channelId),
);
}
return this.productVariantService.getProductVariantPrices(ctx, productVariant.id);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { idsAreEqual } from '../../../common/utils';
import { Refund } from '../../../entity/refund/refund.entity';
import { PaymentService } from '../../../service/services/payment.service';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Refund')
export class RefundEntityResolver {
constructor(private paymentService: PaymentService) {}
@ResolveField()
async lines(@Ctx() ctx: RequestContext, @Parent() refund: Refund) {
if (refund.lines) {
return refund.lines;
}
const payment = await this.paymentService.findOneOrThrow(ctx, refund.paymentId, ['refunds.lines']);
return payment.refunds.find(r => idsAreEqual(r.id, refund.id))?.lines ?? [];
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { TransactionalConnection } from '../../../connection/transactional-connection';
import { OrderLine } from '../../../entity/order-line/order-line.entity';
import { RefundLine } from '../../../entity/order-line-reference/refund-line.entity';
import { Refund } from '../../../entity/refund/refund.entity';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('RefundLine')
export class RefundLineEntityResolver {
constructor(private connection: TransactionalConnection) {}
@ResolveField()
async orderLine(@Ctx() ctx: RequestContext, @Parent() refundLine: RefundLine): Promise<OrderLine> {
return await this.connection.getEntityOrThrow(ctx, OrderLine, refundLine.orderLineId);
}
@ResolveField()
async refund(@Ctx() ctx: RequestContext, @Parent() refundLine: RefundLine): Promise<Refund> {
return this.connection.getEntityOrThrow(ctx, Refund, refundLine.refundId);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Channel } from '../../../entity/channel/channel.entity';
import { Role } from '../../../entity/role/role.entity';
import { RoleService } from '../../../service/services/role.service';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('Role')
export class RoleEntityResolver {
constructor(private roleService: RoleService) {}
@ResolveField()
async channels(@Ctx() ctx: RequestContext, @Parent() role: Role): Promise<Channel[]> {
if (role.channels) {
return role.channels;
}
return this.roleService.getChannelsForRole(ctx, role.id);
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { ShippingLine } from '../../../entity/shipping-line/shipping-line.entity';
import { ShippingMethodService } from '../../../service/services/shipping-method.service';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('ShippingLine')
export class ShippingLineEntityResolver {
constructor(private shippingMethodService: ShippingMethodService) {}
@ResolveField()
async shippingMethod(@Ctx() ctx: RequestContext, @Parent() shippingLine: ShippingLine) {
if (shippingLine.shippingMethodId) {
// Does not need to be decoded because it is an internal property
// which is never exposed to the outside world.
const shippingMethodId = shippingLine.shippingMethodId;
return this.shippingMethodService.findOne(ctx, shippingMethodId, true);
} else {
return null;
}
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { ShippingMethod } from '../../../entity/shipping-method/shipping-method.entity';
import { LocaleStringHydrator } from '../../../service/helpers/locale-string-hydrator/locale-string-hydrator';
import { RequestContext } from '../../common/request-context';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('ShippingMethod')
export class ShippingMethodEntityResolver {
constructor(private localeStringHydrator: LocaleStringHydrator) {}
@ResolveField()
name(@Ctx() ctx: RequestContext, @Parent() shippingMethod: ShippingMethod): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, shippingMethod, 'name');
}
@ResolveField()
description(@Ctx() ctx: RequestContext, @Parent() shippingMethod: ShippingMethod): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, shippingMethod, 'description');
}
@ResolveField()
languageCode(@Ctx() ctx: RequestContext, @Parent() shippingMethod: ShippingMethod): Promise<string> {
return this.localeStringHydrator.hydrateLocaleStringField(ctx, shippingMethod, 'languageCode');
}
}
|
import { Parent, ResolveField, Resolver } from '@nestjs/graphql';
import { Permission } from '@vendure/common/lib/generated-types';
import { Channel } from '../../../entity/channel/channel.entity';
import { CustomerGroup } from '../../../entity/customer-group/customer-group.entity';
import { TaxRate } from '../../../entity/tax-rate/tax-rate.entity';
import { RoleService } from '../../../service/services/role.service';
import { TaxRateService } from '../../../service/services/tax-rate.service';
import { RequestContext } from '../../common/request-context';
import { Allow } from '../../decorators/allow.decorator';
import { Ctx } from '../../decorators/request-context.decorator';
@Resolver('TaxRate')
export class TaxRateEntityResolver {
constructor(private taxRateService: TaxRateService) {}
@Allow(Permission.ReadCustomer, Permission.ReadCustomerGroup)
@ResolveField()
async customerGroup(
@Ctx() ctx: RequestContext,
@Parent() taxRate: TaxRate,
): Promise<CustomerGroup | undefined> {
if (taxRate.customerGroup) {
return taxRate.customerGroup;
}
return (await this.taxRateService.findOne(ctx, taxRate.id))?.customerGroup;
}
}
|