This commit is contained in:
Jonasz Bigda
2023-03-25 21:51:42 +01:00
parent 0db1d5117e
commit b332e9ceb0
1044 changed files with 37502 additions and 63938 deletions

View File

@@ -1,5 +1,6 @@
'use strict';
const Mixed = require('../../schema/mixed');
const defineKey = require('../document/compile').defineKey;
const get = require('../get');
const utils = require('../../utils');
@@ -62,7 +63,7 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
}
let value = name;
if (typeof tiedValue == 'string' && tiedValue.length) {
if ((typeof tiedValue === 'string' && tiedValue.length) || tiedValue != null) {
value = tiedValue;
}
@@ -84,22 +85,25 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
for (const path of baseSchemaPaths) {
if (schema.nested[path]) {
conflictingPaths.push(path);
continue;
}
if (path.indexOf('.') === -1) {
continue;
}
const sp = path.split('.');
const sp = path.split('.').slice(0, -1);
let cur = '';
for (const piece of sp) {
cur += (cur.length ? '.' : '') + piece;
if (schema.paths[cur] || schema.singleNestedPaths[cur]) {
if (schema.paths[cur] instanceof Mixed ||
schema.singleNestedPaths[cur] instanceof Mixed) {
conflictingPaths.push(path);
}
}
}
utils.merge(schema, baseSchema, {
isDiscriminatorSchemaMerge: true,
omit: { discriminators: true, base: true },
omitNested: conflictingPaths.reduce((cur, path) => {
cur['tree.' + path] = true;
@@ -122,17 +126,17 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
default: value,
select: true,
set: function(newName) {
if (newName === value) {
if (newName === value || (Array.isArray(value) && utils.deepEqual(newName, value))) {
return value;
}
throw new Error('Can\'t set discriminator key "' + key + '"');
},
$skipDiscriminatorCheck: true
};
obj[key][schema.options.typeKey] = existingPath ?
existingPath.instance :
String;
obj[key][schema.options.typeKey] = existingPath ? existingPath.options[schema.options.typeKey] : String;
schema.add(obj);
schema.discriminatorMapping = { key: key, value: value, isRoot: false };
if (baseSchema.options.collection) {
@@ -149,11 +153,17 @@ module.exports = function discriminator(model, name, schema, tiedValue, applyPlu
for (const _key of keys) {
if (!CUSTOMIZABLE_DISCRIMINATOR_OPTIONS[_key]) {
// Special case: compiling a model sets `pluralization = true` by default. Avoid throwing an error
// for that case. See gh-9238
if (_key === 'pluralization' && schema.options[_key] == true && baseSchema.options[_key] == null) {
continue;
}
if (!utils.deepEqual(schema.options[_key], baseSchema.options[_key])) {
throw new Error('Can\'t customize discriminator option ' + _key +
' (can only modify ' +
Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') +
')');
' (can only modify ' +
Object.keys(CUSTOMIZABLE_DISCRIMINATOR_OPTIONS).join(', ') +
')');
}
}
}