@aws-amplify/datastore
Version:
AppSyncLocal support for aws-amplify
45 lines (42 loc) • 1.63 kB
JavaScript
import { OpType } from '../types.mjs';
import { getIdentifierValue } from './utils.mjs';
// https://github.com/aws-amplify/amplify-js/blob/datastore-docs/packages/datastore/docs/sync-engine.md#merger
class ModelMerger {
constructor(outbox, ownSymbol) {
this.outbox = outbox;
this.ownSymbol = ownSymbol;
}
/**
*
* @param storage Storage adapter that contains the data.
* @param model The model from an outbox mutation.
* @returns The type of operation (INSERT/UPDATE/DELETE)
*/
async merge(storage, model, modelDefinition) {
let result;
const mutationsForModel = await this.outbox.getForModel(storage, model, modelDefinition);
const isDelete = model._deleted;
if (mutationsForModel.length === 0) {
if (isDelete) {
result = OpType.DELETE;
await storage.delete(model, undefined, this.ownSymbol);
}
else {
[[, result]] = await storage.save(model, undefined, this.ownSymbol);
}
}
return result;
}
async mergePage(storage, modelConstructor, items, modelDefinition) {
const itemsMap = new Map();
for (const item of items) {
// merge items by model id. Latest record for a given id remains.
const modelId = getIdentifierValue(modelDefinition, item);
itemsMap.set(modelId, item);
}
const page = [...itemsMap.values()];
return storage.batchSave(modelConstructor, page, this.ownSymbol);
}
}
export { ModelMerger };
//# sourceMappingURL=merger.mjs.map