| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508 |
- import { LanguageCode } from '@vendure/common/lib/generated-types';
- import {
- Asset,
- CustomFields,
- Logger,
- mergeConfig,
- OrderService,
- ProductService,
- RequestContextService,
- TransactionalConnection,
- } from '@vendure/core';
- import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing';
- import { fail } from 'node:assert';
- import path from 'node:path';
- import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
- import { initialData } from '../../../e2e-common/e2e-initial-data';
- import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config';
- import { graphql, ResultOf } from './graphql/graphql-admin';
- import { graphql as graphqlShop, ResultOf as ResultOfShop } from './graphql/graphql-shop';
- import { assertThrowsWithMessage } from './utils/assert-throws-with-message';
- import { fixPostgresTimezone } from './utils/fix-pg-timezone';
- fixPostgresTimezone();
- const validateInjectorSpy = vi.fn();
- const customConfig = mergeConfig(testConfig(), {
- dbConnectionOptions: {
- timezone: 'Z',
- },
- customFields: {
- Product: [
- { name: 'nullable', type: 'string' },
- { name: 'notNullable', type: 'string', nullable: false, defaultValue: '' },
- { name: 'stringWithDefault', type: 'string', defaultValue: 'hello' },
- { name: 'localeStringWithDefault', type: 'localeString', defaultValue: 'hola' },
- { name: 'intWithDefault', type: 'int', defaultValue: 5 },
- { name: 'floatWithDefault', type: 'float', defaultValue: 5.5678 },
- { name: 'booleanWithDefault', type: 'boolean', defaultValue: true },
- {
- name: 'dateTimeWithDefault',
- type: 'datetime',
- defaultValue: new Date('2019-04-30T12:59:16.4158386Z'),
- },
- { name: 'validateString', type: 'string', pattern: '^[0-9][a-z]+$' },
- { name: 'validateLocaleString', type: 'localeString', pattern: '^[0-9][a-z]+$' },
- { name: 'validateInt', type: 'int', min: 0, max: 10 },
- { name: 'validateFloat', type: 'float', min: 0.5, max: 10.5 },
- {
- name: 'validateDateTime',
- type: 'datetime',
- min: '2019-01-01T08:30',
- max: '2019-06-01T08:30',
- },
- {
- name: 'validateFn1',
- type: 'string',
- validate: value => {
- if (value !== 'valid') {
- return `The value ['${value as string}'] is not valid`;
- }
- },
- },
- {
- name: 'validateFn2',
- type: 'string',
- validate: value => {
- if (value !== 'valid') {
- return [
- {
- languageCode: LanguageCode.en,
- value: `The value ['${value as string}'] is not valid`,
- },
- ];
- }
- },
- },
- {
- name: 'validateFn3',
- type: 'string',
- validate: (value, injector) => {
- const connection = injector.get(TransactionalConnection);
- validateInjectorSpy(connection);
- },
- },
- {
- name: 'validateFn4',
- type: 'string',
- validate: async (value, injector) => {
- await new Promise(resolve => setTimeout(resolve, 1));
- return 'async error';
- },
- },
- {
- name: 'validateRelation',
- type: 'relation',
- entity: Asset,
- validate: async value => {
- await new Promise(resolve => setTimeout(resolve, 1));
- return 'relation error';
- },
- },
- {
- name: 'stringWithOptions',
- type: 'string',
- options: [{ value: 'small' }, { value: 'medium' }, { value: 'large' }],
- },
- {
- name: 'nullableStringWithOptions',
- type: 'string',
- nullable: true,
- options: [{ value: 'small' }, { value: 'medium' }, { value: 'large' }],
- },
- {
- name: 'nonPublic',
- type: 'string',
- defaultValue: 'hi!',
- public: false,
- },
- {
- name: 'public',
- type: 'string',
- defaultValue: 'ho!',
- public: true,
- },
- {
- name: 'longString',
- type: 'string',
- length: 10000,
- },
- {
- name: 'longLocaleString',
- type: 'localeString',
- length: 10000,
- },
- {
- name: 'readonlyString',
- type: 'string',
- readonly: true,
- },
- {
- name: 'internalString',
- type: 'string',
- internal: true,
- },
- {
- name: 'stringList',
- type: 'string',
- list: true,
- },
- {
- name: 'localeStringList',
- type: 'localeString',
- list: true,
- },
- {
- name: 'stringListWithDefault',
- type: 'string',
- list: true,
- defaultValue: ['cat'],
- },
- {
- name: 'intListWithValidation',
- type: 'int',
- list: true,
- validate: value => {
- if (!value.includes(42)) {
- return 'Must include the number 42!';
- }
- },
- },
- {
- name: 'uniqueString',
- type: 'string',
- unique: true,
- },
- ],
- Facet: [
- {
- name: 'translated',
- type: 'localeString',
- },
- ],
- Customer: [
- {
- name: 'score',
- type: 'int',
- readonly: true,
- },
- ],
- Collection: [
- { name: 'secretKey1', type: 'string', defaultValue: '', public: false, internal: true },
- { name: 'secretKey2', type: 'string', defaultValue: '', public: false, internal: false },
- ],
- OrderLine: [{ name: 'validateInt', type: 'int', min: 0, max: 10 }],
- ProductVariantPrice: [
- {
- name: 'costPrice',
- type: 'int',
- },
- ],
- // Single readonly Address custom field to test
- // https://github.com/vendure-ecommerce/vendure/issues/3326
- Address: [
- {
- name: 'hereId',
- type: 'string',
- readonly: true,
- nullable: true,
- },
- ],
- } as CustomFields,
- });
- describe('Custom fields', () => {
- const { server, adminClient, shopClient } = createTestEnvironment(customConfig);
- // Product guard for nullable results with customFields
- type ProductWithCustomFields = NonNullable<ResultOf<typeof getProductNullableDocument>['product']>;
- const productGuard: ErrorResultGuard<ProductWithCustomFields> = createErrorResultGuard(
- input => input !== null && 'customFields' in input,
- );
- // Collection guard for shop API
- type CollectionResult = NonNullable<ResultOfShop<typeof getCollectionCustomFieldsDocument>['collection']>;
- const collectionGuard: ErrorResultGuard<CollectionResult> = createErrorResultGuard(
- input => input !== null,
- );
- // ProductVariant guard (custom document with price customFields)
- type ProductVariantResult = ResultOf<
- typeof updateProductVariantsWithPriceCustomFieldsDocument
- >['updateProductVariants'][number];
- const productVariantGuard: ErrorResultGuard<ProductVariantResult> = createErrorResultGuard(
- input => input !== null && 'prices' in input,
- );
- // Order guard for shop API validation tests
- type OrderWithLines = { id: string; lines: any[] };
- const orderGuard: ErrorResultGuard<OrderWithLines> = createErrorResultGuard(input => 'lines' in input);
- beforeAll(async () => {
- await server.init({
- initialData,
- productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
- customerCount: 1,
- });
- await adminClient.asSuperAdmin();
- }, TEST_SETUP_TIMEOUT_MS);
- afterAll(async () => {
- await server.destroy();
- });
- it('globalSettings.serverConfig.customFieldConfig', async () => {
- const { globalSettings } = await adminClient.query(getServerConfigCustomFieldsDocument);
- expect(globalSettings.serverConfig.customFieldConfig).toEqual({
- Product: [
- { name: 'nullable', type: 'string', list: false },
- { name: 'notNullable', type: 'string', list: false },
- { name: 'stringWithDefault', type: 'string', list: false },
- { name: 'localeStringWithDefault', type: 'localeString', list: false },
- { name: 'intWithDefault', type: 'int', list: false },
- { name: 'floatWithDefault', type: 'float', list: false },
- { name: 'booleanWithDefault', type: 'boolean', list: false },
- { name: 'dateTimeWithDefault', type: 'datetime', list: false },
- { name: 'validateString', type: 'string', list: false },
- { name: 'validateLocaleString', type: 'localeString', list: false },
- { name: 'validateInt', type: 'int', list: false },
- { name: 'validateFloat', type: 'float', list: false },
- { name: 'validateDateTime', type: 'datetime', list: false },
- { name: 'validateFn1', type: 'string', list: false },
- { name: 'validateFn2', type: 'string', list: false },
- { name: 'validateFn3', type: 'string', list: false },
- { name: 'validateFn4', type: 'string', list: false },
- {
- name: 'validateRelation',
- type: 'relation',
- list: false,
- scalarFields: [
- 'id',
- 'createdAt',
- 'updatedAt',
- 'name',
- 'type',
- 'fileSize',
- 'mimeType',
- 'width',
- 'height',
- 'source',
- 'preview',
- 'customFields',
- ],
- },
- { name: 'stringWithOptions', type: 'string', list: false },
- { name: 'nullableStringWithOptions', type: 'string', list: false },
- { name: 'nonPublic', type: 'string', list: false },
- { name: 'public', type: 'string', list: false },
- { name: 'longString', type: 'string', list: false },
- { name: 'longLocaleString', type: 'localeString', list: false },
- { name: 'readonlyString', type: 'string', list: false },
- { name: 'stringList', type: 'string', list: true },
- { name: 'localeStringList', type: 'localeString', list: true },
- { name: 'stringListWithDefault', type: 'string', list: true },
- { name: 'intListWithValidation', type: 'int', list: true },
- { name: 'uniqueString', type: 'string', list: false },
- // The internal type should not be exposed at all
- // { name: 'internalString', type: 'string' },
- ],
- });
- });
- it('globalSettings.serverConfig.entityCustomFields', async () => {
- const { globalSettings } = await adminClient.query(getServerConfigEntityCustomFieldsDocument);
- const productCustomFields = globalSettings.serverConfig.entityCustomFields.find(
- e => e.entityName === 'Product',
- );
- expect(productCustomFields).toEqual({
- entityName: 'Product',
- customFields: [
- { name: 'nullable', type: 'string', list: false },
- { name: 'notNullable', type: 'string', list: false },
- { name: 'stringWithDefault', type: 'string', list: false },
- { name: 'localeStringWithDefault', type: 'localeString', list: false },
- { name: 'intWithDefault', type: 'int', list: false },
- { name: 'floatWithDefault', type: 'float', list: false },
- { name: 'booleanWithDefault', type: 'boolean', list: false },
- { name: 'dateTimeWithDefault', type: 'datetime', list: false },
- { name: 'validateString', type: 'string', list: false },
- { name: 'validateLocaleString', type: 'localeString', list: false },
- { name: 'validateInt', type: 'int', list: false },
- { name: 'validateFloat', type: 'float', list: false },
- { name: 'validateDateTime', type: 'datetime', list: false },
- { name: 'validateFn1', type: 'string', list: false },
- { name: 'validateFn2', type: 'string', list: false },
- { name: 'validateFn3', type: 'string', list: false },
- { name: 'validateFn4', type: 'string', list: false },
- {
- name: 'validateRelation',
- type: 'relation',
- list: false,
- scalarFields: [
- 'id',
- 'createdAt',
- 'updatedAt',
- 'name',
- 'type',
- 'fileSize',
- 'mimeType',
- 'width',
- 'height',
- 'source',
- 'preview',
- 'customFields',
- ],
- },
- { name: 'stringWithOptions', type: 'string', list: false },
- { name: 'nullableStringWithOptions', type: 'string', list: false },
- { name: 'nonPublic', type: 'string', list: false },
- { name: 'public', type: 'string', list: false },
- { name: 'longString', type: 'string', list: false },
- { name: 'longLocaleString', type: 'localeString', list: false },
- { name: 'readonlyString', type: 'string', list: false },
- { name: 'stringList', type: 'string', list: true },
- { name: 'localeStringList', type: 'localeString', list: true },
- { name: 'stringListWithDefault', type: 'string', list: true },
- { name: 'intListWithValidation', type: 'int', list: true },
- { name: 'uniqueString', type: 'string', list: false },
- // The internal type should not be exposed at all
- // { name: 'internalString', type: 'string' },
- ],
- });
- });
- it('get nullable with no default', async () => {
- const { product } = await adminClient.query(getProductNullableDocument, { id: 'T_1' });
- expect(product).toEqual({
- id: 'T_1',
- name: 'Laptop',
- customFields: {
- nullable: null,
- },
- });
- });
- it('get entity with localeString only', async () => {
- const { facet } = await adminClient.query(getFacetCustomFieldsDocument, { id: 'T_1' });
- expect(facet).toEqual({
- id: 'T_1',
- name: 'category',
- customFields: {
- translated: null,
- },
- });
- });
- it('get fields with default values', async () => {
- const { product } = await adminClient.query(getProductWithDefaultsDocument, { id: 'T_1' });
- const customFields = {
- stringWithDefault: 'hello',
- localeStringWithDefault: 'hola',
- intWithDefault: 5,
- floatWithDefault: 5.5678,
- booleanWithDefault: true,
- dateTimeWithDefault: '2019-04-30T12:59:16.415Z',
- // MySQL does not support defaults on TEXT fields, which is what "simple-json" uses
- // internally. See https://stackoverflow.com/q/3466872/772859
- stringListWithDefault: customConfig.dbConnectionOptions.type === 'mysql' ? null : ['cat'],
- };
- expect(product).toEqual({
- id: 'T_1',
- name: 'Laptop',
- customFields,
- });
- });
- it(
- 'update non-nullable field',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { notNullable: null } }) {
- id
- }
- }
- `),
- );
- }, 'The custom field "notNullable" value cannot be set to null'),
- );
- it(
- 'throws on attempt to update readonly field',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { readonlyString: "hello" } }) {
- id
- }
- }
- `),
- );
- }, 'Field "readonlyString" is not defined by type "UpdateProductCustomFieldsInput"'),
- );
- it(
- 'throws on attempt to update readonly field when no other custom fields defined',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateCustomer(input: { id: "T_1", customFields: { score: 5 } }) {
- ... on Customer {
- id
- }
- }
- }
- `),
- );
- }, 'The custom field "score" is readonly'),
- );
- it(
- 'throws on attempt to create readonly field',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- createProduct(
- input: {
- translations: [{ languageCode: en, name: "test" }]
- customFields: { readonlyString: "hello" }
- }
- ) {
- id
- }
- }
- `),
- );
- }, 'Field "readonlyString" is not defined by type "CreateProductCustomFieldsInput"'),
- );
- it('string length allows long strings', async () => {
- const longString = Array.from({ length: 500 }, v => 'hello there!').join(' ');
- const result = await adminClient.query(updateProductLongStringDocument, {
- id: 'T_1',
- stringValue: longString,
- });
- expect(result.updateProduct.customFields.longString).toBe(longString);
- });
- it('string length allows long localeStrings', async () => {
- const longString = Array.from({ length: 500 }, v => 'hello there!').join(' ');
- const result = await adminClient.query(updateProductLongLocaleStringDocument, {
- id: 'T_1',
- stringValue: longString,
- });
- expect(result.updateProduct.customFields.longLocaleString).toBe(longString);
- });
- describe('validation', () => {
- it(
- 'invalid string',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { validateString: "hello" } }) {
- id
- }
- }
- `),
- );
- }, 'The custom field "validateString" value ["hello"] does not match the pattern [^[0-9][a-z]+$]'),
- );
- it(
- 'invalid string option',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { stringWithOptions: "tiny" } }) {
- id
- }
- }
- `),
- );
- }, "The custom field \"stringWithOptions\" value [\"tiny\"] is invalid. Valid options are ['small', 'medium', 'large']"),
- );
- it('valid string option', async () => {
- const { updateProduct } = await adminClient.query(updateProductStringOptionsDocument, {
- id: 'T_1',
- value: 'medium',
- });
- expect(updateProduct.customFields.stringWithOptions).toBe('medium');
- });
- it('nullable string option with null', async () => {
- const { updateProduct } = await adminClient.query(updateProductNullableStringOptionsDocument, {
- id: 'T_1',
- value: null,
- });
- expect(updateProduct.customFields.nullableStringWithOptions).toBeNull();
- });
- it(
- 'invalid localeString',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(
- input: {
- id: "T_1"
- translations: [
- {
- id: "T_1"
- languageCode: en
- customFields: { validateLocaleString: "servus" }
- }
- ]
- }
- ) {
- id
- }
- }
- `),
- );
- }, 'The custom field "validateLocaleString" value ["servus"] does not match the pattern [^[0-9][a-z]+$]'),
- );
- it(
- 'invalid int',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { validateInt: 12 } }) {
- id
- }
- }
- `),
- );
- }, 'The custom field "validateInt" value [12] is greater than the maximum [10]'),
- );
- it(
- 'invalid float',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { validateFloat: 10.6 } }) {
- id
- }
- }
- `),
- );
- }, 'The custom field "validateFloat" value [10.6] is greater than the maximum [10.5]'),
- );
- it(
- 'invalid datetime',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(
- input: {
- id: "T_1"
- customFields: { validateDateTime: "2019-01-01T05:25:00.000Z" }
- }
- ) {
- id
- }
- }
- `),
- );
- }, 'The custom field "validateDateTime" value [2019-01-01T05:25:00.000Z] is less than the minimum [2019-01-01T08:30]'),
- );
- it(
- 'invalid validate function with string',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { validateFn1: "invalid" } }) {
- id
- }
- }
- `),
- );
- }, "The value ['invalid'] is not valid"),
- );
- it(
- 'invalid validate function with localized string',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { validateFn2: "invalid" } }) {
- id
- }
- }
- `),
- );
- }, "The value ['invalid'] is not valid"),
- );
- it(
- 'invalid list field',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(
- input: { id: "T_1", customFields: { intListWithValidation: [1, 2, 3] } }
- ) {
- id
- }
- }
- `),
- );
- }, 'Must include the number 42!'),
- );
- it('valid list field', async () => {
- const { updateProduct } = await adminClient.query(updateProductIntListDocument, {
- id: 'T_1',
- values: [1, 42, 3],
- });
- expect(updateProduct.customFields.intListWithValidation).toEqual([1, 42, 3]);
- });
- it('can inject providers into validation fn', async () => {
- const { updateProduct } = await adminClient.query(updateProductValidateFn3Document, {
- id: 'T_1',
- value: 'some value',
- });
- expect(updateProduct.customFields.validateFn3).toBe('some value');
- expect(validateInjectorSpy).toHaveBeenCalledTimes(1);
- expect(validateInjectorSpy.mock.calls[0][0] instanceof TransactionalConnection).toBe(true);
- });
- it(
- 'supports async validation fn',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { validateFn4: "some value" } }) {
- id
- customFields {
- validateFn4
- }
- }
- }
- `),
- );
- }, 'async error'),
- );
- // https://github.com/vendure-ecommerce/vendure/issues/1000
- it(
- 'supports validation of relation types',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- mutation {
- updateProduct(input: { id: "T_1", customFields: { validateRelationId: "T_1" } }) {
- id
- customFields {
- validateFn4
- }
- }
- }
- `),
- );
- }, 'relation error'),
- );
- // https://github.com/vendure-ecommerce/vendure/issues/1091
- it('handles well graphql internal fields', async () => {
- // throws "Cannot read property 'args' of undefined" if broken
- await adminClient.query(
- graphql(`
- mutation {
- __typename
- updateProduct(input: { id: "T_1", customFields: { nullable: "some value" } }) {
- __typename
- id
- customFields {
- __typename
- nullable
- }
- }
- }
- `),
- );
- });
- // https://github.com/vendure-ecommerce/vendure/issues/1953
- describe('validation of OrderLine custom fields', () => {
- it('addItemToOrder', async () => {
- try {
- const { addItemToOrder } = await shopClient.query(
- graphqlShop(`
- mutation {
- addItemToOrder(
- productVariantId: 1
- quantity: 1
- customFields: { validateInt: 11 }
- ) {
- ... on Order {
- id
- }
- }
- }
- `),
- );
- fail('Should have thrown');
- } catch (e) {
- expect(e.message).toContain(
- 'The custom field "validateInt" value [11] is greater than the maximum [10]',
- );
- }
- const { addItemToOrder: result } = await shopClient.query(
- addItemToOrderWithCustomFieldsDocument,
- {
- productVariantId: '1',
- quantity: 1,
- validateInt: 9,
- },
- );
- orderGuard.assertSuccess(result);
- expect(result.lines[0].customFields).toEqual({ validateInt: 9 });
- });
- it('adjustOrderLine', async () => {
- try {
- const { adjustOrderLine } = await shopClient.query(
- graphqlShop(`
- mutation {
- adjustOrderLine(
- orderLineId: "T_1"
- quantity: 1
- customFields: { validateInt: 11 }
- ) {
- ... on Order {
- id
- }
- }
- }
- `),
- );
- fail('Should have thrown');
- } catch (e) {
- expect(e.message).toContain(
- 'The custom field "validateInt" value [11] is greater than the maximum [10]',
- );
- }
- const { adjustOrderLine: result } = await shopClient.query(
- adjustOrderLineWithCustomFieldsDocument,
- {
- orderLineId: 'T_1',
- quantity: 1,
- validateInt: 2,
- },
- );
- orderGuard.assertSuccess(result);
- expect(result.lines[0].customFields).toEqual({ validateInt: 2 });
- });
- });
- });
- describe('public access', () => {
- it(
- 'non-public throws for Shop API',
- assertThrowsWithMessage(async () => {
- await shopClient.query(
- graphqlShop(`
- query {
- product(id: "T_1") {
- id
- customFields {
- nonPublic
- }
- }
- }
- `),
- );
- }, 'Cannot query field "nonPublic" on type "ProductCustomFields"'),
- );
- it('publicly accessible via Shop API', async () => {
- const { product } = await shopClient.query(getShopProductPublicCustomFieldDocument, {
- id: 'T_1',
- });
- if (!product) {
- throw new Error('Product not found');
- }
- productGuard.assertSuccess(product);
- expect(product.customFields.public).toBe('ho!');
- });
- it(
- 'internal throws for Shop API',
- assertThrowsWithMessage(async () => {
- await shopClient.query(
- graphqlShop(`
- query {
- product(id: "T_1") {
- id
- customFields {
- internalString
- }
- }
- }
- `),
- );
- }, 'Cannot query field "internalString" on type "ProductCustomFields"'),
- );
- it(
- 'internal throws for Admin API',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- query {
- product(id: "T_1") {
- id
- customFields {
- internalString
- }
- }
- }
- `),
- );
- }, 'Cannot query field "internalString" on type "ProductCustomFields"'),
- );
- // https://github.com/vendure-ecommerce/vendure/issues/3049
- it('does not leak private fields via JSON type', async () => {
- const { collection } = await shopClient.query(getCollectionCustomFieldsDocument, { id: 'T_1' });
- collectionGuard.assertSuccess(collection);
- expect(collection.customFields).toBe(null);
- });
- });
- describe('sort & filter', () => {
- it('can sort by custom fields', async () => {
- const { products } = await adminClient.query(getProductsSortByNullableDocument);
- expect(products.totalItems).toBe(1);
- });
- // https://github.com/vendure-ecommerce/vendure/issues/1581
- it('can sort by localeString custom fields', async () => {
- const { products } = await adminClient.query(getProductsSortByLocaleStringDocument);
- expect(products.totalItems).toBe(1);
- });
- it('can filter by custom fields', async () => {
- const { products } = await adminClient.query(getProductsFilterByStringDocument);
- expect(products.totalItems).toBe(1);
- });
- it('can filter by localeString custom fields', async () => {
- const { products } = await adminClient.query(getProductsFilterByLocaleStringDocument);
- expect(products.totalItems).toBe(1);
- });
- it('can filter by custom list fields', async () => {
- const { products: result1 } = await adminClient.query(getProductsFilterByIntListDocument, {
- value: 42,
- });
- expect(result1.totalItems).toBe(1);
- const { products: result2 } = await adminClient.query(getProductsFilterByIntListDocument, {
- value: 43,
- });
- expect(result2.totalItems).toBe(0);
- });
- it(
- 'cannot sort by custom list fields',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- query {
- products(options: { sort: { intListWithValidation: ASC } }) {
- totalItems
- }
- }
- `),
- );
- }, 'Field "intListWithValidation" is not defined by type "ProductSortParameter".'),
- );
- it(
- 'cannot filter by internal field in Admin API',
- assertThrowsWithMessage(async () => {
- await adminClient.query(
- graphql(`
- query {
- products(options: { filter: { internalString: { contains: "hello" } } }) {
- totalItems
- }
- }
- `),
- );
- }, 'Field "internalString" is not defined by type "ProductFilterParameter"'),
- );
- it(
- 'cannot filter by internal field in Shop API',
- assertThrowsWithMessage(async () => {
- await shopClient.query(
- graphqlShop(`
- query {
- products(options: { filter: { internalString: { contains: "hello" } } }) {
- totalItems
- }
- }
- `),
- );
- }, 'Field "internalString" is not defined by type "ProductFilterParameter"'),
- );
- });
- describe('product on productVariant entity', () => {
- it('is translated', async () => {
- const { productVariants } = await adminClient.query(getProductVariantsWithCustomFieldsDocument, {
- productId: 'T_1',
- });
- expect(productVariants.items[0].product).toEqual({
- id: 'T_1',
- name: 'Laptop',
- customFields: {
- localeStringWithDefault: 'hola',
- stringWithDefault: 'hello',
- },
- });
- });
- });
- describe('unique constraint', () => {
- it('setting unique value works', async () => {
- const result = await adminClient.query(updateProductUniqueStringDocument, {
- id: 'T_1',
- value: 'foo',
- });
- expect(result.updateProduct.customFields.uniqueString).toBe('foo');
- });
- it('setting conflicting value fails', async () => {
- try {
- await adminClient.query(createProductUniqueStringDocument, { uniqueString: 'foo' });
- fail('Should have thrown');
- } catch (e: any) {
- let duplicateKeyErrMessage = 'unassigned';
- switch (customConfig.dbConnectionOptions.type) {
- case 'mariadb':
- case 'mysql':
- duplicateKeyErrMessage = "Duplicate entry 'foo' for key";
- break;
- case 'postgres':
- duplicateKeyErrMessage = 'duplicate key value violates unique constraint';
- break;
- case 'sqlite':
- case 'sqljs':
- duplicateKeyErrMessage = 'UNIQUE constraint failed: product.customFieldsUniquestring';
- break;
- }
- expect(e.message).toContain(duplicateKeyErrMessage);
- }
- });
- });
- it('on ProductVariantPrice', async () => {
- const { updateProductVariants } = await adminClient.query(
- updateProductVariantsWithPriceCustomFieldsDocument,
- {
- input: [
- {
- id: 'T_1',
- prices: [
- {
- price: 129900,
- currencyCode: 'USD',
- customFields: {
- costPrice: 100,
- },
- },
- ],
- },
- ],
- },
- );
- productVariantGuard.assertSuccess(updateProductVariants[0]);
- if (!updateProductVariants[0]) {
- throw new Error('Update product variants failed');
- }
- expect(updateProductVariants[0].prices).toEqual([
- {
- currencyCode: 'USD',
- price: 129900,
- customFields: {
- costPrice: 100,
- },
- },
- ]);
- });
- describe('setting custom fields directly via a service method', () => {
- it('OrderService.addItemToOrder warns on unknown custom field', async () => {
- const orderService = server.app.get(OrderService);
- const requestContextService = server.app.get(RequestContextService);
- const ctx = await requestContextService.create({
- apiType: 'admin',
- });
- const order = await orderService.create(ctx);
- const warnSpy = vi.spyOn(Logger, 'warn');
- await orderService.addItemToOrder(ctx, order.id, 1, 1, {
- customFieldWhichDoesNotExist: 'test value',
- });
- expect(warnSpy).toHaveBeenCalledWith(
- 'Custom field customFieldWhichDoesNotExist not found for entity OrderLine',
- );
- });
- it('OrderService.addItemToOrder does not warn on known custom field', async () => {
- const orderService = server.app.get(OrderService);
- const requestContextService = server.app.get(RequestContextService);
- const ctx = await requestContextService.create({
- apiType: 'admin',
- });
- const order = await orderService.create(ctx);
- const warnSpy = vi.spyOn(Logger, 'warn');
- await orderService.addItemToOrder(ctx, order.id, 1, 1, {
- validateInt: 1,
- });
- expect(warnSpy).not.toHaveBeenCalled();
- });
- it('OrderService.addItemToOrder warns on multiple unknown custom fields', async () => {
- const orderService = server.app.get(OrderService);
- const requestContextService = server.app.get(RequestContextService);
- const ctx = await requestContextService.create({
- apiType: 'admin',
- });
- const order = await orderService.create(ctx);
- const warnSpy = vi.spyOn(Logger, 'warn');
- await orderService.addItemToOrder(ctx, order.id, 1, 1, {
- unknownField1: 'foo',
- unknownField2: 'bar',
- });
- expect(warnSpy).toHaveBeenCalledWith('Custom field unknownField1 not found for entity OrderLine');
- expect(warnSpy).toHaveBeenCalledWith('Custom field unknownField2 not found for entity OrderLine');
- });
- it('OrderService.addItemToOrder does not warn when no custom fields are provided', async () => {
- const orderService = server.app.get(OrderService);
- const requestContextService = server.app.get(RequestContextService);
- const ctx = await requestContextService.create({
- apiType: 'admin',
- });
- const order = await orderService.create(ctx);
- const warnSpy = vi.spyOn(Logger, 'warn');
- await orderService.addItemToOrder(ctx, order.id, 1, 1);
- expect(warnSpy).not.toHaveBeenCalled();
- });
- it('warns on unknown custom field in ProductTranslation entity', async () => {
- const productService = server.app.get(ProductService);
- const requestContextService = server.app.get(RequestContextService);
- const ctx = await requestContextService.create({
- apiType: 'admin',
- });
- const warnSpy = vi.spyOn(Logger, 'warn');
- await productService.create(ctx, {
- translations: [
- {
- languageCode: LanguageCode.en,
- name: 'test',
- slug: 'test',
- description: '',
- customFields: { customFieldWhichDoesNotExist: 'foo' },
- },
- ],
- });
- expect(warnSpy).toHaveBeenCalledWith(
- 'Custom field customFieldWhichDoesNotExist not found for entity ProductTranslation',
- );
- });
- it('does not warn when Translation has a valid custom field', async () => {
- const productService = server.app.get(ProductService);
- const requestContextService = server.app.get(RequestContextService);
- const ctx = await requestContextService.create({
- apiType: 'admin',
- });
- const warnSpy = vi.spyOn(Logger, 'warn');
- await productService.create(ctx, {
- translations: [
- {
- languageCode: LanguageCode.en,
- name: 'test',
- slug: 'test',
- description: '',
- customFields: { localeStringWithDefault: 'foo' },
- },
- ],
- });
- expect(warnSpy).not.toHaveBeenCalled();
- });
- });
- });
- const getServerConfigCustomFieldsDocument = graphql(`
- query GetServerConfigCustomFields {
- globalSettings {
- serverConfig {
- customFieldConfig {
- Product {
- ... on CustomField {
- name
- type
- list
- }
- ... on RelationCustomFieldConfig {
- scalarFields
- }
- }
- }
- }
- }
- }
- `);
- const getServerConfigEntityCustomFieldsDocument = graphql(`
- query GetServerConfigEntityCustomFields {
- globalSettings {
- serverConfig {
- entityCustomFields {
- entityName
- customFields {
- ... on CustomField {
- name
- type
- list
- }
- ... on RelationCustomFieldConfig {
- scalarFields
- }
- }
- }
- }
- }
- }
- `);
- const getProductNullableDocument = graphql(`
- query GetProductNullable($id: ID!) {
- product(id: $id) {
- id
- name
- customFields {
- nullable
- }
- }
- }
- `);
- const getProductWithDefaultsDocument = graphql(`
- query GetProductWithDefaults($id: ID!) {
- product(id: $id) {
- id
- name
- customFields {
- stringWithDefault
- localeStringWithDefault
- intWithDefault
- floatWithDefault
- booleanWithDefault
- dateTimeWithDefault
- stringListWithDefault
- }
- }
- }
- `);
- const updateProductLongStringDocument = graphql(`
- mutation UpdateProductLongString($id: ID!, $stringValue: String!) {
- updateProduct(input: { id: $id, customFields: { longString: $stringValue } }) {
- id
- customFields {
- longString
- }
- }
- }
- `);
- const updateProductLongLocaleStringDocument = graphql(`
- mutation UpdateProductLongLocaleString($id: ID!, $stringValue: String!) {
- updateProduct(
- input: {
- id: $id
- translations: [{ languageCode: en, customFields: { longLocaleString: $stringValue } }]
- }
- ) {
- id
- customFields {
- longLocaleString
- }
- }
- }
- `);
- const updateProductStringOptionsDocument = graphql(`
- mutation UpdateProductStringOptions($id: ID!, $value: String!) {
- updateProduct(input: { id: $id, customFields: { stringWithOptions: $value } }) {
- id
- customFields {
- stringWithOptions
- }
- }
- }
- `);
- const updateProductNullableStringOptionsDocument = graphql(`
- mutation UpdateProductNullableStringOptions($id: ID!, $value: String) {
- updateProduct(input: { id: $id, customFields: { nullableStringWithOptions: $value } }) {
- id
- customFields {
- nullableStringWithOptions
- }
- }
- }
- `);
- const updateProductIntListDocument = graphql(`
- mutation UpdateProductIntList($id: ID!, $values: [Int!]!) {
- updateProduct(input: { id: $id, customFields: { intListWithValidation: $values } }) {
- id
- customFields {
- intListWithValidation
- }
- }
- }
- `);
- const updateProductValidateFn3Document = graphql(`
- mutation UpdateProductValidateFn3($id: ID!, $value: String!) {
- updateProduct(input: { id: $id, customFields: { validateFn3: $value } }) {
- id
- customFields {
- validateFn3
- }
- }
- }
- `);
- const updateProductUniqueStringDocument = graphql(`
- mutation UpdateProductUniqueString($id: ID!, $value: String!) {
- updateProduct(input: { id: $id, customFields: { uniqueString: $value } }) {
- id
- customFields {
- uniqueString
- }
- }
- }
- `);
- const createProductUniqueStringDocument = graphql(`
- mutation CreateProductUniqueString($uniqueString: String!) {
- createProduct(
- input: {
- translations: [{ languageCode: en, name: "test 2", slug: "test-2", description: "" }]
- customFields: { uniqueString: $uniqueString }
- }
- ) {
- id
- }
- }
- `);
- const getProductVariantsWithCustomFieldsDocument = graphql(`
- query GetProductVariantsWithCustomFields($productId: ID!) {
- productVariants(productId: $productId) {
- items {
- product {
- name
- id
- customFields {
- localeStringWithDefault
- stringWithDefault
- }
- }
- }
- }
- }
- `);
- const getFacetCustomFieldsDocument = graphql(`
- query GetFacetCustomFields($id: ID!) {
- facet(id: $id) {
- id
- name
- customFields {
- translated
- }
- }
- }
- `);
- const getCollectionCustomFieldsDocument = graphqlShop(`
- query GetCollectionCustomFields($id: ID!) {
- collection(id: $id) {
- id
- customFields
- }
- }
- `);
- const getProductsSortByNullableDocument = graphql(`
- query GetProductsSortByNullable {
- products(options: { sort: { nullable: ASC } }) {
- totalItems
- }
- }
- `);
- const getProductsSortByLocaleStringDocument = graphql(`
- query GetProductsSortByLocaleString {
- products(options: { sort: { localeStringWithDefault: ASC } }) {
- totalItems
- }
- }
- `);
- const getProductsFilterByStringDocument = graphql(`
- query GetProductsFilterByString {
- products(options: { filter: { stringWithDefault: { contains: "hello" } } }) {
- totalItems
- }
- }
- `);
- const getProductsFilterByLocaleStringDocument = graphql(`
- query GetProductsFilterByLocaleString {
- products(options: { filter: { localeStringWithDefault: { contains: "hola" } } }) {
- totalItems
- }
- }
- `);
- const getProductsFilterByIntListDocument = graphql(`
- query GetProductsFilterByIntList($value: Float!) {
- products(options: { filter: { intListWithValidation: { inList: $value } } }) {
- totalItems
- }
- }
- `);
- const addItemToOrderWithCustomFieldsDocument = graphqlShop(`
- mutation AddItemToOrderWithCustomFields($productVariantId: ID!, $quantity: Int!, $validateInt: Int!) {
- addItemToOrder(productVariantId: $productVariantId, quantity: $quantity, customFields: { validateInt: $validateInt }) {
- ... on Order {
- id
- lines {
- customFields {
- validateInt
- }
- }
- }
- }
- }
- `);
- const adjustOrderLineWithCustomFieldsDocument = graphqlShop(`
- mutation AdjustOrderLineWithCustomFields($orderLineId: ID!, $quantity: Int!, $validateInt: Int!) {
- adjustOrderLine(orderLineId: $orderLineId, quantity: $quantity, customFields: { validateInt: $validateInt }) {
- ... on Order {
- id
- lines {
- customFields {
- validateInt
- }
- }
- }
- }
- }
- `);
- const updateProductVariantsWithPriceCustomFieldsDocument = graphql(`
- mutation UpdateProductVariantsWithPriceCustomFields($input: [UpdateProductVariantInput!]!) {
- updateProductVariants(input: $input) {
- id
- prices {
- currencyCode
- price
- customFields {
- costPrice
- }
- }
- }
- }
- `);
- const getShopProductPublicCustomFieldDocument = graphqlShop(`
- query GetShopProductPublicCustomField($id: ID!) {
- product(id: $id) {
- id
- customFields {
- public
- }
- }
- }
- `);
|