@strapi/data-transfer
Version:
Data transfer capabilities for Strapi
63 lines (60 loc) • 2.75 kB
JavaScript
import { Writable } from 'stream';
import { last } from 'lodash/fp';
import { ProviderTransferError } from '../../../../../errors/providers.mjs';
import 'crypto';
import { diff } from '../../../../../utils/json.mjs';
import 'events';
import { createEntityQuery } from '../../../../queries/entity.mjs';
import { resolveComponentUID } from '../../../../../utils/components.mjs';
const createEntitiesWriteStream = (options)=>{
const { strapi, updateMappingTable, transaction } = options;
const query = createEntityQuery(strapi);
return new Writable({
objectMode: true,
async write (entity, _encoding, callback) {
await transaction?.attach(async ()=>{
const { type, id, data } = entity;
const { create, getDeepPopulateComponentLikeQuery } = query(type);
const contentType = strapi.getModel(type);
try {
const created = await create({
data,
populate: getDeepPopulateComponentLikeQuery(contentType, {
select: 'id'
}),
select: 'id'
});
// Compute differences between original & new entities
const diffs = diff(data, created);
updateMappingTable(type, id, created.id);
// For each difference found on an ID attribute,
// update the mapping the table accordingly
diffs.forEach((diff)=>{
if (diff.kind === 'modified' && last(diff.path) === 'id' && 'kind' in contentType) {
const target = resolveComponentUID({
paths: diff.path,
data,
contentType,
strapi
});
// If no type is found for the given path, then ignore the diff
if (!target) {
return;
}
const [oldID, newID] = diff.values;
updateMappingTable(target, oldID, newID);
}
});
} catch (e) {
if (e instanceof Error) {
return callback(e);
}
return callback(new ProviderTransferError(`Failed to create "${type}" (${id})`));
}
return callback(null);
});
}
});
};
export { createEntitiesWriteStream };
//# sourceMappingURL=entities.mjs.map