Sunday, 30 April 2017

Updating associated keywords for entry, using Sequelize?

I have some code that I have written in node.js & Sequelize to update the keywords associated with an entry, and would like to know whether there is a way to improve on this code.

I have 3 tables:

  • Document
  • Keywords (fields: id, name, language)
  • Document-Keywords (fields: document_id, keyword_id)

Below is the function, which takes the document and the keywords to be associated. The first step is removing the keywords associations and then adding the ones to be set. This may result in a keyword association being removed, only to be added again, but I couldn't see an approach that would result in less code.

setKeywords(document, keywords, language, transaction) {
    return documentKeyword.destroy({
        where: {
            documentId: document.id
        },
        transaction: transaction
    }).then(function (deletedRecords) {
        return Promise.mapSeries(keywords, function (keyword) {
            // Find or create the keyword and then
            // create an association
            return Keyword.findOrCreate({
                    where: {
                        name: keyword,
                        language: language
                    },
                    transaction: transaction
                }).spread(function(keyword) {
                    return document.addKeyword(keyword, {
                        transaction: transaction
                    });
                }).then(function(result) {
                    return {
                        name: keyword,
                        rating: language
                    };
                });
        });
    })
}



via Andre M

No comments:

Post a Comment