Skip to content

Commit

Permalink
feat(edition): Allow EG to be auto-created if editign existing Edition
Browse files Browse the repository at this point in the history
If an Edition doesn't have an EG filled (whether it be during creation or edit, previously only for cretion), auto create an EG.
See metabrainz/bookbrainz-site#522 for context
  • Loading branch information
MonkeyDo committed Oct 8, 2020
1 parent da4e85b commit 7144d3f
Showing 1 changed file with 18 additions and 9 deletions.
27 changes: 18 additions & 9 deletions src/models/entities/edition.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@
import _ from 'lodash';
import {createEditionGroupForNewEdition} from '../../util';

/**
* @param {any} model The ORM model of the Edition being edited/created
* @param {any} bookshelf The BoolshelfJS ORM
* @param {any} options Query options — seuch as transacting object
* @description Automatically create and sets a new Edition Group
* if there is none selected, in the same transaction
*/
async function autoCreateNewEditionGroup(model, bookshelf, options) {
const aliasSetId = model.get('aliasSetId');
const revisionId = model.get('revisionId');
const newEditionGroupBBID = await createEditionGroupForNewEdition(
bookshelf, options.transacting, aliasSetId, revisionId
);
model.set('editionGroupBbid', newEditionGroupBBID);
}

export default function edition(bookshelf) {
const EditionData = bookshelf.model('EditionData');
Expand All @@ -36,25 +51,19 @@ export default function edition(bookshelf) {
}
});

this.on('updating', (model, attrs, options) => {
this.on('updating', async (model, attrs, options) => {
// Always update the master revision.
options.query.where({master: true});
if (_.has(model, 'changed.editionGroupBbid') &&
!model.get('editionGroupBbid')
) {
throw new Error('EditionGroupBbid required in Edition update');
await autoCreateNewEditionGroup(model, bookshelf, options);
}
});

this.on('creating', async (model, attrs, options) => {
// Automatically create a new Edition Group if there is none selected,
// in the same transaction
if (!model.get('editionGroupBbid')) {
const aliasSetId = model.get('aliasSetId');
const revisionId = model.get('revisionId');
const newEditionGroupBBID =
await createEditionGroupForNewEdition(bookshelf, options.transacting, aliasSetId, revisionId);
model.set('editionGroupBbid', newEditionGroupBBID);
await autoCreateNewEditionGroup(model, bookshelf, options);
}
});
},
Expand Down

0 comments on commit 7144d3f

Please sign in to comment.