import { rewriteDocs } from '../lib/migrate-global-docs' import { fakeArgs, fakeCollection } from './helpers/fake-mongo' type Doc = Record const upper = (data: Doc) => { if (typeof data.title !== 'string') return 0 data.title = data.title.toUpperCase() return 1 } describe('rewriteDocs (MITHOME-112)', () => { it('should rewrite every document of a collection and all its versions by default', async () => { const docs = fakeCollection([ { _id: 'a', slug: 'adatvedelem', title: 'a' }, { _id: 'b', slug: 'hasznalati-feltetelek', title: 'b' }, ]) const versions = fakeCollection([ { _id: 'v1', latest: false, version: { title: 'old' } }, { _id: 'v2', latest: true, version: { title: 'new' } }, ]) const { args } = fakeArgs({ collections: { 'legal-pages': docs }, versions: { 'legal-pages': versions } }) const changed = await rewriteDocs(args, { kind: 'collection', slug: 'legal-pages' }, ['title'], upper) expect(changed).toBe(4) expect(docs.updateOne).toHaveBeenCalledWith({ _id: 'a' }, { $set: { title: 'A' } }, { session: undefined }) expect(versions.updateOne).toHaveBeenCalledTimes(2) }) it('should only touch the latest version when scoped to latest', async () => { const versions = fakeCollection([ { _id: 'v1', latest: false, version: { title: 'old' } }, { _id: 'v2', latest: true, version: { title: 'new' } }, ]) const { args } = fakeArgs({ collections: { 'legal-pages': fakeCollection([]) }, versions: { 'legal-pages': versions } }) await rewriteDocs(args, { kind: 'collection', slug: 'legal-pages' }, ['title'], upper, { versions: 'latest' }) expect(versions.updateOne).toHaveBeenCalledTimes(1) expect(versions.updateOne).toHaveBeenCalledWith({ _id: 'v2' }, { $set: { version: { title: 'NEW' } } }, { session: undefined }) }) it('should only read the targeted global', async () => { const globals = fakeCollection([ { _id: 'h', globalType: 'home', title: 'home' }, { _id: 'c', globalType: 'common', title: 'common' }, ]) const { args } = fakeArgs({ globals }) expect(await rewriteDocs(args, { kind: 'global', slug: 'home' }, ['title'], upper)).toBe(1) expect(globals.docs[1].title).toBe('common') }) it('should skip a collection that does not exist and version records without data', async () => { const versions = fakeCollection([{ _id: 'v', version: null }]) const { args } = fakeArgs({ versions: { nope: versions } }) expect(await rewriteDocs(args, { kind: 'collection', slug: 'nope' }, ['title'], upper)).toBe(0) }) })