Skip to content

Commit

Permalink
chore(datastore): manual fix of linter reported issues (issues that r…
Browse files Browse the repository at this point in the history
…equries refactoring are suppresed by eslint ignore comment for stability)
  • Loading branch information
HuiSF committed Apr 30, 2024
1 parent 2213564 commit 502b457
Show file tree
Hide file tree
Showing 26 changed files with 473 additions and 438 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ function getAuthRules({
export const multiAuthStrategy: (
amplifyContext: AmplifyContext,
) => AuthModeStrategy =
(amplifyContext: AmplifyContext) =>
() =>
async ({ schema, modelName }) => {
let currentUser;
try {
Expand Down
76 changes: 39 additions & 37 deletions packages/datastore/src/datastore/datastore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ const buildSeedPredicate = <T extends PersistentModel>(
};

// exporting syncClasses for testing outbox.test.ts
// TODO(eslint): refactor not to export non-constant
// eslint-disable-next-line import/no-mutable-exports
export let syncClasses: TypeConstructorMap;
let userClasses: TypeConstructorMap;
let dataStoreClasses: TypeConstructorMap;
Expand Down Expand Up @@ -490,7 +492,7 @@ const checkSchemaCodegenVersion = (codegenVersion: string) => {
let isValid = false;
try {
const versionParts = codegenVersion.split('.');
const [major, minor, patch, patchrevision] = versionParts;
const [major, minor] = versionParts;
isValid = Number(major) === majorVersion && Number(minor) >= minorVersion;
} catch (err) {
console.log(`Error parsing codegen version: ${codegenVersion}\n${err}`);
Expand Down Expand Up @@ -548,12 +550,12 @@ export declare type ModelInstanceCreator = typeof modelInstanceCreator;
const instancesMetadata = new WeakSet<ModelInit<any, any>>();

function modelInstanceCreator<T extends PersistentModel>(
modelConstructor: PersistentModelConstructor<T>,
ModelConstructor: PersistentModelConstructor<T>,
init: Partial<T>,
): T {
instancesMetadata.add(init);

return new modelConstructor(init as ModelInit<T, PersistentModelMetaData<T>>);
return new ModelConstructor(init as ModelInit<T, PersistentModelMetaData<T>>);
}

const validateModelFields =
Expand Down Expand Up @@ -652,6 +654,7 @@ const validateModelFields =
}
}
} else if (!isRequired && v === undefined) {
// no-op for this branch but still to filter this branch out
} else if (typeof v !== jsType && v !== null) {
throw new Error(
`Field ${name} should be of type ${jsType}, ${typeof v} received. ${v}`,
Expand Down Expand Up @@ -905,7 +908,7 @@ const createModelClass = <T extends PersistentModel>(
{ source },
);
}
(draft as Object)[key] = source[key];
(draft as object)[key] = source[key];
});

const modelValidator = validateModelFields(modelDefinition);
Expand Down Expand Up @@ -994,7 +997,7 @@ const createModelClass = <T extends PersistentModel>(
// Avoid validation error when processing AppSync response with nested
// selection set. Nested entitites lack version field and can not be validated
// TODO: explore a more reliable method to solve this
if (model.hasOwnProperty('_version')) {
if (Object.prototype.hasOwnProperty.call(model, '_version')) {
const modelConstructor = Object.getPrototypeOf(model || {})
.constructor as PersistentModelConstructor<T>;

Expand Down Expand Up @@ -1040,7 +1043,7 @@ const createModelClass = <T extends PersistentModel>(
// if the memos already has a result for this field, we'll use it.
// there is no "cache" invalidation of any kind; memos are permanent to
// keep an immutable perception of the instance.
if (!instanceMemos.hasOwnProperty(field)) {
if (!Object.prototype.hasOwnProperty.call(instanceMemos, field)) {
// before we populate the memo, we need to know where to look for relatives.
// today, this only supports DataStore. Models aren't managed elsewhere in Amplify.
if (getAttachment(this) === ModelAttachment.DataStore) {
Expand All @@ -1052,12 +1055,14 @@ const createModelClass = <T extends PersistentModel>(
relationship.remoteModelConstructor as PersistentModelConstructor<T>,
base =>
base.and(q => {
return relationship.remoteJoinFields.map((field, index) => {
// TODO: anything we can use instead of `any` here?
return (q[field] as T[typeof field]).eq(
this[relationship.localJoinFields[index]],
);
});
return relationship.remoteJoinFields.map(
(joinField, index) => {
// TODO: anything we can use instead of `any` here?
return (q[joinField] as T[typeof joinField]).eq(
this[relationship.localJoinFields[index]],
);
},
);
}),
);

Expand Down Expand Up @@ -1301,14 +1306,14 @@ async function checkSchemaVersion(
storage: Storage,
version: string,
): Promise<void> {
const Setting =
const SettingCtor =
dataStoreClasses.Setting as PersistentModelConstructor<Setting>;

const modelDefinition = schema.namespaces[DATASTORE].models.Setting;

await storage.runExclusive(async s => {
const [schemaVersionSetting] = await s.query(
Setting,
SettingCtor,
ModelPredicateCreator.createFromAST(modelDefinition, {
and: { key: { eq: SETTING_SCHEMA_VERSION } },
}),
Expand All @@ -1326,7 +1331,7 @@ async function checkSchemaVersion(
}
} else {
await s.save(
modelInstanceCreator(Setting, {
modelInstanceCreator(SettingCtor, {
key: SETTING_SCHEMA_VERSION,
value: JSON.stringify(version),
}),
Expand Down Expand Up @@ -1404,8 +1409,8 @@ class DataStore {
private errorHandler!: (error: SyncError<PersistentModel>) => void;
private fullSyncInterval!: number;
private initialized?: Promise<void>;
private initReject!: Function;
private initResolve!: Function;
private initReject!: () => void;
private initResolve!: () => void;
private maxRecordsToSync!: number;
private storage?: Storage;
private sync?: SyncEngine;
Expand Down Expand Up @@ -1513,9 +1518,9 @@ class DataStore {
this.state = DataStoreState.Starting;
if (this.initialized === undefined) {
logger.debug('Starting DataStore');
this.initialized = new Promise((res, rej) => {
this.initResolve = res;
this.initReject = rej;
this.initialized = new Promise((resolve, reject) => {
this.initResolve = resolve;
this.initReject = reject;
});
} else {
await this.initialized;
Expand Down Expand Up @@ -1831,12 +1836,7 @@ class DataStore {
: undefined;

const [savedModel] = await this.storage.runExclusive(async s => {
const saved = await s.save(
model,
producedCondition,
undefined,
patchesTuple,
);
await s.save(model, producedCondition, undefined, patchesTuple);

return s.query<T>(
modelConstructor,
Expand Down Expand Up @@ -2074,18 +2074,18 @@ class DataStore {

if (modelOrConstructor && modelConstructor === undefined) {
const model = modelOrConstructor as T;
const modelConstructor =
model && (Object.getPrototypeOf(model) as Object).constructor;
const resolvedModelConstructor =
model && (Object.getPrototypeOf(model) as object).constructor;

if (isValidModelConstructor<T>(modelConstructor)) {
if (isValidModelConstructor<T>(resolvedModelConstructor)) {
if (identifierOrCriteria) {
logger.warn('idOrCriteria is ignored when using a model instance', {
model,
identifierOrCriteria,
});
}

return this.observe(modelConstructor, model.id);
return this.observe(resolvedModelConstructor, model.id);
} else {
const msg =
'The model is not an instance of a PersistentModelConstructor';
Expand Down Expand Up @@ -2282,10 +2282,11 @@ class DataStore {
// to have visibility into items that move from in-set to out-of-set.
// We need to explicitly remove those items from the existing snapshot.
handle = this.observe(model).subscribe(
({ element, model, opType }) =>
({ element, model: observedModel, opType }) =>
this.runningProcesses.isOpen &&
this.runningProcesses.add(async () => {
const itemModelDefinition = getModelDefinition(model)!;
const itemModelDefinition =
getModelDefinition(observedModel)!;
const idOrPk = getIdentifierValue(
itemModelDefinition,
element,
Expand Down Expand Up @@ -2320,7 +2321,7 @@ class DataStore {
}

const isSynced =
this.sync?.getModelSyncedStatus(model) ?? false;
this.sync?.getModelSyncedStatus(observedModel) ?? false;

const limit =
itemsChanged.size - deletedItemIds.length >=
Expand Down Expand Up @@ -2409,8 +2410,11 @@ class DataStore {
* @param itemsToSort A array of model type.
*/
const sortItems = (itemsToSort: T[]): void => {
const modelDefinition = getModelDefinition(model);
const pagination = this.processPagination(modelDefinition!, options);
const sortingModelDefinition = getModelDefinition(model);
const pagination = this.processPagination(
sortingModelDefinition!,
options,
);

const sortPredicates = ModelSortPredicateCreator.getPredicates(
pagination!.sort!,
Expand Down Expand Up @@ -2456,8 +2460,6 @@ class DataStore {
const {
DataStore: configDataStore,
authModeStrategyType: configAuthModeStrategyType,
conflictHandler: configConflictHandler,
errorHandler: configErrorHandler,
maxRecordsToSync: configMaxRecordsToSync,
syncPageSize: configSyncPageSize,
fullSyncInterval: configFullSyncInterval,
Expand Down
2 changes: 2 additions & 0 deletions packages/datastore/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export {
DataStoreClass,
initSchema,
ModelInstanceCreator,
// eslint-disable-next-line import/export
AsyncCollection,
AsyncItem,
} from './datastore/datastore';
Expand All @@ -34,4 +35,5 @@ export const utils = {
isModelConstructor,
};

// eslint-disable-next-line import/export
export * from './types';
3 changes: 2 additions & 1 deletion packages/datastore/src/predicates/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ export const PredicateAll = Symbol('A predicate that matches all records');

export class Predicates {
public static get ALL(): typeof PredicateAll {
const predicate = c => c as ProducerModelPredicate<any>;
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const predicate = <ProducerModelPredicate<any>>(c => c);

predicatesAllSet.add(predicate);

Expand Down
23 changes: 12 additions & 11 deletions packages/datastore/src/predicates/next.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ export class FieldCondition {
* @param extract Not used. Present only to fulfill the `UntypedCondition` interface.
* @returns A new, identitical `FieldCondition`.
*/
copy(extract?: GroupCondition): [FieldCondition, GroupCondition | undefined] {
copy(): [FieldCondition, GroupCondition | undefined] {
return [
new FieldCondition(this.field, this.operator, [...this.operands]),
undefined,
Expand Down Expand Up @@ -193,7 +193,8 @@ export class FieldCondition {
* @param storage N/A. If ever implemented, the storage adapter to query.
* @returns N/A. If ever implemented, return items from `storage` that match.
*/
async fetch(storage: StorageAdapter): Promise<Record<string, any>[]> {
async fetch(): Promise<Record<string, any>[]> {
// eslint-disable-next-line prefer-promise-reject-errors
return Promise.reject('No implementation needed [yet].');
}

Expand Down Expand Up @@ -796,16 +797,16 @@ export function recursivePredicateFor<T extends PersistentModel>(
registerPredicateInternals(baseCondition, link);

const copyLink = () => {
const [query, newTail] = baseCondition.copy(tailCondition);
const [copiedQuery, newTail] = baseCondition.copy(tailCondition);
const newLink = recursivePredicateFor(
ModelType,
allowRecursion,
undefined,
query,
copiedQuery,
newTail,
);

return { query, newTail, newLink };
return { query: copiedQuery, newTail, newLink };
};

// Adds .or() and .and() methods to the link.
Expand All @@ -814,7 +815,7 @@ export function recursivePredicateFor<T extends PersistentModel>(
link[op] = (builder: RecursiveModelPredicateAggregateExtender<T>) => {
// or() and and() will return a copy of the original link
// to head off mutability concerns.
const { query, newTail } = copyLink();
const { query: copiedLinkQuery, newTail } = copyLink();

const childConditions = builder(
recursivePredicateFor(ModelType, allowRecursion),
Expand All @@ -838,7 +839,7 @@ export function recursivePredicateFor<T extends PersistentModel>(
);

// FinalPredicate
return registerPredicateInternals(query);
return registerPredicateInternals(copiedLinkQuery);
};
});

Expand All @@ -848,7 +849,7 @@ export function recursivePredicateFor<T extends PersistentModel>(
): PredicateInternalsKey => {
// not() will return a copy of the original link
// to head off mutability concerns.
const { query, newTail } = copyLink();
const { query: copiedLinkQuery, newTail } = copyLink();

// unlike and() and or(), the customer will supply a "singular" child predicate.
// the difference being: not() does not accept an array of predicate-like objects.
Expand All @@ -862,7 +863,7 @@ export function recursivePredicateFor<T extends PersistentModel>(
// A `FinalModelPredicate`.
// Return a thing that can no longer be extended, but instead used to `async filter(items)`
// or query storage: `.__query.fetch(storage)`.
return registerPredicateInternals(query);
return registerPredicateInternals(copiedLinkQuery);
};

// For each field on the model schema, we want to add a getter
Expand Down Expand Up @@ -890,7 +891,7 @@ export function recursivePredicateFor<T extends PersistentModel>(
[operator]: (...operands: any[]) => {
// build off a fresh copy of the existing `link`, just in case
// the same link is being used elsewhere by the customer.
const { query, newTail } = copyLink();
const { query: copiedLinkQuery, newTail } = copyLink();

// normalize operands. if any of the values are `undefiend`, use
// `null` instead, because that's what will be stored cross-platform.
Expand All @@ -907,7 +908,7 @@ export function recursivePredicateFor<T extends PersistentModel>(
// A `FinalModelPredicate`.
// Return a thing that can no longer be extended, but instead used to `async filter(items)`
// or query storage: `.__query.fetch(storage)`.
return registerPredicateInternals(query);
return registerPredicateInternals(copiedLinkQuery);
},
};
}, {});
Expand Down
Loading

0 comments on commit 502b457

Please sign in to comment.