Skip to content

Instantly share code, notes, and snippets.

@arnaudbesnier
Created January 23, 2018 17:33
Show Gist options
  • Save arnaudbesnier/ea10740cdb19a927d4056efa3492419c to your computer and use it in GitHub Desktop.
Save arnaudbesnier/ea10740cdb19a927d4056efa3492419c to your computer and use it in GitHub Desktop.
Smart Action for "deep" creation
// See documentation at https://doc.forestadmin.com/developer-guide/lumber.html#actions
// Smart Action declaration example in forest/request.js
const Liana = require('forest-express-sequelize');
Liana.collection('request', {
actions: [{
name: 'Add offer with child objects',
fields: [{
field: 'offerStatus',
type: 'String',
}, {
field: 'userName',
type: 'String',
}, {
field: 'offerDetailDescription',
type: 'String',
}],
}],
});
// Smart Action logic in routes/requests.js
'use strict';
const P = require('bluebird');
const express = require('express');
const router = express.Router();
const liana = require('forest-express-sequelize');
const models = require('../models');
router.post('/actions/add-offer-with-child-objects', liana.ensureAuthenticated, (request, response) => {
const requestId = request.body.data.attributes.ids[0];
const params = request.body.data.attributes.values;
const promises = [];
promises.push(models.requests.findById(requestId));
promises.push(models.offers.create({ status: params.offerStatus }));
promises.push(models.users.create({ name: params.userName }));
promises.push(models.offerDetails.create({ description: params.offerDetailDescription }));
return P
.spread(promises)
.then(function(request, offer, user, offerDetail) {
return offer
.setUser(user);
.then(function () {
return offer.setOfferDetail(offerDetail);
})
.then(function() {
return request.addOffer(offer);
});
});
.then(function() {
response.send({
success: 'Offer successfully added!',
});
});
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment