From e93ad5d7b3299dbd28d6ad80d7716c59948ad190 Mon Sep 17 00:00:00 2001 From: dbroqua Date: Wed, 10 Oct 2018 21:10:43 +0200 Subject: [PATCH] Auto add properties --- middleware/Vegetables.js | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/middleware/Vegetables.js b/middleware/Vegetables.js index b08d9f7..9b4a338 100644 --- a/middleware/Vegetables.js +++ b/middleware/Vegetables.js @@ -31,7 +31,41 @@ class Vegetables { vegetables.create(newItem) .then(item => { - callback(null, item) + models.properties + .findAndCountAll() + .then(properties => { + if (properties && properties.rows.length > 0) { + let saved = 0 + const _callback = () => { + if (properties.count === saved) { + callback(null, item) + } + + properties.rows.forEach(propperty => { + models.vegetableProp + .create({ + vegetablesId: item.id, + propertyId: propperty.id + }) + .then(() => { + saved += 1 + _callback() + }) + .catch((e) => { + console.log(e) + saved += 1 + _callback() + }) + }) + } + } else { + callback(null, item) + } + }) + .catch(e => { + item.destroy() + callback(e, 500) + }) }) .catch(e => { callback(e, null)