@aws-amplify/data-schema 1.3.7 → 1.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/CombineSchema.js +5 -1
- package/dist/cjs/CombineSchema.js.map +1 -1
- package/dist/cjs/ModelSchema.js +8 -2
- package/dist/cjs/ModelSchema.js.map +1 -1
- package/dist/cjs/SchemaProcessor.js +269 -4
- package/dist/cjs/SchemaProcessor.js.map +1 -1
- package/dist/cjs/runtime/internals/server/generateModelsProperty.js +1 -1
- package/dist/cjs/runtime/internals/server/generateModelsProperty.js.map +1 -1
- package/dist/esm/CombineSchema.mjs +5 -1
- package/dist/esm/CombineSchema.mjs.map +1 -1
- package/dist/esm/ModelSchema.d.ts +6 -0
- package/dist/esm/ModelSchema.mjs +8 -2
- package/dist/esm/ModelSchema.mjs.map +1 -1
- package/dist/esm/SchemaProcessor.mjs +270 -5
- package/dist/esm/SchemaProcessor.mjs.map +1 -1
- package/dist/esm/runtime/client/index.d.ts +20 -10
- package/dist/esm/runtime/internals/server/generateModelsProperty.mjs +1 -1
- package/dist/esm/runtime/internals/server/generateModelsProperty.mjs.map +1 -1
- package/dist/meta/cjs.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/src/CombineSchema.ts +5 -1
- package/src/ModelSchema.ts +14 -2
- package/src/SchemaProcessor.ts +416 -5
- package/src/runtime/client/index.ts +40 -22
- package/src/runtime/internals/server/generateModelsProperty.ts +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ModelSchema.mjs","sources":["../../src/ModelSchema.ts"],"sourcesContent":["import { isSchemaModelType, } from './ModelType';\nimport { processSchema } from './SchemaProcessor';\nimport { allow } from './Authorization';\nimport { brand, getBrand } from './util';\nexport const rdsSchemaBrandName = 'RDSSchema';\nexport const rdsSchemaBrand = brand(rdsSchemaBrandName);\nexport const ddbSchemaBrandName = 'DDBSchema';\nconst ddbSchemaBrand = brand(ddbSchemaBrandName);\n/**\n * Filter the schema types down to only include the ModelTypes as SchemaModelType\n *\n * @param schemaContents The object containing all SchemaContent for this schema\n * @returns Only the schemaContents that are ModelTypes, coerced to the SchemaModelType surface\n */\nconst filterSchemaModelTypes = (schemaContents) => {\n const modelTypes = {};\n if (schemaContents) {\n Object.entries(schemaContents).forEach(([key, content]) => {\n if (isSchemaModelType(content)) {\n modelTypes[key] = content;\n }\n });\n }\n return modelTypes;\n};\n/**\n * Model Schema type guard\n * @param schema - api-next ModelSchema or string\n * @returns true if the given value is a ModelSchema\n */\nexport const isModelSchema = (schema) => {\n return typeof schema === 'object' && schema.data !== undefined;\n};\n/**\n * Ensures that only supported entities are being added to the SQL schema through `addToSchema`\n * Models are not supported for brownfield SQL\n *\n * @param types - purposely widened to ModelSchemaContents, because we need to validate at runtime that a model is not being passed in here\n */\nfunction validateAddToSchema(types) {\n for (const [name, type] of Object.entries(types)) {\n if (getBrand(type) === 'modelType') {\n throw new Error(`Invalid value specified for ${name} in addToSchema(). Models cannot be manually added to a SQL schema.`);\n }\n }\n}\nfunction _rdsSchema(types, config) {\n const data = {\n types,\n authorization: [],\n configuration: config,\n };\n const models = filterSchemaModelTypes(data.types);\n return {\n data,\n models,\n transform() {\n const internalSchema = { data };\n return processSchema({ schema: internalSchema });\n },\n authorization(callback) {\n const rules = callback(allow);\n this.data.authorization = Array.isArray(rules) ? rules : [rules];\n const { authorization: _, ...rest } = this;\n return rest;\n },\n addToSchema(types) {\n validateAddToSchema(types);\n this.data.types = { ...this.data.types, ...types };\n const { addToSchema: _, ...rest } = this;\n return rest;\n },\n addQueries(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addQueries: _, ...rest } = this;\n return rest;\n },\n addMutations(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addMutations: _, ...rest } = this;\n return rest;\n },\n addSubscriptions(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addSubscriptions: _, ...rest } = this;\n return rest;\n },\n setAuthorization(callback) {\n callback(models, this);\n const { setAuthorization: _, ...rest } = this;\n return rest;\n },\n setRelationships(callback) {\n const { setRelationships: _, ...rest } = this;\n // The relationships are added via `models.<Model>.relationships`\n // modifiers that's being called within the callback. They are modifying\n // by references on each model, so there is not anything else to be done\n // here.\n callback(models);\n return rest;\n },\n renameModels(callback) {\n const { renameModels: _, ...rest } = this;\n // returns an array of tuples [curName, newName]\n const changeLog = callback();\n changeLog.forEach(([curName, newName]) => {\n const currentType = data.types[curName];\n if (currentType === undefined) {\n throw new Error(`Invalid renameModels call. ${curName} is not defined in the schema`);\n }\n if (typeof newName !== 'string' || newName.length < 1) {\n throw new Error(`Invalid renameModels call. New name must be a non-empty string. Received: \"${newName}\"`);\n }\n models[newName] = currentType;\n data.types[newName] = currentType;\n models[newName].data.originalName = curName;\n delete models[curName];\n delete data.types[curName];\n });\n return rest;\n },\n ...rdsSchemaBrand,\n };\n}\nfunction _ddbSchema(types, config) {\n const data = {\n types,\n authorization: [],\n configuration: config,\n };\n return {\n data,\n transform() {\n const internalSchema = { data };\n return processSchema({ schema: internalSchema });\n },\n authorization(callback) {\n const rules = callback(allow);\n this.data.authorization = Array.isArray(rules) ? rules : [rules];\n const { authorization: _, ...rest } = this;\n return rest;\n },\n models: filterSchemaModelTypes(data.types),\n ...ddbSchemaBrand,\n };\n}\nfunction bindConfigToSchema(config) {\n return (types) => {\n return (config.database.engine === 'dynamodb'\n ? _ddbSchema(types, config)\n : _rdsSchema(types, config));\n };\n}\n/**\n * The API and data model definition for Amplify Data. Pass in `{ <NAME>: a.model(...) }` to create a database table\n * and exposes CRUDL operations via an API.\n * @param types The API and data model definition\n * @returns An API and data model definition to be deployed with Amplify (Gen 2) experience (`processSchema(...)`)\n * or with the Amplify Data CDK construct (`@aws-amplify/data-construct`)\n */\nexport const schema = bindConfigToSchema({ database: { engine: 'dynamodb' } });\n/**\n * Configure wraps schema definition with non-default config to allow usecases other than\n * the default DynamoDB use-case.\n *\n * @param config The SchemaConfig augments the schema with content like the database type\n * @returns\n */\nexport function configure(config) {\n return {\n schema: bindConfigToSchema(config),\n };\n}\nexport function isCustomPathData(obj) {\n return ('stack' in obj &&\n (typeof obj.stack === 'undefined' || typeof obj.stack === 'string') &&\n 'entry' in obj &&\n typeof obj.entry === 'string');\n}\n"],"names":[],"mappings":";;;;;AAIY,MAAC,kBAAkB,GAAG,YAAY;AAClC,MAAC,cAAc,GAAG,KAAK,CAAC,kBAAkB,EAAE;AAC5C,MAAC,kBAAkB,GAAG,YAAY;AAC9C,MAAM,cAAc,GAAG,KAAK,CAAC,kBAAkB,CAAC,CAAC;AACjD;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,sBAAsB,GAAG,CAAC,cAAc,KAAK;AACnD,IAAI,MAAM,UAAU,GAAG,EAAE,CAAC;AAC1B,IAAI,IAAI,cAAc,EAAE;AACxB,QAAQ,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,OAAO,CAAC,KAAK;AACnE,YAAY,IAAI,iBAAiB,CAAC,OAAO,CAAC,EAAE;AAC5C,gBAAgB,UAAU,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;AAC1C,aAAa;AACb,SAAS,CAAC,CAAC;AACX,KAAK;AACL,IAAI,OAAO,UAAU,CAAC;AACtB,CAAC,CAAC;AACF;AACA;AACA;AACA;AACA;AACY,MAAC,aAAa,GAAG,CAAC,MAAM,KAAK;AACzC,IAAI,OAAO,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,CAAC;AACnE,EAAE;AACF;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,mBAAmB,CAAC,KAAK,EAAE;AACpC,IAAI,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACtD,QAAQ,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,WAAW,EAAE;AAC5C,YAAY,MAAM,IAAI,KAAK,CA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AAE,EAAE,EAAE;AAC/E;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,SAAS,CAAC,MAAM,EAAE;AAClC,IAAI,OAAO;AACX,QAAQ,MAAM,EAAE,kBAAkB,CAAC,MAAM,CAAC;AAC1C,KAAK,CAAC;AACN,CAAC;AACM,SAAS,gBAAgB,CAAC,GAAG,EAAE;AACtC,IAAI,QAAQ,OAAO,IAAI,GAAG;AAC1B,SAAS,OAAO,GAAG,CAAC,KAAK,KAAK,WAAW,IAAI,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,CAAC;AAC3E,QAAQ,OAAO,IAAI,GAAG;AACtB,QAAQ,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,EAAE;AACvC;;;;"}
|
|
1
|
+
{"version":3,"file":"ModelSchema.mjs","sources":["../../src/ModelSchema.ts"],"sourcesContent":["import { isSchemaModelType, } from './ModelType';\nimport { processSchema } from './SchemaProcessor';\nimport { allow } from './Authorization';\nimport { brand, getBrand } from './util';\nexport const rdsSchemaBrandName = 'RDSSchema';\nexport const rdsSchemaBrand = brand(rdsSchemaBrandName);\nexport const ddbSchemaBrandName = 'DDBSchema';\nconst ddbSchemaBrand = brand(ddbSchemaBrandName);\n/**\n * Filter the schema types down to only include the ModelTypes as SchemaModelType\n *\n * @param schemaContents The object containing all SchemaContent for this schema\n * @returns Only the schemaContents that are ModelTypes, coerced to the SchemaModelType surface\n */\nconst filterSchemaModelTypes = (schemaContents) => {\n const modelTypes = {};\n if (schemaContents) {\n Object.entries(schemaContents).forEach(([key, content]) => {\n if (isSchemaModelType(content)) {\n modelTypes[key] = content;\n }\n });\n }\n return modelTypes;\n};\n/**\n * Model Schema type guard\n * @param schema - api-next ModelSchema or string\n * @returns true if the given value is a ModelSchema\n */\nexport const isModelSchema = (schema) => {\n return typeof schema === 'object' && schema.data !== undefined;\n};\n/**\n * Ensures that only supported entities are being added to the SQL schema through `addToSchema`\n * Models are not supported for brownfield SQL\n *\n * @param types - purposely widened to ModelSchemaContents, because we need to validate at runtime that a model is not being passed in here\n */\nfunction validateAddToSchema(types) {\n for (const [name, type] of Object.entries(types)) {\n if (getBrand(type) === 'modelType') {\n throw new Error(`Invalid value specified for ${name} in addToSchema(). Models cannot be manually added to a SQL schema.`);\n }\n }\n}\nfunction _rdsSchema(types, config) {\n const data = {\n types,\n authorization: [],\n configuration: config,\n };\n const models = filterSchemaModelTypes(data.types);\n return {\n data,\n models,\n transform() {\n const internalSchema = {\n data,\n context: this.context,\n };\n return processSchema({ schema: internalSchema });\n },\n authorization(callback) {\n const rules = callback(allow);\n this.data.authorization = Array.isArray(rules) ? rules : [rules];\n const { authorization: _, ...rest } = this;\n return rest;\n },\n addToSchema(types) {\n validateAddToSchema(types);\n this.data.types = { ...this.data.types, ...types };\n const { addToSchema: _, ...rest } = this;\n return rest;\n },\n addQueries(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addQueries: _, ...rest } = this;\n return rest;\n },\n addMutations(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addMutations: _, ...rest } = this;\n return rest;\n },\n addSubscriptions(types) {\n this.data.types = { ...this.data.types, ...types };\n const { addSubscriptions: _, ...rest } = this;\n return rest;\n },\n setAuthorization(callback) {\n callback(models, this);\n const { setAuthorization: _, ...rest } = this;\n return rest;\n },\n setRelationships(callback) {\n const { setRelationships: _, ...rest } = this;\n // The relationships are added via `models.<Model>.relationships`\n // modifiers that's being called within the callback. They are modifying\n // by references on each model, so there is not anything else to be done\n // here.\n callback(models);\n return rest;\n },\n renameModels(callback) {\n const { renameModels: _, ...rest } = this;\n // returns an array of tuples [curName, newName]\n const changeLog = callback();\n changeLog.forEach(([curName, newName]) => {\n const currentType = data.types[curName];\n if (currentType === undefined) {\n throw new Error(`Invalid renameModels call. ${curName} is not defined in the schema`);\n }\n if (typeof newName !== 'string' || newName.length < 1) {\n throw new Error(`Invalid renameModels call. New name must be a non-empty string. Received: \"${newName}\"`);\n }\n models[newName] = currentType;\n data.types[newName] = currentType;\n models[newName].data.originalName = curName;\n delete models[curName];\n delete data.types[curName];\n });\n return rest;\n },\n ...rdsSchemaBrand,\n };\n}\nfunction _ddbSchema(types, config) {\n const data = {\n types,\n authorization: [],\n configuration: config,\n };\n return {\n data,\n transform() {\n const internalSchema = {\n data,\n context: this.context,\n };\n return processSchema({ schema: internalSchema });\n },\n authorization(callback) {\n const rules = callback(allow);\n this.data.authorization = Array.isArray(rules) ? rules : [rules];\n const { authorization: _, ...rest } = this;\n return rest;\n },\n models: filterSchemaModelTypes(data.types),\n ...ddbSchemaBrand,\n };\n}\nfunction bindConfigToSchema(config) {\n return (types) => {\n return (config.database.engine === 'dynamodb'\n ? _ddbSchema(types, config)\n : _rdsSchema(types, config));\n };\n}\n/**\n * The API and data model definition for Amplify Data. Pass in `{ <NAME>: a.model(...) }` to create a database table\n * and exposes CRUDL operations via an API.\n * @param types The API and data model definition\n * @returns An API and data model definition to be deployed with Amplify (Gen 2) experience (`processSchema(...)`)\n * or with the Amplify Data CDK construct (`@aws-amplify/data-construct`)\n */\nexport const schema = bindConfigToSchema({ database: { engine: 'dynamodb' } });\n/**\n * Configure wraps schema definition with non-default config to allow usecases other than\n * the default DynamoDB use-case.\n *\n * @param config The SchemaConfig augments the schema with content like the database type\n * @returns\n */\nexport function configure(config) {\n return {\n schema: bindConfigToSchema(config),\n };\n}\nexport function isCustomPathData(obj) {\n return ('stack' in obj &&\n (typeof obj.stack === 'undefined' || typeof obj.stack === 'string') &&\n 'entry' in obj &&\n typeof obj.entry === 'string');\n}\n"],"names":[],"mappings":";;;;;AAIY,MAAC,kBAAkB,GAAG,YAAY;AAClC,MAAC,cAAc,GAAG,KAAK,CAAC,kBAAkB,EAAE;AAC5C,MAAC,kBAAkB,GAAG,YAAY;AAC9C,MAAM,cAAc,GAAG,KAAK,CAAC,kBAAkB,CAAC,CAAC;AACjD;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,sBAAsB,GAAG,CAAC,cAAc,KAAK;AACnD,IAAI,MAAM,UAAU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AAC,KAAK,KAAK,QAAQ,CAAC;AAC3E,QAAQ,OAAO,IAAI,GAAG;AACtB,QAAQ,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,EAAE;AACvC;;;;"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ModelFieldType, string } from './ModelField.mjs';
|
|
2
|
+
import { ModelRelationshipTypes } from './ModelRelationalField.mjs';
|
|
2
3
|
import { accessData, accessSchemaData } from './Authorization.mjs';
|
|
3
4
|
import { CustomOperationNames } from './CustomOperation.mjs';
|
|
4
5
|
import { getBrand } from './util/Brand.mjs';
|
|
@@ -694,14 +695,36 @@ const extractFunctionSchemaAccess = (authRules) => {
|
|
|
694
695
|
}
|
|
695
696
|
return { schemaAuth, functionSchemaAccess };
|
|
696
697
|
};
|
|
698
|
+
/**
|
|
699
|
+
* Searches a schema and all related schemas (through `.combine()`) for the given type by name.
|
|
700
|
+
*
|
|
701
|
+
* @param schema
|
|
702
|
+
* @param name
|
|
703
|
+
* @returns
|
|
704
|
+
*/
|
|
705
|
+
const findCombinedSchemaType = (schema, name) => {
|
|
706
|
+
if (schema.context) {
|
|
707
|
+
for (const contextualSchema of schema.context.schemas) {
|
|
708
|
+
if (contextualSchema.data.types[name]) {
|
|
709
|
+
return contextualSchema.data.types[name];
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
else {
|
|
714
|
+
return schema.data.types[name];
|
|
715
|
+
}
|
|
716
|
+
return undefined;
|
|
717
|
+
};
|
|
697
718
|
/**
|
|
698
719
|
* Returns a closure for retrieving reference type and definition from schema
|
|
699
720
|
*/
|
|
700
721
|
const getRefTypeForSchema = (schema) => {
|
|
701
|
-
const getRefType = (
|
|
702
|
-
const typeDef = schema
|
|
722
|
+
const getRefType = (name, referrerName) => {
|
|
723
|
+
const typeDef = findCombinedSchemaType(schema, name);
|
|
703
724
|
if (typeDef === undefined) {
|
|
704
|
-
throw new Error(
|
|
725
|
+
throw new Error(referrerName
|
|
726
|
+
? `Invalid ref. ${referrerName} is referring to ${name} which is not defined in the schema`
|
|
727
|
+
: `Invalid ref. ${name} is not defined in the schema`);
|
|
705
728
|
}
|
|
706
729
|
if (isInternalModel(typeDef)) {
|
|
707
730
|
return { type: 'Model', def: typeDef };
|
|
@@ -715,7 +738,9 @@ const getRefTypeForSchema = (schema) => {
|
|
|
715
738
|
if (isEnumType(typeDef)) {
|
|
716
739
|
return { type: 'Enum', def: typeDef };
|
|
717
740
|
}
|
|
718
|
-
throw new Error(
|
|
741
|
+
throw new Error(referrerName
|
|
742
|
+
? `Invalid ref. ${referrerName} is referring to ${name} which is neither a Model, Custom Operation, Custom Type, or Enum`
|
|
743
|
+
: `Invalid ref. ${name} is neither a Model, Custom Operation, Custom Type, or Enum`);
|
|
719
744
|
};
|
|
720
745
|
return getRefType;
|
|
721
746
|
};
|
|
@@ -866,6 +891,14 @@ const schemaPreprocessor = (schema) => {
|
|
|
866
891
|
if (authString == '') {
|
|
867
892
|
throw new Error(`Model \`${typeName}\` is missing authorization rules. Add global rules to the schema or ensure every model has its own rules.`);
|
|
868
893
|
}
|
|
894
|
+
const getInternalModel = (modelName, sourceName) => {
|
|
895
|
+
const model = getRefType(modelName, sourceName);
|
|
896
|
+
if (!isInternalModel(model.def)) {
|
|
897
|
+
throw new Error(`Expected to find model type with name ${modelName}`);
|
|
898
|
+
}
|
|
899
|
+
return model.def;
|
|
900
|
+
};
|
|
901
|
+
validateRelationships(typeName, fields, getInternalModel);
|
|
869
902
|
const fieldLevelAuthRules = processFieldLevelAuthRules(fields, authFields);
|
|
870
903
|
const { gqlFields, implicitTypes } = processFields(typeName, fields, authFields, fieldLevelAuthRules, identifier, partitionKey, transformedSecondaryIndexes);
|
|
871
904
|
topLevelTypes.push(...implicitTypes);
|
|
@@ -1083,6 +1116,238 @@ function extractNestedCustomTypeNames(customTypeAuthRules, topLevelTypes, getRef
|
|
|
1083
1116
|
const nestedCustomTypeNames = traverseCustomTypeFields(customTypeAuthRules.typeName, customTypeDef);
|
|
1084
1117
|
return nestedCustomTypeNames;
|
|
1085
1118
|
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Validates that defined relationships conform to the following rules.
|
|
1121
|
+
* - relationships are bidirectional
|
|
1122
|
+
* - hasOne has a belongsTo counterpart
|
|
1123
|
+
* - hasMany has a belongsTo counterpart
|
|
1124
|
+
* - belongsTo has either a hasOne or hasMany counterpart
|
|
1125
|
+
* - both sides of a relationship have identical `references` defined.
|
|
1126
|
+
* - the `references` match the primary key of the parent model
|
|
1127
|
+
* - references[0] is the primaryKey's partitionKey on the parent model
|
|
1128
|
+
* - references[1...n] are the primaryKey's sortKey(s) on the parent model
|
|
1129
|
+
* - types match (id / string / number)
|
|
1130
|
+
* - the `references` are fields defined on the child model
|
|
1131
|
+
* - field names match the named `references` arguments
|
|
1132
|
+
* - child model references fields types match those of the parent model's primaryKey
|
|
1133
|
+
* @param typeName source model's type name.
|
|
1134
|
+
* @param record map of field name to {@link ModelField}
|
|
1135
|
+
* @param getInternalModel given a model name, return an {@link InternalModel}
|
|
1136
|
+
*/
|
|
1137
|
+
function validateRelationships(typeName, record, getInternalModel) {
|
|
1138
|
+
for (const [name, field] of Object.entries(record)) {
|
|
1139
|
+
// If the field's type is not a model, there's no relationship
|
|
1140
|
+
// to evaluate and we can skip this iteration.
|
|
1141
|
+
if (!isModelField(field)) {
|
|
1142
|
+
continue;
|
|
1143
|
+
}
|
|
1144
|
+
// Create a structure representing the relationship for validation.
|
|
1145
|
+
const relationship = getModelRelationship(typeName, { name: name, def: field.data }, getInternalModel);
|
|
1146
|
+
// Validate that the references defined in the relationship follow the
|
|
1147
|
+
// relational definition rules.
|
|
1148
|
+
validateRelationalReferences(relationship);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Helper function that describes the relationship of a given connection field for use in logging or error messages.
|
|
1153
|
+
*
|
|
1154
|
+
* `Parent.child: Child @hasMany(references: ['parentId'])`
|
|
1155
|
+
* -- or --
|
|
1156
|
+
* `Child.parent: Parent @belongsTo(references: ['parentId'])`
|
|
1157
|
+
* @param sourceField The {@link ConnectionField} to describe.
|
|
1158
|
+
* @param sourceModelName The name of the model within which the sourceField is defined.
|
|
1159
|
+
* @returns a 'string' describing the relationship
|
|
1160
|
+
*/
|
|
1161
|
+
function describeConnectFieldRelationship(sourceField, sourceModelName) {
|
|
1162
|
+
const associatedTypeDescription = sourceField.def.array
|
|
1163
|
+
? `[${sourceField.def.relatedModel}]`
|
|
1164
|
+
: sourceField.def.relatedModel;
|
|
1165
|
+
const referencesDescription = sourceField.def.references
|
|
1166
|
+
.reduce((description, reference) => description + `'${reference}', `, 'references: [')
|
|
1167
|
+
.slice(0, -2) + ']';
|
|
1168
|
+
return `${sourceModelName}.${sourceField.name}: ${associatedTypeDescription} @${sourceField.def.type}(${referencesDescription})`;
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Validates that the types of child model's reference fields match the types of the parent model's identifier fields.
|
|
1172
|
+
* @param relationship The {@link ModelRelationship} to validate.
|
|
1173
|
+
*/
|
|
1174
|
+
function validateRelationalReferences(relationship) {
|
|
1175
|
+
const { parent, parentConnectionField, child, childConnectionField, references, } = relationship;
|
|
1176
|
+
const parentIdentifiers = getIndentifierTypes(parent);
|
|
1177
|
+
const childReferenceTypes = [];
|
|
1178
|
+
// Iterate through the model schema defined 'references' to find each matching field on the Related model.
|
|
1179
|
+
// If a field by that name is not found, throw a validate error.
|
|
1180
|
+
// Accumulate the ModelFieldType for each reference field to validate matching types below.
|
|
1181
|
+
for (const reference of references) {
|
|
1182
|
+
const relatedReferenceType = child.data.fields[reference]?.data
|
|
1183
|
+
.fieldType;
|
|
1184
|
+
// reference field on related type with name passed to references not found. Time to throw a validation error.
|
|
1185
|
+
if (!relatedReferenceType) {
|
|
1186
|
+
const errorMessage = `reference field '${reference}' must be defined on ${parentConnectionField.def.relatedModel}. ` +
|
|
1187
|
+
describeConnectFieldRelationship(parentConnectionField, childConnectionField.def.relatedModel) +
|
|
1188
|
+
' <-> ' +
|
|
1189
|
+
describeConnectFieldRelationship(childConnectionField, parentConnectionField.def.relatedModel);
|
|
1190
|
+
throw new Error(errorMessage);
|
|
1191
|
+
}
|
|
1192
|
+
childReferenceTypes.push(relatedReferenceType);
|
|
1193
|
+
}
|
|
1194
|
+
if (parentIdentifiers.length !== childReferenceTypes.length) {
|
|
1195
|
+
throw new Error(`The identifiers defined on ${childConnectionField.def.relatedModel} must match the reference fields defined on ${parentConnectionField.def.relatedModel}.\n` +
|
|
1196
|
+
`${parentIdentifiers.length} identifiers defined on ${childConnectionField.def.relatedModel}.\n` +
|
|
1197
|
+
`${childReferenceTypes.length} reference fields found on ${parentConnectionField.def.relatedModel}`);
|
|
1198
|
+
}
|
|
1199
|
+
const matchingModelFieldType = (a, b) => {
|
|
1200
|
+
// `String` and `Id` are considered equal types for when comparing
|
|
1201
|
+
// the child model's references fields with their counterparts within
|
|
1202
|
+
// the parent model's identifier (parent key) fields.
|
|
1203
|
+
const matching = [ModelFieldType.Id, ModelFieldType.String];
|
|
1204
|
+
return a === b || (matching.includes(a) && matching.includes(b));
|
|
1205
|
+
};
|
|
1206
|
+
// Zip pairs of child model's reference field with corresponding parent model's identifier field.
|
|
1207
|
+
// Confirm that the types match. If they don't, throw a validation error.
|
|
1208
|
+
parentIdentifiers
|
|
1209
|
+
.map((identifier, index) => [identifier, childReferenceTypes[index]])
|
|
1210
|
+
.forEach(([parent, child]) => {
|
|
1211
|
+
if (!matchingModelFieldType(parent, child)) {
|
|
1212
|
+
throw new Error('Validate Error: types do not match');
|
|
1213
|
+
}
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Relationship definitions require bi-directionality.
|
|
1218
|
+
* Use this to generate a `ModelRelationshipTypes[]` containing acceptable counterparts on the
|
|
1219
|
+
* associated model.
|
|
1220
|
+
*
|
|
1221
|
+
* Given {@link ModelRelationshipTypes.hasOne} or {@link ModelRelationshipTypes.hasOne} returns [{@link ModelRelationshipTypes.belongsTo}]
|
|
1222
|
+
* Given {@link ModelRelationshipTypes.belongsTo} returns [{@link ModelRelationshipTypes.hasOne}, {@link ModelRelationshipTypes.belongsTo}]
|
|
1223
|
+
*
|
|
1224
|
+
* @param relationshipType {@link ModelRelationshipTypes} defined on source model's connection field.
|
|
1225
|
+
* @returns possible counterpart {@link ModelRelationshipTypes} as `ModelRelationshipTypes[]`
|
|
1226
|
+
*/
|
|
1227
|
+
function associatedRelationshipTypes(relationshipType) {
|
|
1228
|
+
switch (relationshipType) {
|
|
1229
|
+
case ModelRelationshipTypes.hasOne:
|
|
1230
|
+
case ModelRelationshipTypes.hasMany:
|
|
1231
|
+
return [ModelRelationshipTypes.belongsTo];
|
|
1232
|
+
case ModelRelationshipTypes.belongsTo:
|
|
1233
|
+
return [ModelRelationshipTypes.hasOne, ModelRelationshipTypes.hasMany];
|
|
1234
|
+
default:
|
|
1235
|
+
return []; // TODO: Remove this case on types are updated.
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Retrieves the types of the identifiers defined on a model.
|
|
1240
|
+
*
|
|
1241
|
+
* Note: if a field by the name `id` isn't found in the {@link InternalModel},
|
|
1242
|
+
* this assumes an implicitly generated identifier is used with the type.
|
|
1243
|
+
*
|
|
1244
|
+
* This function does not validate that a corresponding field exists for each of the
|
|
1245
|
+
* identifiers because this validation happens at compile time.
|
|
1246
|
+
* @param model {@link InternalModel} from which to retrieve identifier types.
|
|
1247
|
+
* @returns Array of {@link ModelFieldType} of the model's identifiers found.
|
|
1248
|
+
*/
|
|
1249
|
+
function getIndentifierTypes(model) {
|
|
1250
|
+
return model.data.identifier.flatMap((fieldName) => {
|
|
1251
|
+
const field = model.data.fields[fieldName];
|
|
1252
|
+
if (field) {
|
|
1253
|
+
return [field.data.fieldType];
|
|
1254
|
+
}
|
|
1255
|
+
else if (fieldName === 'id') {
|
|
1256
|
+
// implicity generated ID
|
|
1257
|
+
return [ModelFieldType.Id];
|
|
1258
|
+
}
|
|
1259
|
+
return [];
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
/**
|
|
1263
|
+
* Given a relationship definition within a source model (`sourceModelName`, `sourceConnectionField`) and
|
|
1264
|
+
* the associated model (`associatedModel`), this finds the connection field for the relationship defined on the
|
|
1265
|
+
* associated model. Invalid states, such a 0 or >1 matching connection fields result in an error.
|
|
1266
|
+
* @param sourceModelName
|
|
1267
|
+
* @param sourceConnectionField
|
|
1268
|
+
* @param associatedModel
|
|
1269
|
+
* @returns
|
|
1270
|
+
*/
|
|
1271
|
+
function getAssociatedConnectionField(sourceModelName, sourceConnectionField, associatedModel) {
|
|
1272
|
+
const associatedRelationshipOptions = associatedRelationshipTypes(sourceConnectionField.def.type);
|
|
1273
|
+
// Iterate through the associated model's fields to find the associated connection field for the relationship defined on the source model.
|
|
1274
|
+
const associatedConnectionFieldCandidates = Object.entries(associatedModel.data.fields).filter(([_key, connectionField]) => {
|
|
1275
|
+
// If the field isn't a model, it's not part of the relationship definition -- ignore the field.
|
|
1276
|
+
if (!isModelField(connectionField)) {
|
|
1277
|
+
return false;
|
|
1278
|
+
}
|
|
1279
|
+
// In order to find that associated connection field, we need to do some validation that we'll depend on further downstream.
|
|
1280
|
+
// 1. Field type matches the source model's type.
|
|
1281
|
+
// 2. A valid counterpart relational modifier is defined on the field. See `associatedRelationshipTypes` for more information.
|
|
1282
|
+
// 3. The reference arguments provided to the field match (element count + string comparison) references passed to the source connection field.
|
|
1283
|
+
return (connectionField.data.relatedModel === sourceModelName &&
|
|
1284
|
+
associatedRelationshipOptions.includes(connectionField.data.type) &&
|
|
1285
|
+
connectionField.data.references.length ===
|
|
1286
|
+
sourceConnectionField.def.references.length &&
|
|
1287
|
+
connectionField.data.references.every((value, index) => value === sourceConnectionField.def.references[index]));
|
|
1288
|
+
});
|
|
1289
|
+
// We should have found exactly one connection field candidate. If that's not the case, we need to throw a validation error.
|
|
1290
|
+
if (associatedConnectionFieldCandidates.length != 1) {
|
|
1291
|
+
// const associatedModelDescription = sourceConnectionField.def.array
|
|
1292
|
+
// ? `[${sourceConnectionField.def.relatedModel}]`
|
|
1293
|
+
// : sourceConnectionField.def.relatedModel
|
|
1294
|
+
const sourceConnectionFieldDescription = describeConnectFieldRelationship(sourceConnectionField, sourceModelName); // `${sourceModelName}.${sourceConnectionField.name}: ${associatedModelDescription} @${sourceConnectionField.def.type}(references: [${sourceConnectionField.def.references}])`
|
|
1295
|
+
const errorMessage = associatedConnectionFieldCandidates.length === 0
|
|
1296
|
+
? `Unable to find associated relationship definition in ${sourceConnectionField.def.relatedModel}`
|
|
1297
|
+
: `Found multiple relationship associations with ${associatedConnectionFieldCandidates.map((field) => `${sourceConnectionField.def.relatedModel}.${field[0]}`).join(', ')}`;
|
|
1298
|
+
throw new Error(`${errorMessage} for ${sourceConnectionFieldDescription}`);
|
|
1299
|
+
}
|
|
1300
|
+
const associatedConnectionField = associatedConnectionFieldCandidates[0];
|
|
1301
|
+
if (!isModelField(associatedConnectionField[1])) {
|
|
1302
|
+
// This shouldn't happen because we've validated that it's a model field above.
|
|
1303
|
+
// However it's necessary to narrow the type.
|
|
1304
|
+
// const associatedModelDescription = sourceConnectionField.def.array
|
|
1305
|
+
// ? `[${sourceConnectionField.def.relatedModel}]`
|
|
1306
|
+
// : sourceConnectionField.def.relatedModel
|
|
1307
|
+
const sourceConnectionFieldDescription = describeConnectFieldRelationship(sourceConnectionField, sourceModelName);
|
|
1308
|
+
const errorMessage = `Cannot find counterpart to relationship defintion for ${sourceConnectionFieldDescription}`;
|
|
1309
|
+
throw new Error(errorMessage);
|
|
1310
|
+
}
|
|
1311
|
+
return {
|
|
1312
|
+
name: associatedConnectionField[0],
|
|
1313
|
+
def: associatedConnectionField[1].data,
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* Given either side of a relationship (source), this retrieves the other side (related)
|
|
1318
|
+
* and packages the information neatly into a {@link ModelRelationship} for validation purposes.
|
|
1319
|
+
*
|
|
1320
|
+
* @param sourceModelName
|
|
1321
|
+
* @param sourceConnectionField
|
|
1322
|
+
* @param getInternalModel
|
|
1323
|
+
* @returns a {@link ModelRelationship}
|
|
1324
|
+
*/
|
|
1325
|
+
function getModelRelationship(sourceModelName, sourceModelConnectionField, getInternalModel) {
|
|
1326
|
+
const sourceModel = getInternalModel(sourceModelName, sourceModelName);
|
|
1327
|
+
const associatedModel = getInternalModel(sourceModelConnectionField.def.relatedModel, sourceModelName);
|
|
1328
|
+
const relatedModelConnectionField = getAssociatedConnectionField(sourceModelName, sourceModelConnectionField, associatedModel);
|
|
1329
|
+
switch (sourceModelConnectionField.def.type) {
|
|
1330
|
+
case ModelRelationshipTypes.hasOne:
|
|
1331
|
+
case ModelRelationshipTypes.hasMany:
|
|
1332
|
+
return {
|
|
1333
|
+
parent: sourceModel,
|
|
1334
|
+
parentConnectionField: sourceModelConnectionField,
|
|
1335
|
+
child: associatedModel,
|
|
1336
|
+
childConnectionField: relatedModelConnectionField,
|
|
1337
|
+
references: sourceModelConnectionField.def.references,
|
|
1338
|
+
};
|
|
1339
|
+
case ModelRelationshipTypes.belongsTo:
|
|
1340
|
+
return {
|
|
1341
|
+
parent: associatedModel,
|
|
1342
|
+
parentConnectionField: relatedModelConnectionField,
|
|
1343
|
+
child: sourceModel,
|
|
1344
|
+
childConnectionField: sourceModelConnectionField,
|
|
1345
|
+
references: sourceModelConnectionField.def.references,
|
|
1346
|
+
};
|
|
1347
|
+
default:
|
|
1348
|
+
throw new Error(`"${sourceModelConnectionField.def.type}" is not a valid relationship type.`);
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1086
1351
|
/**
|
|
1087
1352
|
* Returns API definition from ModelSchema or string schema
|
|
1088
1353
|
* @param arg - { schema }
|