Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(@aws-amplify/datastore): consecutive updates with timestamps #9298

Merged
merged 1 commit into from
Dec 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions packages/datastore/__tests__/outbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ describe('Outbox tests', () => {
_version: (updatedModel1 as any)._version + 1, // increment version like we would expect coming back from AppSync
_lastChangedAt: Date.now(),
_deleted: false,
createdAt: '2021-11-30T20:51:00.250Z',
updatedAt: '2021-11-30T20:52:00.250Z',
};

await Storage.runExclusive(async s => {
Expand All @@ -166,6 +168,8 @@ describe('Outbox tests', () => {
_version: inProgressData._version + 1, // increment version like we would expect coming back from AppSync
_lastChangedAt: Date.now(),
_deleted: false,
createdAt: '2021-11-30T20:51:00.250Z',
updatedAt: '2021-11-30T20:52:00.250Z',
};

await processMutationResponse(
Expand Down Expand Up @@ -320,9 +324,8 @@ async function instantiateOutbox(): Promise<void> {
Storage = <StorageType>DataStore.storage;
anyStorage = Storage;

const namespaceResolver = anyStorage.storage.namespaceResolver.bind(
anyStorage
);
const namespaceResolver =
anyStorage.storage.namespaceResolver.bind(anyStorage);

({ modelInstanceCreator } = anyStorage.storage);

Expand Down
75 changes: 57 additions & 18 deletions packages/datastore/src/sync/outbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
PersistentModelConstructor,
QueryOne,
} from '../types';
import { SYNC, valuesEqual } from '../util';
import { USER, SYNC, valuesEqual } from '../util';
import { TransformerMutationType } from './utils';

// TODO: Persist deleted ids
Expand All @@ -31,9 +31,8 @@ class MutationEventOutbox {
mutationEvent: MutationEvent
): Promise<void> {
storage.runExclusive(async s => {
const mutationEventModelDefinition = this.schema.namespaces[SYNC].models[
'MutationEvent'
];
const mutationEventModelDefinition =
this.schema.namespaces[SYNC].models['MutationEvent'];

const predicate = ModelPredicateCreator.createFromExisting<MutationEvent>(
mutationEventModelDefinition,
Expand Down Expand Up @@ -124,8 +123,8 @@ class MutationEventOutbox {
storage: StorageFacade,
model: T
): Promise<MutationEvent[]> {
const mutationEventModelDefinition = this.schema.namespaces[SYNC].models
.MutationEvent;
const mutationEventModelDefinition =
this.schema.namespaces[SYNC].models.MutationEvent;

const mutationEvents = await storage.query(
this.MutationEvent,
Expand Down Expand Up @@ -161,7 +160,9 @@ class MutationEventOutbox {
return;
}

const { _version, _lastChangedAt, _deleted, ...incomingData } = record;
const { _version, _lastChangedAt, _deleted, ..._incomingData } = record;
const incomingData = this.removeTimestampFields(head.model, _incomingData);

const data = JSON.parse(head.data);

if (!data) {
Expand All @@ -172,18 +173,18 @@ class MutationEventOutbox {
_version: __version,
_lastChangedAt: __lastChangedAt,
_deleted: __deleted,
...outgoingData
..._outgoingData
} = data;
const outgoingData = this.removeTimestampFields(head.model, _outgoingData);

// Don't sync the version when the data in the response does not match the data
// in the request, i.e., when there's a handled conflict
if (!valuesEqual(incomingData, outgoingData, true)) {
return;
}

const mutationEventModelDefinition = this.schema.namespaces[SYNC].models[
'MutationEvent'
];
const mutationEventModelDefinition =
this.schema.namespaces[SYNC].models['MutationEvent'];

const predicate = ModelPredicateCreator.createFromExisting<MutationEvent>(
mutationEventModelDefinition,
Expand Down Expand Up @@ -222,13 +223,8 @@ class MutationEventOutbox {
previous: MutationEvent,
current: MutationEvent
): MutationEvent {
const {
_version,
id,
_lastChangedAt,
_deleted,
...previousData
} = JSON.parse(previous.data);
const { _version, id, _lastChangedAt, _deleted, ...previousData } =
JSON.parse(previous.data);

const {
id: __id,
Expand All @@ -252,6 +248,49 @@ class MutationEventOutbox {
data,
});
}

/*
if a model is using custom timestamp fields
the custom field names will be stored in the model attributes

e.g.
"attributes": [
{
"type": "model",
"properties": {
"timestamps": {
"createdAt": "createdOn",
"updatedAt": "updatedOn"
}
}
}
]
*/
private removeTimestampFields(
model: string,
record: PersistentModel
): PersistentModel {
const CREATED_AT_DEFAULT_KEY = 'createdAt';
const UPDATED_AT_DEFAULT_KEY = 'updatedAt';

let createdTimestampKey = CREATED_AT_DEFAULT_KEY;
let updatedTimestampKey = UPDATED_AT_DEFAULT_KEY;

const modelAttributes = this.schema.namespaces[USER].models[
iartemiev marked this conversation as resolved.
Show resolved Hide resolved
model
].attributes?.find(attr => attr.type === 'model');
const timestampFieldsMap = modelAttributes?.properties?.timestamps;

if (timestampFieldsMap) {
createdTimestampKey = timestampFieldsMap[CREATED_AT_DEFAULT_KEY];
updatedTimestampKey = timestampFieldsMap[UPDATED_AT_DEFAULT_KEY];
}

delete (record as Record<string, any>)[createdTimestampKey];
delete (record as Record<string, any>)[updatedTimestampKey];

return record;
}
}

export { MutationEventOutbox };