Started restructuring the library with attacks, saves, and limited parenting

This commit is contained in:
Stefan Zermatten
2019-08-12 16:42:30 +02:00
parent 6f4710bee3
commit a8b3fc3f2f
14 changed files with 204 additions and 91 deletions

View File

@@ -1,5 +1,41 @@
import fetchDocByRef from '/imports/api/parenting/fetchDocByRef.js';
import getCollectionByName from '/imports/api/parenting/getCollectionByName.js';
import { flatten } from 'lodash';
const generalParents = [
'attribute',
'buff',
'classLevel',
'feature',
'folder',
'root',
'item',
'spell',
];
// Which types are allowed as parents for other types
const allowedParenting = {
folder: [...generalParents, 'container'],
rollResult: ['roll', 'rollResult'],
container: ['root', 'folder'],
item: ['root', 'container', 'folder'],
};
const allParentTypes = new Set(flatten(Object.values(allowedParenting)));
export function canBeParent(type){
return type && allParentTypes.has(type);
}
export function getAllowedParents({childType}){
return allowedParenting[childType] || generalParents;
}
export function isParentAllowed({parentType = 'root', childType}){
if (!childType) throw 'childType is required';
let allowedParents = getAllowedParents({childType});
return allowedParents.includes(parentType);
}
export function fetchParent({id, collection}){
return fetchDocByRef({id, collection});
@@ -55,7 +91,7 @@ export function getAncestry({parentRef, inheritedFields = {}}){
let ancestors = parentDoc.ancestors || [];
ancestors.push(parent);
return {parent, ancestors};
return {parentDoc, parent, ancestors};
}
export function updateParent({docRef, parentRef}){
@@ -63,14 +99,30 @@ export function updateParent({docRef, parentRef}){
let oldDoc = fetchDocByRef(docRef, {fields: {
parent: 1,
ancestors: 1,
type: 1,
}});
let updateOptions = { selector: {type: 'any'} };
// Skip if we aren't changing the parent id
if (oldDoc.parent.id === parentRef.id) return;
// Get the parent and its ancestry
let {parentDoc, parent, ancestors} = getAncestry({parentRef});
// If the doc and its parent are in the same collection, apply the allowed
// parent rules based on type
if (docRef.collection === parentRef.collection){
let parentAllowed = isParentAllowed({
parentType: parentDoc.type,
childType: oldDoc.type
});
if (!parentAllowed){
throw new Meteor.Error('invalid parenting',
`Can't make ${oldDoc.type} a child of ${parentDoc.type}`)
}
}
// update the document's parenting
let {parent, ancestors} = getAncestry({parentRef});
collection.update(docRef.id, {
$set: {parent, ancestors}
}, updateOptions);