UNPKG

cluedin-widget

Version:

This is the project for creating and managing widgets in CluedIn.

69 lines (56 loc) 2.89 kB
var lodash = require( 'lodash' ); module.exports = function( bookshelf ) { var models = require( 'cluedin-widget-models' )( bookshelf ).models; var UserProfile = models.application.UserWidgetProfile; var UserWidgetConfigurations = models.application.UserWidgetConfigurations; return { createUserProfile: function( userProfile, callback ) { if ( !userProfile.email || !userProfile.clientId ) { return callback( "invalid userProfile" ); } new UserProfile( userProfile ).save().then( function( model ) { callback( null, model ) } ).catch( callback ); }, express: { updateWidgetConfiguration: function( req, res ) { if ( !req.body.email || !req.body.clientId || !req.body.widgetId || !req.body.configuration ) { return res.send( 400 ); } new UserProfile( { email: req.body.email, clientId: req.body.clientId } ).fetch( { withRelated: [ 'configurations', 'configurations.widget' ] } ).then( function( userProfile ) { var configurations = userProfile.related( 'configurations' ); var findConfiguration = lodash.find( configurations, function( conf ) { return conf.widget.id === req.body.widgetId; } ); if ( !findConfiguration ) { //new widget Config var userWidgetConfig = new UserWidgetConfigurations( { configuration: req.body.configuration, userWidgetProfile_id: userProfile.id, widget_id: req.body.widgetId } ); userWidgetConfig.save().then( function( model ) { //should be good if ( !model ) { return res.send( 'something went wrong' ); } else { return res.send( 200 ); } } ); } else { //existing new UserWidgetConfigurations( findConfiguration ).fetch().then( function( widgetConfigModel ) { widgetConfigModel.configuration = req.body.configuration; widgetConfigModel.save().then( function() { return res.send( 200 ); } ); } ); } } ); } } }; };