Skip to content

Commit

Permalink
feat: provide entry id for transform and derive functions (#1212)
Browse files Browse the repository at this point in the history
For all transformation functions (`transformEntries`, `deriveLinkedEntries` and `transformEntriesToType`) we provide the entry id of the entry in scope in the call signature of the transform callbacks. This allows for cross checking the id with any other source, or more custom validations within scope.

We opted-in for an wrapping object as a third parameter to eventually enrich the callback with further data in the future.


**Example:** (more in the updated readme)
```js
module.exports = function (migration) {
  migration.transformEntries({
    contentType: 'newsArticle',
    from: ['author', 'authorCity'],
    to: ['byline'],
    transformEntryForLocale: function (fromFields, currentLocale, {id}) {
      
      if(id === '<specific-entry-id>') {
        return;
      }
      
      if (currentLocale === 'de-DE') {
        return;
      }
      const newByline = `${fromFields.author[currentLocale]} ${fromFields.authorCity[currentLocale]}`;
      return { byline: newByline };
    }
  });
};
```
  • Loading branch information
marcolink committed Jun 7, 2023
1 parent ce4b13a commit 05f1135
Show file tree
Hide file tree
Showing 7 changed files with 171 additions and 12 deletions.
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,10 +285,10 @@ The transform function is expected to return an object with the desired target f
- **`contentType : string`** _(required)_ – Content type ID
- **`from : array`** _(required)_ – Array of the source field IDs
- **`to : array`** _(required)_ – Array of the target field IDs
- **`transformEntryForLocale : function (fields, locale): object`** _(required)_ – Transformation function to be applied.
- **`transformEntryForLocale : function (fields, locale, {id}): object`** _(required)_ – Transformation function to be applied.
- `fields` is an object containing each of the `from` fields. Each field will contain their current localized values (i.e. `fields == {myField: {'en-US': 'my field value'}}`)
- `locale` one of the locales in the space being transformed

- `id` id of the current entry in scope
The return value must be an object with the same keys as specified in `to`. Their values will be written to the respective entry fields for the current locale (i.e. `{nameField: 'myNewValue'}`). If it returns `undefined`, this the values for this locale on the entry will be left untouched.
- **`shouldPublish : bool | 'preserve'`** _(optional)_ – Flag that specifies publishing of target entries, `preserve` will keep current states of the source entries (default `'preserve'`)

Expand All @@ -299,7 +299,7 @@ migration.transformEntries({
contentType: 'newsArticle',
from: ['author', 'authorCity'],
to: ['byline'],
transformEntryForLocale: function (fromFields, currentLocale) {
transformEntryForLocale: function (fromFields, currentLocale, { id }) {
if (currentLocale === 'de-DE') {
return
}
Expand Down Expand Up @@ -333,10 +333,11 @@ The derive function is expected to return an object with the desired target fiel

- `fields` is an object containing each of the `from` fields. Each field will contain their current localized values (i.e. `fields == {myField: {'en-US': 'my field value'}}`)

- **`deriveEntryForLocale : function (fields, locale): object`** _(required)_ – Function that generates the field values for the derived entry.
- **`deriveEntryForLocale : function (fields, locale, {id}): object`** _(required)_ – Function that generates the field values for the derived entry.

- `fields` is an object containing each of the `from` fields. Each field will contain their current localized values (i.e. `fields == {myField: {'en-US': 'my field value'}}`)
- `locale` one of the locales in the space being transformed
- `id` id of the current entry in scope

The return value must be an object with the same keys as specified in `derivedFields`. Their values will be written to the respective new entry fields for the current locale (i.e. `{nameField: 'myNewValue'}`)

Expand All @@ -355,7 +356,7 @@ migration.deriveLinkedEntries({
return fromFields.owner['en-US'].toLowerCase().replace(' ', '-')
},
shouldPublish: true,
deriveEntryForLocale: async (inputFields, locale) => {
deriveEntryForLocale: async (inputFields, locale, { id }) => {
if (locale !== 'en-US') {
return
}
Expand Down Expand Up @@ -383,10 +384,11 @@ For the given (source) content type, transforms all its entries according to the
- **`shouldPublish : bool | 'preserve'`** _(optional)_ – Flag that specifies publishing of target entries, `preserve` will keep current states of the source entries (default `false`)
- **`updateReferences : bool`** _(optional)_ – Flag that specifies if linking entries should be updated with target entries (default `false`). Note that this flag does not support Rich Text Fields references.
- **`removeOldEntries : bool`** _(optional)_ – Flag that specifies if source entries should be deleted (default `false`)
- **`transformEntryForLocale : function (fields, locale): object`** _(required)_ – Transformation function to be applied.
- **`transformEntryForLocale : function (fields, locale, {id}): object`** _(required)_ – Transformation function to be applied.

- `fields` is an object containing each of the `from` fields. Each field will contain their current localized values (i.e. `fields == {myField: {'en-US': 'my field value'}}`)
- `locale` one of the locales in the space being transformed
- `id` id of the current entry in scope

The return value must be an object with the same keys as specified in the `targetContentType`. Their values will be written to the respective entry fields for the current locale (i.e. `{nameField: 'myNewValue'}`). If it returns `undefined`, this the values for this locale on the entry will be left untouched.

Expand All @@ -406,7 +408,7 @@ migration.transformEntriesToType({
const value = fields.woofs['en-US'].toString()
return MurmurHash3(value).result().toString()
},
transformEntryForLocale: function (fromFields, currentLocale) {
transformEntryForLocale: function (fromFields, currentLocale, { id }) {
return {
woofs: `copy - ${fromFields.woofs[currentLocale]}`
}
Expand Down
10 changes: 8 additions & 2 deletions src/lib/action/entry-derive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ class EntryDeriveAction extends APIAction {
private fromFields: string[]
private referenceField: string
private derivedContentType: string
private deriveEntryForLocale: (inputFields: any, locale: string) => Promise<any>
private deriveEntryForLocale: (
inputFields: any,
locale: string,
{ id }: { id: string }
) => Promise<any>
private identityKey: (fromFields: any) => Promise<string>
private shouldPublish: boolean | 'preserve'

Expand Down Expand Up @@ -46,7 +50,9 @@ class EntryDeriveAction extends APIAction {
for (const locale of locales) {
let outputsForCurrentLocale
try {
outputsForCurrentLocale = await this.deriveEntryForLocale(inputs, locale)
outputsForCurrentLocale = await this.deriveEntryForLocale(inputs, locale, {
id: entry.id
})
} catch (err) {
await api.recordRuntimeError(err)
continue
Expand Down
10 changes: 8 additions & 2 deletions src/lib/action/entry-transform-to-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ class EntryTransformToTypeAction extends APIAction {
private fromFields?: string[]
private sourceContentTypeId: string
private targetContentTypeId: string
private transformEntryForLocale: (inputFields: any, locale: string) => Promise<any>
private transformEntryForLocale: (
inputFields: any,
locale: string,
{ id }: { id: string }
) => Promise<any>
private identityKey: (fromFields: any) => Promise<string>
private shouldPublish: boolean | 'preserve'
private removeOldEntries: boolean
Expand Down Expand Up @@ -47,7 +51,9 @@ class EntryTransformToTypeAction extends APIAction {
for (const locale of locales) {
let outputsForCurrentLocale
try {
outputsForCurrentLocale = await this.transformEntryForLocale(inputs, locale)
outputsForCurrentLocale = await this.transformEntryForLocale(inputs, locale, {
id: entry.id
})
} catch (err) {
await api.recordRuntimeError(err)
continue
Expand Down
4 changes: 3 additions & 1 deletion src/lib/action/entry-transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ class EntryTransformAction extends APIAction {
for (const locale of locales) {
let outputsForCurrentLocale
try {
outputsForCurrentLocale = await this.transformEntryForLocale(inputs, locale)
outputsForCurrentLocale = await this.transformEntryForLocale(inputs, locale, {
id: entry.id
})
} catch (err) {
await api.recordRuntimeError(err)
continue
Expand Down
61 changes: 61 additions & 0 deletions test/unit/lib/actions/entry-derive.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -438,4 +438,65 @@ describe('Entry Derive', function () {
batches[0].requests[0].data.sys.id
) // id of linked object is same as id of target object
})

it('provides entry id', async function () {
const ids = []
const action = new EntryDeriveAction('dog', {
derivedContentType: 'owner',
from: ['owner'],
toReferenceField: 'ownerRef',
derivedFields: ['firstName', 'lastName'],
identityKey: async (fromFields) => {
return fromFields.owner['en-US'].toLowerCase().replace(' ', '-')
},
shouldPublish: true,
deriveEntryForLocale: async (inputFields, locale, { id }) => {
ids.push(id)
const [firstName, lastName] = inputFields.owner[locale].split(' ')
return {
firstName,
lastName
}
}
})

const contentTypes = new Map()
contentTypes.set(
'dog',
new ContentType({
sys: {
id: 'dog'
},
fields: [
{
name: 'ownerRef',
id: 'ownerRef',
type: 'Symbol'
}
]
})
)

const entries = [
new Entry(
makeApiEntry({
id: '246',
contentTypeId: 'dog',
version: 1,
fields: {
owner: {
'en-US': 'john doe'
}
}
})
)
]

const api = new OfflineApi({ contentTypes, entries, locales: ['en-US'] })
api.startRecordingRequests(null)
await action.applyTo(api)
api.stopRecordingRequests()

expect(ids).to.eql(['246'])
})
})
37 changes: 37 additions & 0 deletions test/unit/lib/actions/entry-transform-to-type.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -523,4 +523,41 @@ describe('Transform Entry to Type Action', function () {
expect(passedObject).to.have.property('name')
expect(passedObject).to.have.property('other')
})

it('provides entry id', async function () {
const ids = []

const transformation: TransformEntryToType = {
sourceContentType: 'dog',
targetContentType: 'copycat',
from: ['name'],
identityKey: async (fields) => fields.name['en-US'].toString(),
transformEntryForLocale: async (fields, locale, { id }) => {
ids.push(id)
return { name: 'x' + fields['name'][locale] }
}
}

const action = new EntryTransformToTypeAction(transformation)
const entries = [
new Entry(
makeApiEntry({
id: '246',
contentTypeId: 'dog',
version: 1,
fields: {
name: {
'en-US': 'bob'
}
}
})
)
]
const api = new OfflineApi({ contentTypes: new Map(), entries, locales: ['en-US'] })
await api.startRecordingRequests(null)

await action.applyTo(api)
await api.stopRecordingRequests()
expect(ids).to.eql(['246'])
})
})
45 changes: 45 additions & 0 deletions test/unit/lib/actions/entry-transform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,49 @@ describe('Entry Action', function () {
return shouldPublishTest('preserve', 2, 1, true)
return shouldPublishTest('preserve', 3, 1, true)
})

it('provides entry id', async function () {
const ids = []

const transformation = (fields, locale, { id }) => {
ids.push(id)
return {
name: fields.name[locale] + '!'
}
}

const action = new EntryTransformAction('dog', ['name'], transformation)
const entries = [
new Entry(
makeApiEntry({
id: '246',
contentTypeId: 'dog',
version: 1,
fields: {
name: {
'en-US': 'Putin'
}
}
})
),
new Entry(
makeApiEntry({
id: '123',
contentTypeId: 'dog',
version: 1,
fields: {
name: {
'en-US': 'Trump'
}
}
})
)
]
const api = new OfflineApi({ contentTypes: new Map(), entries, locales: ['en-US'] })
await api.startRecordingRequests(null)

await action.applyTo(api)
await api.stopRecordingRequests()
expect(ids).to.eql(['246', '123'])
})
})

0 comments on commit 05f1135

Please sign in to comment.