custom-fields.e2e-spec.ts 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. import { LanguageCode } from '@vendure/common/lib/generated-types';
  2. import {
  3. Asset,
  4. CustomFields,
  5. Logger,
  6. mergeConfig,
  7. OrderService,
  8. ProductService,
  9. RequestContextService,
  10. TransactionalConnection,
  11. } from '@vendure/core';
  12. import { createTestEnvironment } from '@vendure/testing';
  13. import { fail } from 'assert';
  14. import gql from 'graphql-tag';
  15. import path from 'path';
  16. import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
  17. import { initialData } from '../../../e2e-common/e2e-initial-data';
  18. import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config';
  19. import { assertThrowsWithMessage } from './utils/assert-throws-with-message';
  20. import { fixPostgresTimezone } from './utils/fix-pg-timezone';
  21. fixPostgresTimezone();
  22. /* eslint-disable @typescript-eslint/no-non-null-assertion */
  23. const validateInjectorSpy = vi.fn();
  24. const customConfig = mergeConfig(testConfig(), {
  25. dbConnectionOptions: {
  26. timezone: 'Z',
  27. },
  28. customFields: {
  29. Product: [
  30. { name: 'nullable', type: 'string' },
  31. { name: 'notNullable', type: 'string', nullable: false, defaultValue: '' },
  32. { name: 'stringWithDefault', type: 'string', defaultValue: 'hello' },
  33. { name: 'localeStringWithDefault', type: 'localeString', defaultValue: 'hola' },
  34. { name: 'intWithDefault', type: 'int', defaultValue: 5 },
  35. { name: 'floatWithDefault', type: 'float', defaultValue: 5.5678 },
  36. { name: 'booleanWithDefault', type: 'boolean', defaultValue: true },
  37. {
  38. name: 'dateTimeWithDefault',
  39. type: 'datetime',
  40. defaultValue: new Date('2019-04-30T12:59:16.4158386Z'),
  41. },
  42. { name: 'validateString', type: 'string', pattern: '^[0-9][a-z]+$' },
  43. { name: 'validateLocaleString', type: 'localeString', pattern: '^[0-9][a-z]+$' },
  44. { name: 'validateInt', type: 'int', min: 0, max: 10 },
  45. { name: 'validateFloat', type: 'float', min: 0.5, max: 10.5 },
  46. {
  47. name: 'validateDateTime',
  48. type: 'datetime',
  49. min: '2019-01-01T08:30',
  50. max: '2019-06-01T08:30',
  51. },
  52. {
  53. name: 'validateFn1',
  54. type: 'string',
  55. validate: value => {
  56. if (value !== 'valid') {
  57. return `The value ['${value as string}'] is not valid`;
  58. }
  59. },
  60. },
  61. {
  62. name: 'validateFn2',
  63. type: 'string',
  64. validate: value => {
  65. if (value !== 'valid') {
  66. return [
  67. {
  68. languageCode: LanguageCode.en,
  69. value: `The value ['${value as string}'] is not valid`,
  70. },
  71. ];
  72. }
  73. },
  74. },
  75. {
  76. name: 'validateFn3',
  77. type: 'string',
  78. validate: (value, injector) => {
  79. const connection = injector.get(TransactionalConnection);
  80. validateInjectorSpy(connection);
  81. },
  82. },
  83. {
  84. name: 'validateFn4',
  85. type: 'string',
  86. validate: async (value, injector) => {
  87. await new Promise(resolve => setTimeout(resolve, 1));
  88. return 'async error';
  89. },
  90. },
  91. {
  92. name: 'validateRelation',
  93. type: 'relation',
  94. entity: Asset,
  95. validate: async value => {
  96. await new Promise(resolve => setTimeout(resolve, 1));
  97. return 'relation error';
  98. },
  99. },
  100. {
  101. name: 'stringWithOptions',
  102. type: 'string',
  103. options: [{ value: 'small' }, { value: 'medium' }, { value: 'large' }],
  104. },
  105. {
  106. name: 'nullableStringWithOptions',
  107. type: 'string',
  108. nullable: true,
  109. options: [{ value: 'small' }, { value: 'medium' }, { value: 'large' }],
  110. },
  111. {
  112. name: 'nonPublic',
  113. type: 'string',
  114. defaultValue: 'hi!',
  115. public: false,
  116. },
  117. {
  118. name: 'public',
  119. type: 'string',
  120. defaultValue: 'ho!',
  121. public: true,
  122. },
  123. {
  124. name: 'longString',
  125. type: 'string',
  126. length: 10000,
  127. },
  128. {
  129. name: 'longLocaleString',
  130. type: 'localeString',
  131. length: 10000,
  132. },
  133. {
  134. name: 'readonlyString',
  135. type: 'string',
  136. readonly: true,
  137. },
  138. {
  139. name: 'internalString',
  140. type: 'string',
  141. internal: true,
  142. },
  143. {
  144. name: 'stringList',
  145. type: 'string',
  146. list: true,
  147. },
  148. {
  149. name: 'localeStringList',
  150. type: 'localeString',
  151. list: true,
  152. },
  153. {
  154. name: 'stringListWithDefault',
  155. type: 'string',
  156. list: true,
  157. defaultValue: ['cat'],
  158. },
  159. {
  160. name: 'intListWithValidation',
  161. type: 'int',
  162. list: true,
  163. validate: value => {
  164. if (!value.includes(42)) {
  165. return 'Must include the number 42!';
  166. }
  167. },
  168. },
  169. {
  170. name: 'uniqueString',
  171. type: 'string',
  172. unique: true,
  173. },
  174. ],
  175. Facet: [
  176. {
  177. name: 'translated',
  178. type: 'localeString',
  179. },
  180. ],
  181. Customer: [
  182. {
  183. name: 'score',
  184. type: 'int',
  185. readonly: true,
  186. },
  187. ],
  188. Collection: [
  189. { name: 'secretKey1', type: 'string', defaultValue: '', public: false, internal: true },
  190. { name: 'secretKey2', type: 'string', defaultValue: '', public: false, internal: false },
  191. ],
  192. OrderLine: [{ name: 'validateInt', type: 'int', min: 0, max: 10 }],
  193. ProductVariantPrice: [
  194. {
  195. name: 'costPrice',
  196. type: 'int',
  197. },
  198. ],
  199. // Single readonly Address custom field to test
  200. // https://github.com/vendurehq/vendure/issues/3326
  201. Address: [
  202. {
  203. name: 'hereId',
  204. type: 'string',
  205. readonly: true,
  206. nullable: true,
  207. },
  208. ],
  209. } as CustomFields,
  210. });
  211. describe('Custom fields', () => {
  212. const { server, adminClient, shopClient } = createTestEnvironment(customConfig);
  213. beforeAll(async () => {
  214. await server.init({
  215. initialData,
  216. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-minimal.csv'),
  217. customerCount: 1,
  218. });
  219. await adminClient.asSuperAdmin();
  220. }, TEST_SETUP_TIMEOUT_MS);
  221. afterAll(async () => {
  222. await server.destroy();
  223. });
  224. it('globalSettings.serverConfig.customFieldConfig', async () => {
  225. const { globalSettings } = await adminClient.query(gql`
  226. query {
  227. globalSettings {
  228. serverConfig {
  229. customFieldConfig {
  230. Product {
  231. ... on CustomField {
  232. name
  233. type
  234. list
  235. }
  236. ... on RelationCustomFieldConfig {
  237. scalarFields
  238. }
  239. }
  240. }
  241. }
  242. }
  243. }
  244. `);
  245. expect(globalSettings.serverConfig.customFieldConfig).toEqual({
  246. Product: [
  247. { name: 'nullable', type: 'string', list: false },
  248. { name: 'notNullable', type: 'string', list: false },
  249. { name: 'stringWithDefault', type: 'string', list: false },
  250. { name: 'localeStringWithDefault', type: 'localeString', list: false },
  251. { name: 'intWithDefault', type: 'int', list: false },
  252. { name: 'floatWithDefault', type: 'float', list: false },
  253. { name: 'booleanWithDefault', type: 'boolean', list: false },
  254. { name: 'dateTimeWithDefault', type: 'datetime', list: false },
  255. { name: 'validateString', type: 'string', list: false },
  256. { name: 'validateLocaleString', type: 'localeString', list: false },
  257. { name: 'validateInt', type: 'int', list: false },
  258. { name: 'validateFloat', type: 'float', list: false },
  259. { name: 'validateDateTime', type: 'datetime', list: false },
  260. { name: 'validateFn1', type: 'string', list: false },
  261. { name: 'validateFn2', type: 'string', list: false },
  262. { name: 'validateFn3', type: 'string', list: false },
  263. { name: 'validateFn4', type: 'string', list: false },
  264. {
  265. name: 'validateRelation',
  266. type: 'relation',
  267. list: false,
  268. scalarFields: [
  269. 'id',
  270. 'createdAt',
  271. 'updatedAt',
  272. 'name',
  273. 'type',
  274. 'fileSize',
  275. 'mimeType',
  276. 'width',
  277. 'height',
  278. 'source',
  279. 'preview',
  280. 'customFields',
  281. ],
  282. },
  283. { name: 'stringWithOptions', type: 'string', list: false },
  284. { name: 'nullableStringWithOptions', type: 'string', list: false },
  285. { name: 'nonPublic', type: 'string', list: false },
  286. { name: 'public', type: 'string', list: false },
  287. { name: 'longString', type: 'string', list: false },
  288. { name: 'longLocaleString', type: 'localeString', list: false },
  289. { name: 'readonlyString', type: 'string', list: false },
  290. { name: 'stringList', type: 'string', list: true },
  291. { name: 'localeStringList', type: 'localeString', list: true },
  292. { name: 'stringListWithDefault', type: 'string', list: true },
  293. { name: 'intListWithValidation', type: 'int', list: true },
  294. { name: 'uniqueString', type: 'string', list: false },
  295. // The internal type should not be exposed at all
  296. // { name: 'internalString', type: 'string' },
  297. ],
  298. });
  299. });
  300. it('globalSettings.serverConfig.entityCustomFields', async () => {
  301. const { globalSettings } = await adminClient.query(gql`
  302. query {
  303. globalSettings {
  304. serverConfig {
  305. entityCustomFields {
  306. entityName
  307. customFields {
  308. ... on CustomField {
  309. name
  310. type
  311. list
  312. }
  313. ... on RelationCustomFieldConfig {
  314. scalarFields
  315. }
  316. }
  317. }
  318. }
  319. }
  320. }
  321. `);
  322. const productCustomFields = globalSettings.serverConfig.entityCustomFields.find(
  323. e => e.entityName === 'Product',
  324. );
  325. expect(productCustomFields).toEqual({
  326. entityName: 'Product',
  327. customFields: [
  328. { name: 'nullable', type: 'string', list: false },
  329. { name: 'notNullable', type: 'string', list: false },
  330. { name: 'stringWithDefault', type: 'string', list: false },
  331. { name: 'localeStringWithDefault', type: 'localeString', list: false },
  332. { name: 'intWithDefault', type: 'int', list: false },
  333. { name: 'floatWithDefault', type: 'float', list: false },
  334. { name: 'booleanWithDefault', type: 'boolean', list: false },
  335. { name: 'dateTimeWithDefault', type: 'datetime', list: false },
  336. { name: 'validateString', type: 'string', list: false },
  337. { name: 'validateLocaleString', type: 'localeString', list: false },
  338. { name: 'validateInt', type: 'int', list: false },
  339. { name: 'validateFloat', type: 'float', list: false },
  340. { name: 'validateDateTime', type: 'datetime', list: false },
  341. { name: 'validateFn1', type: 'string', list: false },
  342. { name: 'validateFn2', type: 'string', list: false },
  343. { name: 'validateFn3', type: 'string', list: false },
  344. { name: 'validateFn4', type: 'string', list: false },
  345. {
  346. name: 'validateRelation',
  347. type: 'relation',
  348. list: false,
  349. scalarFields: [
  350. 'id',
  351. 'createdAt',
  352. 'updatedAt',
  353. 'name',
  354. 'type',
  355. 'fileSize',
  356. 'mimeType',
  357. 'width',
  358. 'height',
  359. 'source',
  360. 'preview',
  361. 'customFields',
  362. ],
  363. },
  364. { name: 'stringWithOptions', type: 'string', list: false },
  365. { name: 'nullableStringWithOptions', type: 'string', list: false },
  366. { name: 'nonPublic', type: 'string', list: false },
  367. { name: 'public', type: 'string', list: false },
  368. { name: 'longString', type: 'string', list: false },
  369. { name: 'longLocaleString', type: 'localeString', list: false },
  370. { name: 'readonlyString', type: 'string', list: false },
  371. { name: 'stringList', type: 'string', list: true },
  372. { name: 'localeStringList', type: 'localeString', list: true },
  373. { name: 'stringListWithDefault', type: 'string', list: true },
  374. { name: 'intListWithValidation', type: 'int', list: true },
  375. { name: 'uniqueString', type: 'string', list: false },
  376. // The internal type should not be exposed at all
  377. // { name: 'internalString', type: 'string' },
  378. ],
  379. });
  380. });
  381. it('get nullable with no default', async () => {
  382. const { product } = await adminClient.query(gql`
  383. query {
  384. product(id: "T_1") {
  385. id
  386. name
  387. customFields {
  388. nullable
  389. }
  390. }
  391. }
  392. `);
  393. expect(product).toEqual({
  394. id: 'T_1',
  395. name: 'Laptop',
  396. customFields: {
  397. nullable: null,
  398. },
  399. });
  400. });
  401. it('get entity with localeString only', async () => {
  402. const { facet } = await adminClient.query(gql`
  403. query {
  404. facet(id: "T_1") {
  405. id
  406. name
  407. customFields {
  408. translated
  409. }
  410. }
  411. }
  412. `);
  413. expect(facet).toEqual({
  414. id: 'T_1',
  415. name: 'category',
  416. customFields: {
  417. translated: null,
  418. },
  419. });
  420. });
  421. it('get fields with default values', async () => {
  422. const { product } = await adminClient.query(gql`
  423. query {
  424. product(id: "T_1") {
  425. id
  426. name
  427. customFields {
  428. stringWithDefault
  429. localeStringWithDefault
  430. intWithDefault
  431. floatWithDefault
  432. booleanWithDefault
  433. dateTimeWithDefault
  434. stringListWithDefault
  435. }
  436. }
  437. }
  438. `);
  439. const customFields = {
  440. stringWithDefault: 'hello',
  441. localeStringWithDefault: 'hola',
  442. intWithDefault: 5,
  443. floatWithDefault: 5.5678,
  444. booleanWithDefault: true,
  445. dateTimeWithDefault: '2019-04-30T12:59:16.415Z',
  446. // MySQL does not support defaults on TEXT fields, which is what "simple-json" uses
  447. // internally. See https://stackoverflow.com/q/3466872/772859
  448. stringListWithDefault: customConfig.dbConnectionOptions.type === 'mysql' ? null : ['cat'],
  449. };
  450. expect(product).toEqual({
  451. id: 'T_1',
  452. name: 'Laptop',
  453. customFields,
  454. });
  455. });
  456. it(
  457. 'update non-nullable field',
  458. assertThrowsWithMessage(async () => {
  459. await adminClient.query(gql`
  460. mutation {
  461. updateProduct(input: { id: "T_1", customFields: { notNullable: null } }) {
  462. id
  463. }
  464. }
  465. `);
  466. }, 'The custom field "notNullable" value cannot be set to null'),
  467. );
  468. it(
  469. 'throws on attempt to update readonly field',
  470. assertThrowsWithMessage(async () => {
  471. await adminClient.query(gql`
  472. mutation {
  473. updateProduct(input: { id: "T_1", customFields: { readonlyString: "hello" } }) {
  474. id
  475. }
  476. }
  477. `);
  478. }, 'Field "readonlyString" is not defined by type "UpdateProductCustomFieldsInput"'),
  479. );
  480. it(
  481. 'throws on attempt to update readonly field when no other custom fields defined',
  482. assertThrowsWithMessage(async () => {
  483. await adminClient.query(gql`
  484. mutation {
  485. updateCustomer(input: { id: "T_1", customFields: { score: 5 } }) {
  486. ... on Customer {
  487. id
  488. }
  489. }
  490. }
  491. `);
  492. }, 'The custom field "score" is readonly'),
  493. );
  494. it(
  495. 'throws on attempt to create readonly field',
  496. assertThrowsWithMessage(async () => {
  497. await adminClient.query(gql`
  498. mutation {
  499. createProduct(
  500. input: {
  501. translations: [{ languageCode: en, name: "test" }]
  502. customFields: { readonlyString: "hello" }
  503. }
  504. ) {
  505. id
  506. }
  507. }
  508. `);
  509. }, 'Field "readonlyString" is not defined by type "CreateProductCustomFieldsInput"'),
  510. );
  511. it('string length allows long strings', async () => {
  512. const longString = Array.from({ length: 500 }, v => 'hello there!').join(' ');
  513. const result = await adminClient.query(
  514. gql`
  515. mutation ($stringValue: String!) {
  516. updateProduct(input: { id: "T_1", customFields: { longString: $stringValue } }) {
  517. id
  518. customFields {
  519. longString
  520. }
  521. }
  522. }
  523. `,
  524. { stringValue: longString },
  525. );
  526. expect(result.updateProduct.customFields.longString).toBe(longString);
  527. });
  528. it('string length allows long localeStrings', async () => {
  529. const longString = Array.from({ length: 500 }, v => 'hello there!').join(' ');
  530. const result = await adminClient.query(
  531. gql`
  532. mutation ($stringValue: String!) {
  533. updateProduct(
  534. input: {
  535. id: "T_1"
  536. translations: [
  537. { languageCode: en, customFields: { longLocaleString: $stringValue } }
  538. ]
  539. }
  540. ) {
  541. id
  542. customFields {
  543. longLocaleString
  544. }
  545. }
  546. }
  547. `,
  548. { stringValue: longString },
  549. );
  550. expect(result.updateProduct.customFields.longLocaleString).toBe(longString);
  551. });
  552. describe('validation', () => {
  553. it(
  554. 'invalid string',
  555. assertThrowsWithMessage(async () => {
  556. await adminClient.query(gql`
  557. mutation {
  558. updateProduct(input: { id: "T_1", customFields: { validateString: "hello" } }) {
  559. id
  560. }
  561. }
  562. `);
  563. }, 'The custom field "validateString" value ["hello"] does not match the pattern [^[0-9][a-z]+$]'),
  564. );
  565. it(
  566. 'invalid string option',
  567. assertThrowsWithMessage(async () => {
  568. await adminClient.query(gql`
  569. mutation {
  570. updateProduct(input: { id: "T_1", customFields: { stringWithOptions: "tiny" } }) {
  571. id
  572. }
  573. }
  574. `);
  575. }, "The custom field \"stringWithOptions\" value [\"tiny\"] is invalid. Valid options are ['small', 'medium', 'large']"),
  576. );
  577. it('valid string option', async () => {
  578. const { updateProduct } = await adminClient.query(gql`
  579. mutation {
  580. updateProduct(input: { id: "T_1", customFields: { stringWithOptions: "medium" } }) {
  581. id
  582. customFields {
  583. stringWithOptions
  584. }
  585. }
  586. }
  587. `);
  588. expect(updateProduct.customFields.stringWithOptions).toBe('medium');
  589. });
  590. it('nullable string option with null', async () => {
  591. const { updateProduct } = await adminClient.query(gql`
  592. mutation {
  593. updateProduct(input: { id: "T_1", customFields: { nullableStringWithOptions: null } }) {
  594. id
  595. customFields {
  596. nullableStringWithOptions
  597. }
  598. }
  599. }
  600. `);
  601. expect(updateProduct.customFields.nullableStringWithOptions).toBeNull();
  602. });
  603. it(
  604. 'invalid localeString',
  605. assertThrowsWithMessage(async () => {
  606. await adminClient.query(gql`
  607. mutation {
  608. updateProduct(
  609. input: {
  610. id: "T_1"
  611. translations: [
  612. {
  613. id: "T_1"
  614. languageCode: en
  615. customFields: { validateLocaleString: "servus" }
  616. }
  617. ]
  618. }
  619. ) {
  620. id
  621. }
  622. }
  623. `);
  624. }, 'The custom field "validateLocaleString" value ["servus"] does not match the pattern [^[0-9][a-z]+$]'),
  625. );
  626. it(
  627. 'invalid int',
  628. assertThrowsWithMessage(async () => {
  629. await adminClient.query(gql`
  630. mutation {
  631. updateProduct(input: { id: "T_1", customFields: { validateInt: 12 } }) {
  632. id
  633. }
  634. }
  635. `);
  636. }, 'The custom field "validateInt" value [12] is greater than the maximum [10]'),
  637. );
  638. it(
  639. 'invalid float',
  640. assertThrowsWithMessage(async () => {
  641. await adminClient.query(gql`
  642. mutation {
  643. updateProduct(input: { id: "T_1", customFields: { validateFloat: 10.6 } }) {
  644. id
  645. }
  646. }
  647. `);
  648. }, 'The custom field "validateFloat" value [10.6] is greater than the maximum [10.5]'),
  649. );
  650. it(
  651. 'invalid datetime',
  652. assertThrowsWithMessage(async () => {
  653. await adminClient.query(gql`
  654. mutation {
  655. updateProduct(
  656. input: {
  657. id: "T_1"
  658. customFields: { validateDateTime: "2019-01-01T05:25:00.000Z" }
  659. }
  660. ) {
  661. id
  662. }
  663. }
  664. `);
  665. }, 'The custom field "validateDateTime" value [2019-01-01T05:25:00.000Z] is less than the minimum [2019-01-01T08:30]'),
  666. );
  667. it(
  668. 'invalid validate function with string',
  669. assertThrowsWithMessage(async () => {
  670. await adminClient.query(gql`
  671. mutation {
  672. updateProduct(input: { id: "T_1", customFields: { validateFn1: "invalid" } }) {
  673. id
  674. }
  675. }
  676. `);
  677. }, "The value ['invalid'] is not valid"),
  678. );
  679. it(
  680. 'invalid validate function with localized string',
  681. assertThrowsWithMessage(async () => {
  682. await adminClient.query(gql`
  683. mutation {
  684. updateProduct(input: { id: "T_1", customFields: { validateFn2: "invalid" } }) {
  685. id
  686. }
  687. }
  688. `);
  689. }, "The value ['invalid'] is not valid"),
  690. );
  691. it(
  692. 'invalid list field',
  693. assertThrowsWithMessage(async () => {
  694. await adminClient.query(gql`
  695. mutation {
  696. updateProduct(
  697. input: { id: "T_1", customFields: { intListWithValidation: [1, 2, 3] } }
  698. ) {
  699. id
  700. }
  701. }
  702. `);
  703. }, 'Must include the number 42!'),
  704. );
  705. it('valid list field', async () => {
  706. const { updateProduct } = await adminClient.query(gql`
  707. mutation {
  708. updateProduct(input: { id: "T_1", customFields: { intListWithValidation: [1, 42, 3] } }) {
  709. id
  710. customFields {
  711. intListWithValidation
  712. }
  713. }
  714. }
  715. `);
  716. expect(updateProduct.customFields.intListWithValidation).toEqual([1, 42, 3]);
  717. });
  718. it('can inject providers into validation fn', async () => {
  719. const { updateProduct } = await adminClient.query(gql`
  720. mutation {
  721. updateProduct(input: { id: "T_1", customFields: { validateFn3: "some value" } }) {
  722. id
  723. customFields {
  724. validateFn3
  725. }
  726. }
  727. }
  728. `);
  729. expect(updateProduct.customFields.validateFn3).toBe('some value');
  730. expect(validateInjectorSpy).toHaveBeenCalledTimes(1);
  731. expect(validateInjectorSpy.mock.calls[0][0] instanceof TransactionalConnection).toBe(true);
  732. });
  733. it(
  734. 'supports async validation fn',
  735. assertThrowsWithMessage(async () => {
  736. await adminClient.query(gql`
  737. mutation {
  738. updateProduct(input: { id: "T_1", customFields: { validateFn4: "some value" } }) {
  739. id
  740. customFields {
  741. validateFn4
  742. }
  743. }
  744. }
  745. `);
  746. }, 'async error'),
  747. );
  748. // https://github.com/vendurehq/vendure/issues/1000
  749. it(
  750. 'supports validation of relation types',
  751. assertThrowsWithMessage(async () => {
  752. await adminClient.query(gql`
  753. mutation {
  754. updateProduct(input: { id: "T_1", customFields: { validateRelationId: "T_1" } }) {
  755. id
  756. customFields {
  757. validateFn4
  758. }
  759. }
  760. }
  761. `);
  762. }, 'relation error'),
  763. );
  764. // https://github.com/vendurehq/vendure/issues/1091
  765. it('handles well graphql internal fields', async () => {
  766. // throws "Cannot read property 'args' of undefined" if broken
  767. await adminClient.query(gql`
  768. mutation {
  769. __typename
  770. updateProduct(input: { id: "T_1", customFields: { nullable: "some value" } }) {
  771. __typename
  772. id
  773. customFields {
  774. __typename
  775. nullable
  776. }
  777. }
  778. }
  779. `);
  780. });
  781. // https://github.com/vendurehq/vendure/issues/1953
  782. describe('validation of OrderLine custom fields', () => {
  783. it('addItemToOrder', async () => {
  784. try {
  785. const { addItemToOrder } = await shopClient.query(gql`
  786. mutation {
  787. addItemToOrder(
  788. productVariantId: 1
  789. quantity: 1
  790. customFields: { validateInt: 11 }
  791. ) {
  792. ... on Order {
  793. id
  794. }
  795. }
  796. }
  797. `);
  798. fail('Should have thrown');
  799. } catch (e) {
  800. expect(e.message).toContain(
  801. 'The custom field "validateInt" value [11] is greater than the maximum [10]',
  802. );
  803. }
  804. const { addItemToOrder: result } = await shopClient.query(gql`
  805. mutation {
  806. addItemToOrder(productVariantId: 1, quantity: 1, customFields: { validateInt: 9 }) {
  807. ... on Order {
  808. id
  809. lines {
  810. customFields {
  811. validateInt
  812. }
  813. }
  814. }
  815. }
  816. }
  817. `);
  818. expect(result.lines[0].customFields).toEqual({ validateInt: 9 });
  819. });
  820. it('adjustOrderLine', async () => {
  821. try {
  822. const { adjustOrderLine } = await shopClient.query(gql`
  823. mutation {
  824. adjustOrderLine(
  825. orderLineId: "T_1"
  826. quantity: 1
  827. customFields: { validateInt: 11 }
  828. ) {
  829. ... on Order {
  830. id
  831. }
  832. }
  833. }
  834. `);
  835. fail('Should have thrown');
  836. } catch (e) {
  837. expect(e.message).toContain(
  838. 'The custom field "validateInt" value [11] is greater than the maximum [10]',
  839. );
  840. }
  841. const { adjustOrderLine: result } = await shopClient.query(gql`
  842. mutation {
  843. adjustOrderLine(orderLineId: "T_1", quantity: 1, customFields: { validateInt: 2 }) {
  844. ... on Order {
  845. id
  846. lines {
  847. customFields {
  848. validateInt
  849. }
  850. }
  851. }
  852. }
  853. }
  854. `);
  855. expect(result.lines[0].customFields).toEqual({ validateInt: 2 });
  856. });
  857. });
  858. });
  859. describe('public access', () => {
  860. it(
  861. 'non-public throws for Shop API',
  862. assertThrowsWithMessage(async () => {
  863. await shopClient.query(gql`
  864. query {
  865. product(id: "T_1") {
  866. id
  867. customFields {
  868. nonPublic
  869. }
  870. }
  871. }
  872. `);
  873. }, 'Cannot query field "nonPublic" on type "ProductCustomFields"'),
  874. );
  875. it('publicly accessible via Shop API', async () => {
  876. const { product } = await shopClient.query(gql`
  877. query {
  878. product(id: "T_1") {
  879. id
  880. customFields {
  881. public
  882. }
  883. }
  884. }
  885. `);
  886. expect(product.customFields.public).toBe('ho!');
  887. });
  888. it(
  889. 'internal throws for Shop API',
  890. assertThrowsWithMessage(async () => {
  891. await shopClient.query(gql`
  892. query {
  893. product(id: "T_1") {
  894. id
  895. customFields {
  896. internalString
  897. }
  898. }
  899. }
  900. `);
  901. }, 'Cannot query field "internalString" on type "ProductCustomFields"'),
  902. );
  903. it(
  904. 'internal throws for Admin API',
  905. assertThrowsWithMessage(async () => {
  906. await adminClient.query(gql`
  907. query {
  908. product(id: "T_1") {
  909. id
  910. customFields {
  911. internalString
  912. }
  913. }
  914. }
  915. `);
  916. }, 'Cannot query field "internalString" on type "ProductCustomFields"'),
  917. );
  918. // https://github.com/vendurehq/vendure/issues/3049
  919. it('does not leak private fields via JSON type', async () => {
  920. const { collection } = await shopClient.query(gql`
  921. query {
  922. collection(id: "T_1") {
  923. id
  924. customFields
  925. }
  926. }
  927. `);
  928. expect(collection.customFields).toBe(null);
  929. });
  930. });
  931. describe('sort & filter', () => {
  932. it('can sort by custom fields', async () => {
  933. const { products } = await adminClient.query(gql`
  934. query {
  935. products(options: { sort: { nullable: ASC } }) {
  936. totalItems
  937. }
  938. }
  939. `);
  940. expect(products.totalItems).toBe(1);
  941. });
  942. // https://github.com/vendurehq/vendure/issues/1581
  943. it('can sort by localeString custom fields', async () => {
  944. const { products } = await adminClient.query(gql`
  945. query {
  946. products(options: { sort: { localeStringWithDefault: ASC } }) {
  947. totalItems
  948. }
  949. }
  950. `);
  951. expect(products.totalItems).toBe(1);
  952. });
  953. it('can filter by custom fields', async () => {
  954. const { products } = await adminClient.query(gql`
  955. query {
  956. products(options: { filter: { stringWithDefault: { contains: "hello" } } }) {
  957. totalItems
  958. }
  959. }
  960. `);
  961. expect(products.totalItems).toBe(1);
  962. });
  963. it('can filter by localeString custom fields', async () => {
  964. const { products } = await adminClient.query(gql`
  965. query {
  966. products(options: { filter: { localeStringWithDefault: { contains: "hola" } } }) {
  967. totalItems
  968. }
  969. }
  970. `);
  971. expect(products.totalItems).toBe(1);
  972. });
  973. it('can filter by custom list fields', async () => {
  974. const { products: result1 } = await adminClient.query(gql`
  975. query {
  976. products(options: { filter: { intListWithValidation: { inList: 42 } } }) {
  977. totalItems
  978. }
  979. }
  980. `);
  981. expect(result1.totalItems).toBe(1);
  982. const { products: result2 } = await adminClient.query(gql`
  983. query {
  984. products(options: { filter: { intListWithValidation: { inList: 43 } } }) {
  985. totalItems
  986. }
  987. }
  988. `);
  989. expect(result2.totalItems).toBe(0);
  990. });
  991. it(
  992. 'cannot sort by custom list fields',
  993. assertThrowsWithMessage(async () => {
  994. await adminClient.query(gql`
  995. query {
  996. products(options: { sort: { intListWithValidation: ASC } }) {
  997. totalItems
  998. }
  999. }
  1000. `);
  1001. }, 'Field "intListWithValidation" is not defined by type "ProductSortParameter".'),
  1002. );
  1003. it(
  1004. 'cannot filter by internal field in Admin API',
  1005. assertThrowsWithMessage(async () => {
  1006. await adminClient.query(gql`
  1007. query {
  1008. products(options: { filter: { internalString: { contains: "hello" } } }) {
  1009. totalItems
  1010. }
  1011. }
  1012. `);
  1013. }, 'Field "internalString" is not defined by type "ProductFilterParameter"'),
  1014. );
  1015. it(
  1016. 'cannot filter by internal field in Shop API',
  1017. assertThrowsWithMessage(async () => {
  1018. await shopClient.query(gql`
  1019. query {
  1020. products(options: { filter: { internalString: { contains: "hello" } } }) {
  1021. totalItems
  1022. }
  1023. }
  1024. `);
  1025. }, 'Field "internalString" is not defined by type "ProductFilterParameter"'),
  1026. );
  1027. });
  1028. describe('product on productVariant entity', () => {
  1029. it('is translated', async () => {
  1030. const { productVariants } = await adminClient.query(gql`
  1031. query {
  1032. productVariants(productId: "T_1") {
  1033. items {
  1034. product {
  1035. name
  1036. id
  1037. customFields {
  1038. localeStringWithDefault
  1039. stringWithDefault
  1040. }
  1041. }
  1042. }
  1043. }
  1044. }
  1045. `);
  1046. expect(productVariants.items[0].product).toEqual({
  1047. id: 'T_1',
  1048. name: 'Laptop',
  1049. customFields: {
  1050. localeStringWithDefault: 'hola',
  1051. stringWithDefault: 'hello',
  1052. },
  1053. });
  1054. });
  1055. });
  1056. describe('unique constraint', () => {
  1057. it('setting unique value works', async () => {
  1058. const result = await adminClient.query(gql`
  1059. mutation {
  1060. updateProduct(input: { id: "T_1", customFields: { uniqueString: "foo" } }) {
  1061. id
  1062. customFields {
  1063. uniqueString
  1064. }
  1065. }
  1066. }
  1067. `);
  1068. expect(result.updateProduct.customFields.uniqueString).toBe('foo');
  1069. });
  1070. it('setting conflicting value fails', async () => {
  1071. try {
  1072. await adminClient.query(gql`
  1073. mutation {
  1074. createProduct(
  1075. input: {
  1076. translations: [
  1077. { languageCode: en, name: "test 2", slug: "test-2", description: "" }
  1078. ]
  1079. customFields: { uniqueString: "foo" }
  1080. }
  1081. ) {
  1082. id
  1083. }
  1084. }
  1085. `);
  1086. fail('Should have thrown');
  1087. } catch (e: any) {
  1088. let duplicateKeyErrMessage = 'unassigned';
  1089. switch (customConfig.dbConnectionOptions.type) {
  1090. case 'mariadb':
  1091. case 'mysql':
  1092. duplicateKeyErrMessage = "Duplicate entry 'foo' for key";
  1093. break;
  1094. case 'postgres':
  1095. duplicateKeyErrMessage = 'duplicate key value violates unique constraint';
  1096. break;
  1097. case 'sqlite':
  1098. case 'sqljs':
  1099. duplicateKeyErrMessage = 'UNIQUE constraint failed: product.customFieldsUniquestring';
  1100. break;
  1101. }
  1102. expect(e.message).toContain(duplicateKeyErrMessage);
  1103. }
  1104. });
  1105. });
  1106. it('on ProductVariantPrice', async () => {
  1107. const { updateProductVariants } = await adminClient.query(
  1108. gql`
  1109. mutation UpdateProductVariants($input: [UpdateProductVariantInput!]!) {
  1110. updateProductVariants(input: $input) {
  1111. id
  1112. prices {
  1113. currencyCode
  1114. price
  1115. customFields {
  1116. costPrice
  1117. }
  1118. }
  1119. }
  1120. }
  1121. `,
  1122. {
  1123. input: [
  1124. {
  1125. id: 'T_1',
  1126. prices: [
  1127. {
  1128. price: 129900,
  1129. currencyCode: 'USD',
  1130. customFields: {
  1131. costPrice: 100,
  1132. },
  1133. },
  1134. ],
  1135. },
  1136. ],
  1137. },
  1138. );
  1139. expect(updateProductVariants[0].prices).toEqual([
  1140. {
  1141. currencyCode: 'USD',
  1142. price: 129900,
  1143. customFields: {
  1144. costPrice: 100,
  1145. },
  1146. },
  1147. ]);
  1148. });
  1149. describe('setting custom fields directly via a service method', () => {
  1150. it('OrderService.addItemToOrder warns on unknown custom field', async () => {
  1151. const orderService = server.app.get(OrderService);
  1152. const requestContextService = server.app.get(RequestContextService);
  1153. const ctx = await requestContextService.create({
  1154. apiType: 'admin',
  1155. });
  1156. const order = await orderService.create(ctx);
  1157. const warnSpy = vi.spyOn(Logger, 'warn');
  1158. await orderService.addItemToOrder(ctx, order.id, 1, 1, {
  1159. customFieldWhichDoesNotExist: 'test value',
  1160. });
  1161. expect(warnSpy).toHaveBeenCalledWith(
  1162. 'Custom field customFieldWhichDoesNotExist not found for entity OrderLine',
  1163. );
  1164. });
  1165. it('OrderService.addItemToOrder does not warn on known custom field', async () => {
  1166. const orderService = server.app.get(OrderService);
  1167. const requestContextService = server.app.get(RequestContextService);
  1168. const ctx = await requestContextService.create({
  1169. apiType: 'admin',
  1170. });
  1171. const order = await orderService.create(ctx);
  1172. const warnSpy = vi.spyOn(Logger, 'warn');
  1173. await orderService.addItemToOrder(ctx, order.id, 1, 1, {
  1174. validateInt: 1,
  1175. });
  1176. expect(warnSpy).not.toHaveBeenCalled();
  1177. });
  1178. it('OrderService.addItemToOrder warns on multiple unknown custom fields', async () => {
  1179. const orderService = server.app.get(OrderService);
  1180. const requestContextService = server.app.get(RequestContextService);
  1181. const ctx = await requestContextService.create({
  1182. apiType: 'admin',
  1183. });
  1184. const order = await orderService.create(ctx);
  1185. const warnSpy = vi.spyOn(Logger, 'warn');
  1186. await orderService.addItemToOrder(ctx, order.id, 1, 1, {
  1187. unknownField1: 'foo',
  1188. unknownField2: 'bar',
  1189. });
  1190. expect(warnSpy).toHaveBeenCalledWith('Custom field unknownField1 not found for entity OrderLine');
  1191. expect(warnSpy).toHaveBeenCalledWith('Custom field unknownField2 not found for entity OrderLine');
  1192. });
  1193. it('OrderService.addItemToOrder does not warn when no custom fields are provided', async () => {
  1194. const orderService = server.app.get(OrderService);
  1195. const requestContextService = server.app.get(RequestContextService);
  1196. const ctx = await requestContextService.create({
  1197. apiType: 'admin',
  1198. });
  1199. const order = await orderService.create(ctx);
  1200. const warnSpy = vi.spyOn(Logger, 'warn');
  1201. await orderService.addItemToOrder(ctx, order.id, 1, 1);
  1202. expect(warnSpy).not.toHaveBeenCalled();
  1203. });
  1204. it('warns on unknown custom field in ProductTranslation entity', async () => {
  1205. const productService = server.app.get(ProductService);
  1206. const requestContextService = server.app.get(RequestContextService);
  1207. const ctx = await requestContextService.create({
  1208. apiType: 'admin',
  1209. });
  1210. const warnSpy = vi.spyOn(Logger, 'warn');
  1211. await productService.create(ctx, {
  1212. translations: [
  1213. {
  1214. languageCode: LanguageCode.en,
  1215. name: 'test',
  1216. slug: 'test',
  1217. description: '',
  1218. customFields: { customFieldWhichDoesNotExist: 'foo' },
  1219. },
  1220. ],
  1221. });
  1222. expect(warnSpy).toHaveBeenCalledWith(
  1223. 'Custom field customFieldWhichDoesNotExist not found for entity ProductTranslation',
  1224. );
  1225. });
  1226. it('does not warn when Translation has a valid custom field', async () => {
  1227. const productService = server.app.get(ProductService);
  1228. const requestContextService = server.app.get(RequestContextService);
  1229. const ctx = await requestContextService.create({
  1230. apiType: 'admin',
  1231. });
  1232. const warnSpy = vi.spyOn(Logger, 'warn');
  1233. await productService.create(ctx, {
  1234. translations: [
  1235. {
  1236. languageCode: LanguageCode.en,
  1237. name: 'test',
  1238. slug: 'test',
  1239. description: '',
  1240. customFields: { localeStringWithDefault: 'foo' },
  1241. },
  1242. ],
  1243. });
  1244. expect(warnSpy).not.toHaveBeenCalled();
  1245. });
  1246. });
  1247. });