From 4dd29bf4e874362b8f885b94c69a22ef76034fc5 Mon Sep 17 00:00:00 2001 From: James Date: Sat, 26 Aug 2023 16:24:35 -0400 Subject: [PATCH] chore: ensures blocks can be updated while saving additional locales --- .../db-postgres/src/find/traverseFields.ts | 2 +- .../src/transform/read/mergeLocales.ts | 86 ------ .../src/transform/read/traverseFields.ts | 23 +- .../src/transform/write/traverseFields.ts | 49 ++-- .../db-postgres/src/transform/write/types.ts | 2 - .../src/upsertRow/deleteExistingArrayRows.ts | 39 +++ ...ildRows.ts => deleteExistingRowsByPath.ts} | 31 +- packages/db-postgres/src/upsertRow/index.ts | 15 +- src/collections/operations/updateByID.ts | 1 - src/fields/hooks/beforeChange/promise.ts | 10 +- src/fields/hooks/beforeValidate/promise.ts | 8 +- test/postgres/collections/Posts.ts | 4 + test/postgres/config.ts | 16 +- test/postgres/int.spec.ts | 273 ++++++++++++++++++ test/postgres/seed/complexDocs.ts | 208 +------------ 15 files changed, 393 insertions(+), 374 deletions(-) delete mode 100644 packages/db-postgres/src/transform/read/mergeLocales.ts create mode 100644 packages/db-postgres/src/upsertRow/deleteExistingArrayRows.ts rename packages/db-postgres/src/upsertRow/{deleteChildRows.ts => deleteExistingRowsByPath.ts} (55%) create mode 100644 test/postgres/int.spec.ts diff --git a/packages/db-postgres/src/find/traverseFields.ts b/packages/db-postgres/src/find/traverseFields.ts index 074d94f517..e644f80230 100644 --- a/packages/db-postgres/src/find/traverseFields.ts +++ b/packages/db-postgres/src/find/traverseFields.ts @@ -84,7 +84,7 @@ export const traverseFields = ({ with: {}, }; - if (adapter.tables[`${topLevelArgs}_${toSnakeCase(block.slug)}_locales`]) withBlock.with._locales = _locales; + if (adapter.tables[`${topLevelTableName}_${toSnakeCase(block.slug)}_locales`]) withBlock.with._locales = _locales; topLevelArgs.with[blockKey] = withBlock; traverseFields({ diff --git a/packages/db-postgres/src/transform/read/mergeLocales.ts b/packages/db-postgres/src/transform/read/mergeLocales.ts deleted file mode 100644 index f07095b79f..0000000000 --- a/packages/db-postgres/src/transform/read/mergeLocales.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* eslint-disable no-param-reassign */ -import { FieldAffectingData, UIField, fieldAffectsData } from 'payload/dist/fields/config/types'; -import { Field } from 'payload/types'; -import flattenTopLevelFields from 'payload/dist/utilities/flattenTopLevelFields'; - -type TraverseFieldsArgs = { - dataRef?: Record - fields: (UIField | FieldAffectingData)[] - parentIsLocalized?: boolean - localeRow: Record - prefix?: string -} - -const traverseFields = ({ - dataRef, - fields, - parentIsLocalized, - localeRow, - prefix, -}: TraverseFieldsArgs) => { - const locale = localeRow._locale; - - if (typeof locale === 'string') { - fields.forEach((field) => { - if (fieldAffectsData(field) && (field.localized || parentIsLocalized)) { - switch (field.type) { - // TODO: handle named tabs - case 'group': { - const flattenedFields = flattenTopLevelFields(field.fields); - if (!dataRef[field.name]) dataRef[field.name] = {}; - if (!dataRef[field.name][locale]) dataRef[field.name][locale] = {}; - - traverseFields({ - dataRef: dataRef[field.name][locale] as Record, - fields: flattenedFields, - parentIsLocalized: true, - localeRow, - prefix: `${prefix || ''}${field.name}_`, - }); - - break; - } - - default: { - const localeData = localeRow[`${prefix}${field.name}`]; - - if (parentIsLocalized) { - dataRef[field.name] = localeData; - } else { - if (typeof dataRef[field.name] !== 'object') dataRef[field.name] = {}; - dataRef[field.name][locale] = localeData; - } - } - } - } - }); - } -}; - -type MergeLocalesArgs = { - fields: Field[] - table: Record -} - -// Merge _locales into the parent data -export const mergeLocales = ({ - fields, - table, -}: MergeLocalesArgs): Record => { - const localeRows = table._locales; - const flattenedFields = flattenTopLevelFields(fields); - - if (Array.isArray(localeRows)) { - localeRows.forEach((localeRow) => { - traverseFields({ - dataRef: table, - fields: flattenedFields, - localeRow, - }); - }); - } - - delete table._locales; - - return table; -}; diff --git a/packages/db-postgres/src/transform/read/traverseFields.ts b/packages/db-postgres/src/transform/read/traverseFields.ts index 5d23d6dca5..c4f48a6c2a 100644 --- a/packages/db-postgres/src/transform/read/traverseFields.ts +++ b/packages/db-postgres/src/transform/read/traverseFields.ts @@ -3,7 +3,6 @@ import { fieldAffectsData } from 'payload/dist/fields/config/types'; import { Field } from 'payload/types'; import { SanitizedConfig } from 'payload/config'; import { BlocksMap } from '../../utilities/createBlocksMap'; -import { transform } from '.'; import { transformRelationship } from './relationship'; type TraverseFieldsArgs = { @@ -263,24 +262,30 @@ export const traverseFields = >({ } case 'number': { + let val = fieldData; // TODO: handle hasMany if (typeof fieldData === 'string') { - const val = Number.parseFloat(fieldData); + val = Number.parseFloat(fieldData); + } - if (typeof locale === 'string') { - ref[locale] = val; - } else { - result[field.name] = val; - } + if (typeof locale === 'string') { + ref[locale] = val; + } else { + result[field.name] = val; } break; } case 'date': { - // TODO: handle localized date fields if (fieldData instanceof Date) { - result[field.name] = fieldData.toISOString(); + const val = fieldData.toISOString(); + + if (typeof locale === 'string') { + ref[locale] = val; + } else { + result[field.name] = val; + } } break; diff --git a/packages/db-postgres/src/transform/write/traverseFields.ts b/packages/db-postgres/src/transform/write/traverseFields.ts index fdb0fef849..b21c0630ca 100644 --- a/packages/db-postgres/src/transform/write/traverseFields.ts +++ b/packages/db-postgres/src/transform/write/traverseFields.ts @@ -47,7 +47,6 @@ export const traverseFields = ({ let targetRow = row; let columnName = ''; let fieldData: unknown; - let hasLocalizedFieldData = false; if (fieldAffectsData(field)) { columnName = `${columnPrefix || ''}${field.name}`; @@ -59,10 +58,10 @@ export const traverseFields = ({ targetRow = localeRow; if (typeof data[field.name] === 'object' && data[field.name] !== null) { - hasLocalizedFieldData = true; - if (typeof data[field.name][locale] !== 'undefined') { fieldData = data[field.name][locale]; + } else { + fieldData = undefined; } } } @@ -96,16 +95,6 @@ export const traverseFields = ({ arrays[arrayTableName] = arrays[arrayTableName].concat(newRows); - // Above, the currently edited locale is being transformed - // Need to do this above thing for all other locales as well - - // if (field.localized && hasLocalizedFieldData) { - // newRow.existingLocales = Object.entries(data[field.name]).map(([existingLocale, existingLocaleData]) => { - // existingLocaleData._locale = existingLocale - // return existingLocaleData - // }) - // } - break; } @@ -120,7 +109,6 @@ export const traverseFields = ({ const newRow: BlockRowToInsert = { arrays: {}, - existingLocales: {}, row: { _order: i + 1, _path: `${path}${field.name}`, @@ -137,7 +125,6 @@ export const traverseFields = ({ blocks, columnPrefix: '', data: blockRow, - existingLocales: newRow.existingLocales, fields: matchedBlock.fields, locale, localeRow: newRow.locale, @@ -258,19 +245,29 @@ export const traverseFields = ({ const relations = Array.isArray(fieldData) ? fieldData : [fieldData]; relations.forEach((relation, i) => { - const relationRow: Record = { - path: `${path || ''}${field.name}`, - }; + if (relation) { + const relationRow: Record = { + path: `${path || ''}${field.name}`, + }; - if ('hasMany' in field && field.hasMany) relationRow.order = i + 1; - if (field.localized) relationRow.locale = locale; + if ('hasMany' in field && field.hasMany) relationRow.order = i + 1; + if (field.localized) { + relationRow.locale = locale; - if (Array.isArray(field.relationTo) && valueIsValueWithRelation(relation)) { - relationRow[`${relation.relationTo}ID`] = relation.value; - relationships.push(relationRow); - } else { - relationRow[`${field.relationTo}ID`] = relation; - if (relation) relationships.push(relationRow); + if (Array.isArray(field.relationTo) && valueIsValueWithRelation(relation)) { + relationRow[`${relation.relationTo}ID`] = relation.value; + relationships.push(relationRow); + } else { + relationRow[`${field.relationTo}ID`] = relation; + if (relation) relationships.push(relationRow); + } + } else if (Array.isArray(field.relationTo) && valueIsValueWithRelation(relation)) { + relationRow[`${relation.relationTo}ID`] = relation.value; + relationships.push(relationRow); + } else { + relationRow[`${field.relationTo}ID`] = relation; + if (relation) relationships.push(relationRow); + } } }); diff --git a/packages/db-postgres/src/transform/write/types.ts b/packages/db-postgres/src/transform/write/types.ts index 200cab8a3b..a3f6eb5274 100644 --- a/packages/db-postgres/src/transform/write/types.ts +++ b/packages/db-postgres/src/transform/write/types.ts @@ -2,7 +2,6 @@ export type ArrayRowToInsert = { columnName: string row: Record, locale: Record - existingLocales: Record[] arrays: { [tableName: string]: ArrayRowToInsert[] } @@ -11,7 +10,6 @@ export type ArrayRowToInsert = { export type BlockRowToInsert = { row: Record, locale: Record - existingLocales: Record[] arrays: { [tableName: string]: ArrayRowToInsert[] } diff --git a/packages/db-postgres/src/upsertRow/deleteExistingArrayRows.ts b/packages/db-postgres/src/upsertRow/deleteExistingArrayRows.ts new file mode 100644 index 0000000000..833fb105f6 --- /dev/null +++ b/packages/db-postgres/src/upsertRow/deleteExistingArrayRows.ts @@ -0,0 +1,39 @@ +import { and, eq } from 'drizzle-orm'; +import { PostgresAdapter } from '../types'; + +type Args = { + adapter: PostgresAdapter + locale?: string + localeColumnName?: string + parentColumnName?: string + parentID: unknown + pathColumnName?: string + newRows: Record[] + tableName: string +} + +export const deleteExistingArrayRows = async ({ + adapter, + locale, + parentID, + tableName, +}: Args): Promise => { + const table = adapter.tables[tableName]; + + const whereConstraints = [ + eq(table._parentID, parentID), + ]; + + // If table has a _locale column, + // match on only the locale being updated + if (typeof table._locale !== 'undefined') { + whereConstraints.push( + eq(table._locale, locale), + ); + } + + await adapter.db.delete(table) + .where( + and(...whereConstraints), + ); +}; diff --git a/packages/db-postgres/src/upsertRow/deleteChildRows.ts b/packages/db-postgres/src/upsertRow/deleteExistingRowsByPath.ts similarity index 55% rename from packages/db-postgres/src/upsertRow/deleteChildRows.ts rename to packages/db-postgres/src/upsertRow/deleteExistingRowsByPath.ts index b1c961c525..32c60f6e95 100644 --- a/packages/db-postgres/src/upsertRow/deleteChildRows.ts +++ b/packages/db-postgres/src/upsertRow/deleteExistingRowsByPath.ts @@ -8,28 +8,25 @@ type Args = { parentColumnName?: string parentID: unknown pathColumnName?: string - rows: Record[] + newRows: Record[] tableName: string } -// TODO: Locale is not on block or array rows -// need to only delete locale rows / recreate them if applicable -// not sure what to do here yet... Arrays are helpful to see this in action - -export const deleteChildRows = async ({ +export const deleteExistingRowsByPath = async ({ adapter, locale, localeColumnName = '_locale', parentColumnName = '_parentID', parentID, - pathColumnName, - rows, + pathColumnName = '_path', + newRows, tableName, }: Args): Promise => { const localizedPathsToDelete = new Set(); const pathsToDelete = new Set(); + const table = adapter.tables[tableName]; - rows.forEach((row) => { + newRows.forEach((row) => { const path = row[pathColumnName]; const localeData = row[localeColumnName]; if (typeof path === 'string') { @@ -43,13 +40,13 @@ export const deleteChildRows = async ({ if (localizedPathsToDelete.size > 0 && locale) { const whereConstraints = [ - eq(adapter.tables[tableName][parentColumnName], parentID), - eq(adapter.tables[tableName][localeColumnName], locale), + eq(table[parentColumnName], parentID), + eq(table[localeColumnName], locale), ]; - if (pathColumnName) whereConstraints.push(inArray(adapter.tables[tableName][pathColumnName], [localizedPathsToDelete])); + if (pathColumnName) whereConstraints.push(inArray(table[pathColumnName], Array.from(localizedPathsToDelete))); - await adapter.db.delete(adapter.tables[tableName]) + await adapter.db.delete(table) .where( and(...whereConstraints), ); @@ -57,14 +54,14 @@ export const deleteChildRows = async ({ if (pathsToDelete.size > 0) { const whereConstraints = [ - eq(adapter.tables[tableName][parentColumnName], parentID), + eq(table[parentColumnName], parentID), ]; - if (pathColumnName) whereConstraints.push(inArray(adapter.tables[tableName][pathColumnName], [pathsToDelete])); + if (pathColumnName) whereConstraints.push(inArray(table[pathColumnName], Array.from(pathsToDelete))); - await adapter.db.delete(adapter.tables[tableName]) + await adapter.db.delete(table) .where( and(...whereConstraints), - ); + ).returning(); } }; diff --git a/packages/db-postgres/src/upsertRow/index.ts b/packages/db-postgres/src/upsertRow/index.ts index 2ece52d325..33c249f67d 100644 --- a/packages/db-postgres/src/upsertRow/index.ts +++ b/packages/db-postgres/src/upsertRow/index.ts @@ -4,7 +4,8 @@ import { BlockRowToInsert } from '../transform/write/types'; import { insertArrays } from '../insertArrays'; import { transformForWrite } from '../transform/write'; import { Args } from './types'; -import { deleteChildRows } from './deleteChildRows'; +import { deleteExistingRowsByPath } from './deleteExistingRowsByPath'; +import { deleteExistingArrayRows } from './deleteExistingArrayRows'; export const upsertRow = async ({ adapter, @@ -119,14 +120,14 @@ export const upsertRow = async ({ promises.push(async () => { const relationshipsTableName = `${tableName}_relationships`; if (operation === 'update') { - await deleteChildRows({ + await deleteExistingRowsByPath({ adapter, locale, localeColumnName: 'locale', parentColumnName: 'parent', parentID: insertedRow.id, pathColumnName: 'path', - rows: relationsToInsert, + newRows: relationsToInsert, tableName: relationshipsTableName, }); } @@ -146,12 +147,12 @@ export const upsertRow = async ({ // For each block, push insert into promises to run parallel promises.push(async () => { if (operation === 'update') { - await deleteChildRows({ + await deleteExistingRowsByPath({ adapter, locale, parentID: insertedRow.id, pathColumnName: '_path', - rows: blockRows.map(({ row }) => row), + newRows: blockRows.map(({ row }) => row), tableName: `${tableName}_${blockName}`, }); } @@ -203,11 +204,11 @@ export const upsertRow = async ({ promises.push(async () => { if (operation === 'update') { await Promise.all(Object.entries(rowToInsert.arrays).map(async ([arrayTableName, tableRows]) => { - await deleteChildRows({ + await deleteExistingArrayRows({ adapter, locale, parentID: insertedRow.id, - rows: tableRows.map(({ row }) => row), + newRows: tableRows.map(({ row }) => row), tableName: arrayTableName, }); })); diff --git a/src/collections/operations/updateByID.ts b/src/collections/operations/updateByID.ts index ae57a9da49..d110294900 100644 --- a/src/collections/operations/updateByID.ts +++ b/src/collections/operations/updateByID.ts @@ -116,7 +116,6 @@ async function updateByID( // Retrieve document // ///////////////////////////////////// - const findOneArgs: FindOneArgs = { collection: collectionConfig.slug, where: combineQueries({ id: { equals: id } }, accessResults), diff --git a/src/fields/hooks/beforeChange/promise.ts b/src/fields/hooks/beforeChange/promise.ts index f13e3564fb..672c8f65af 100644 --- a/src/fields/hooks/beforeChange/promise.ts +++ b/src/fields/hooks/beforeChange/promise.ts @@ -231,7 +231,11 @@ export const promise = async ({ if (Array.isArray(rows)) { const promises = []; rows.forEach((row, i) => { - const block = field.blocks.find((blockType) => blockType.slug === row.blockType); + const rowSiblingDoc = getExistingRowDoc(row, siblingDoc[field.name]); + const rowSiblingDocWithLocales = getExistingRowDoc(row, siblingDocWithLocales[field.name]); + + const blockTypeToMatch = row.blockType || rowSiblingDoc.blockType; + const block = field.blocks.find((blockType) => blockType.slug === blockTypeToMatch); if (block) { promises.push(traverseFields({ @@ -246,8 +250,8 @@ export const promise = async ({ path: `${path}${field.name}.${i}.`, req, siblingData: row, - siblingDoc: getExistingRowDoc(row, siblingDoc[field.name]), - siblingDocWithLocales: getExistingRowDoc(row, siblingDocWithLocales[field.name]), + siblingDoc: rowSiblingDoc, + siblingDocWithLocales: rowSiblingDocWithLocales, skipValidation: skipValidationFromHere, context, })); diff --git a/src/fields/hooks/beforeValidate/promise.ts b/src/fields/hooks/beforeValidate/promise.ts index 5f206dc3fc..c5acc2e437 100644 --- a/src/fields/hooks/beforeValidate/promise.ts +++ b/src/fields/hooks/beforeValidate/promise.ts @@ -267,9 +267,13 @@ export const promise = async ({ if (Array.isArray(rows)) { const promises = []; rows.forEach((row, i) => { - const block = field.blocks.find((blockType) => blockType.slug === row.blockType); + const rowSiblingDoc = getExistingRowDoc(row, siblingDoc[field.name]); + const blockTypeToMatch = row.blockType || rowSiblingDoc.blockType; + const block = field.blocks.find((blockType) => blockType.slug === blockTypeToMatch); if (block) { + row.blockType = blockTypeToMatch; + promises.push(traverseFields({ data, doc, @@ -279,7 +283,7 @@ export const promise = async ({ overrideAccess, req, siblingData: row, - siblingDoc: getExistingRowDoc(row, siblingDoc[field.name]), + siblingDoc: rowSiblingDoc, context, })); } diff --git a/test/postgres/collections/Posts.ts b/test/postgres/collections/Posts.ts index dde044ab41..36649aae11 100644 --- a/test/postgres/collections/Posts.ts +++ b/test/postgres/collections/Posts.ts @@ -78,6 +78,7 @@ export const Posts: CollectionConfig = { name: 'relationHasOne', type: 'relationship', relationTo: 'pages', + localized: true, }, // Has Many { @@ -85,12 +86,14 @@ export const Posts: CollectionConfig = { type: 'relationship', hasMany: true, relationTo: 'pages', + localized: true, }, // Has One - Polymorphic { name: 'relationHasOnePoly', type: 'relationship', relationTo: ['people', 'pages'], + localized: true, }, // Has Many - Polymorphic { @@ -98,6 +101,7 @@ export const Posts: CollectionConfig = { type: 'relationship', hasMany: true, relationTo: ['people', 'pages'], + localized: true, }, { name: 'selfReferencingRelationship', diff --git a/test/postgres/config.ts b/test/postgres/config.ts index b443fd1265..e82fffa0e0 100644 --- a/test/postgres/config.ts +++ b/test/postgres/config.ts @@ -3,16 +3,12 @@ import { LocalizedArrays } from './collections/LocalizedArrays'; import { LocalizedBlocks } from './collections/LocalizedBlocks'; import { LocalizedGroups } from './collections/LocalizedGroups'; import { Posts } from './collections/Posts'; -import { seedComplexDocs } from './seed/complexDocs'; -import { seedLocalizedArrays } from './seed/localizedArrays'; -import { seedLocalizedBlocks } from './seed/localizedBlocks'; -import { seedLocalizedGroups } from './seed/localizedGroups'; const config = buildConfigWithDefaults({ collections: [ - // LocalizedArrays, - // LocalizedBlocks, - // LocalizedGroups, + LocalizedArrays, + LocalizedBlocks, + LocalizedGroups, Posts, { slug: 'pages', @@ -38,12 +34,6 @@ const config = buildConfigWithDefaults({ locales: ['en', 'es'], defaultLocale: 'en', }, - onInit: async (payload) => { - await seedComplexDocs(payload); - // await seedLocalizedGroups(payload); - // await seedLocalizedArrays(payload); - // await seedLocalizedBlocks(payload); - }, }); export default config; diff --git a/test/postgres/int.spec.ts b/test/postgres/int.spec.ts new file mode 100644 index 0000000000..187e4fc5f8 --- /dev/null +++ b/test/postgres/int.spec.ts @@ -0,0 +1,273 @@ +import payload from '../../src'; +import { initPayloadTest } from '../helpers/configHelpers'; + +describe('Postgres', () => { + beforeAll(async () => { + process.env.PAYLOAD_DROP_DATABASE = 'true'; + await initPayloadTest({ __dirname, init: { local: false } }); + }); + + let post; + let page1; + let page2; + let person1; + let person2; + + it('creates a complex doc', async () => { + page1 = await payload.create({ + collection: 'pages', + data: { + slug: 'first', + }, + }); + + page2 = await payload.create({ + collection: 'pages', + data: { + slug: 'second', + }, + }); + + person1 = await payload.create({ + collection: 'people', + data: { + fullName: 'Dan Ribbens', + }, + }); + + person2 = await payload.create({ + collection: 'people', + data: { + fullName: 'Elliot DeNolf', + }, + }); + + const postTitleEN = 'hello'; + + post = await payload.create({ + collection: 'posts', + data: { + title: postTitleEN, + number: 1337, + myGroup: { + subField: 'hello', + subFieldLocalized: 'hello in english', + subGroup: { + subSubField: 'sub hello', + subSubFieldLocalized: 'sub hello in english', + }, + groupArray: [ + { + groupArrayText: 'hello 1', + }, + { + groupArrayText: 'hello 2', + }, + ], + }, + relationHasOne: page1.id, + relationHasOnePoly: { + relationTo: 'people', + value: person1.id, + }, + relationHasMany: [page1.id, page2.id], + relationHasManyPoly: [ + { + relationTo: 'people', + value: person1.id, + }, + { + relationTo: 'pages', + value: page2.id, + }, + ], + myArray: [ + { + subField: 'hello 1', + mySubArray: [ + { + subSubField: 'row 1 subrow 1', + }, + { + subSubField: 'row 1 subrow 2', + }, + ], + }, + { + subField: 'hello 2', + mySubArray: [ + { + subSubField: 'row 2 subrow 1', + }, + { + subSubField: 'row 2 subrow 2', + }, + ], + }, + ], + myBlocks: [ + { + blockType: 'block1', + nonLocalizedText: 'hello', + localizedText: 'hello in english', + }, + { + blockType: 'block2', + number: 123, + blockArray: [ + { + subBlockArray: 'row 1', + }, + { + subBlockArray: 'row 2', + }, + ], + }, + ], + }, + }); + + expect(post.title).toEqual(postTitleEN); + expect(post.myBlocks[0].localizedText).toStrictEqual('hello in english'); + }); + + it('adds locale to existing doc', async () => { + const titleES = 'hello es'; + const arrayTitle = 'hello 1 spanish'; + const blockLocalizedText = 'my block in spanish'; + + const updatedPost = await payload.update({ + collection: 'posts', + id: post.id, + locale: 'es', + data: { + title: titleES, + number: 1000, + myArray: [ + { + id: post.myArray[0].id, + subField: arrayTitle, + }, + ], + myBlocks: [ + { + id: post.myBlocks[0].id, + localizedText: blockLocalizedText, + }, + ], + }, + }); + + expect(updatedPost.title).toStrictEqual(titleES); + expect(updatedPost.number).toStrictEqual(1000); + expect(updatedPost.myArray[0].subField).toStrictEqual(arrayTitle); + expect(updatedPost.myBlocks[0].localizedText).toStrictEqual(blockLocalizedText); + }); + + it('updates original locale', async () => { + const updatedTitle = 'hello 3'; + + const updatedPost = await payload.update({ + collection: 'posts', + id: post.id, + data: { + title: 'hello 3', + number: 1338, + myGroup: { + subFieldLocalized: 'hello in english updated', + subGroup: { + subSubField: 'sub hello updated', + subSubFieldLocalized: 'sub hello in english updated', + }, + groupArray: [ + { + groupArrayText: 'hello 1 updated', + }, + { + groupArrayText: 'hello 2 updated', + }, + ], + }, + relationHasOne: page2.id, + relationHasOnePoly: { + relationTo: 'people', + value: person2.id, + }, + relationHasMany: [page2.id, page1.id], + relationHasManyPoly: [ + { + relationTo: 'pages', + value: page2.id, + }, + { + relationTo: 'people', + value: person1.id, + }, + ], + myArray: [ + { + subField: 'hello 1 updated', + mySubArray: [ + { + subSubField: 'row 1 subrow 1 updated', + }, + { + subSubField: 'row 1 subrow 2 updated', + }, + ], + }, + { + subField: 'hello 2 updated', + mySubArray: [ + { + subSubField: 'row 2 subrow 1 updated', + }, + { + subSubField: 'row 2 subrow 2 updated', + }, + ], + }, + ], + myBlocks: [ + { + blockType: 'block1', + nonLocalizedText: 'hello updated', + localizedText: 'hello in english updated', + }, + { + blockType: 'block2', + number: 1234, + blockArray: [ + { + subBlockArray: 'row 1 updated', + }, + { + subBlockArray: 'row 2 updated', + }, + ], + }, + ], + }, + }); + + expect(updatedPost.title).toStrictEqual(updatedTitle); + expect(updatedPost.myArray[0].subField).toStrictEqual('hello 1 updated'); + expect(updatedPost.myArray[1].subField).toStrictEqual('hello 2 updated'); + expect(updatedPost.myBlocks[0].localizedText).toStrictEqual('hello in english updated'); + }); + + it('retrieves doc in all locales', async () => { + const postAllLocales = await payload.findByID({ + collection: 'posts', + id: post.id, + locale: 'all', + }); + + expect(postAllLocales.title.en).toStrictEqual('hello 3'); + expect(postAllLocales.title.es).toStrictEqual('hello es'); + expect(postAllLocales.number.en).toStrictEqual(1338); + expect(postAllLocales.number.es).toStrictEqual(1000); + expect(postAllLocales.myBlocks[0].localizedText.en).toStrictEqual('hello in english updated'); + expect(postAllLocales.myArray[0].subField.es).toStrictEqual('hello 1 spanish'); + }); +}); diff --git a/test/postgres/seed/complexDocs.ts b/test/postgres/seed/complexDocs.ts index 829b1ab994..b21b092a7e 100644 --- a/test/postgres/seed/complexDocs.ts +++ b/test/postgres/seed/complexDocs.ts @@ -1,20 +1,6 @@ import { Payload } from '../../../src'; export const seedComplexDocs = async (payload: Payload) => { - const page1 = await payload.create({ - collection: 'pages', - data: { - slug: 'first', - }, - }); - - const page2 = await payload.create({ - collection: 'pages', - data: { - slug: 'second', - }, - }); - // const findResult = await payload.find({ // collection: 'pages', // where: { slug: { equals: 'second' } }, @@ -25,198 +11,6 @@ export const seedComplexDocs = async (payload: Payload) => { // id: page1.id, // }); - const person1 = await payload.create({ - collection: 'people', - data: { - fullName: 'Dan Ribbens', - }, - }); - const person2 = await payload.create({ - collection: 'people', - data: { - fullName: 'Elliot DeNolf', - }, - }); - - const post = await payload.create({ - collection: 'posts', - data: { - title: 'hello', - number: 1337, - myGroup: { - subField: 'hello', - subFieldLocalized: 'hello in english', - subGroup: { - subSubField: 'sub hello', - subSubFieldLocalized: 'sub hello in english', - }, - groupArray: [ - { - groupArrayText: 'hello 1', - }, - { - groupArrayText: 'hello 2', - }, - ], - }, - relationHasOne: page1.id, - relationHasOnePoly: { - relationTo: 'people', - value: person1.id, - }, - relationHasMany: [page1.id, page2.id], - relationHasManyPoly: [ - { - relationTo: 'people', - value: person1.id, - }, - { - relationTo: 'pages', - value: page2.id, - }, - ], - myArray: [ - { - subField: 'hello 1', - mySubArray: [ - { - subSubField: 'row 1 subrow 1', - }, - { - subSubField: 'row 1 subrow 2', - }, - ], - }, - { - subField: 'hello 2', - mySubArray: [ - { - subSubField: 'row 2 subrow 1', - }, - { - subSubField: 'row 2 subrow 2', - }, - ], - }, - ], - myBlocks: [ - { - blockType: 'block1', - nonLocalizedText: 'hello', - localizedText: 'hello in english', - }, - { - blockType: 'block2', - number: 123, - blockArray: [ - { - subBlockArray: 'row 1', - }, - { - subBlockArray: 'row 2', - }, - ], - }, - ], - }, - }); - - await payload.update({ - collection: 'posts', - id: post.id, - locale: 'es', - data: { - title: 'hello es', - myArray: [ - { - id: post.myArray[0].id, - subField: 'hello 1 spanish', - }, - ], - }, - }); - - await payload.update({ - collection: 'posts', - id: post.id, - data: { - title: 'hello 3', - number: 1338, - myGroup: { - subFieldLocalized: 'hello in english updated', - subGroup: { - subSubField: 'sub hello updated', - subSubFieldLocalized: 'sub hello in english updated', - }, - groupArray: [ - { - groupArrayText: 'hello 1 updated', - }, - { - groupArrayText: 'hello 2 updated', - }, - ], - }, - relationHasOne: page2.id, - relationHasOnePoly: { - relationTo: 'people', - value: person2.id, - }, - relationHasMany: [page2.id, page1.id], - relationHasManyPoly: [ - { - relationTo: 'pages', - value: page2.id, - }, - { - relationTo: 'people', - value: person1.id, - }, - ], - myArray: [ - { - subField: 'hello 1 updated', - mySubArray: [ - { - subSubField: 'row 1 subrow 1 updated', - }, - { - subSubField: 'row 1 subrow 2 updated', - }, - ], - }, - { - subField: 'hello 2 updated', - mySubArray: [ - { - subSubField: 'row 2 subrow 1 updated', - }, - { - subSubField: 'row 2 subrow 2 updated', - }, - ], - }, - ], - myBlocks: [ - { - blockType: 'block1', - nonLocalizedText: 'hello updated', - localizedText: 'hello in english updated', - }, - { - blockType: 'block2', - number: 1234, - blockArray: [ - { - subBlockArray: 'row 1 updated', - }, - { - subBlockArray: 'row 2 updated', - }, - ], - }, - ], - }, - }); + console.log(postAllLocales); };