Skip to content

Instantly share code, notes, and snippets.

@Mozu-CS
Last active February 18, 2016 00:45
Show Gist options
  • Save Mozu-CS/7c3e8e049801801d730f to your computer and use it in GitHub Desktop.
Save Mozu-CS/7c3e8e049801801d730f to your computer and use it in GitHub Desktop.
Express and Mozu Node SDK Blog Post Materials
Received POST request...
{ eventId: '6e3bf479-599d-4b6e-b649-a570000811bd',
topic: 'application.enabled',
entityId: '0ac2281ae28e4e39ac1b4f58d204d368',
timestamp: '2015-12-16T00:29:20.2971532Z',
correlationId: 'f234a36052bd468e88caf073d538b521',
isTest: false }
POST /application.events 200 4.372 ms - 2
Received POST request...
{ eventId: 'a7a44041-2909-499c-9d21-a5700006670b',
topic: 'application.installed',
entityId: '0ac2281ae28e4e39ac1b4f58d204d368',
timestamp: '2015-12-16T00:23:12.4621615Z',
correlationId: '',
isTest: false }
POST /application.events 200 10.187 ms - 2
{ "eventId": "7a548a93-49ff-4735-aacb-a5700008df7f",
"topic": "application.upgraded",
"entityId": "0ac2281ae28e4e39ac1b4f58d204d368",
"timestamp": "2015-12-16T00:32:12.9551001Z",
"correlationId": "",
"isTest": false }
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var application_events = require('./routes/application-events');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/application.events', application_events);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
var ApplicationResourceFactory = require('mozu-node-sdk/clients/platform/application');
exports.applicationDisabled = function (apiContext, eventPayload) {
console.log("Application Disabled returned -- preparing for work...");
console.log(eventPayload.entityId);
}
exports.applicationEnabled = function (apiContext, eventPayload) {
console.log("Application Enabled returned -- preparing for work...");
console.log(eventPayload.entityId);
}
exports.applicationInstalled = function (apiContext, eventPayload) {
console.log("Application Installed returned -- preparing for work...");
console.log(eventPayload.entityId);
}
exports.applicationUninstalled = function (apiContext, eventPayload) {
console.log("Application Uninstalled returned -- preparing for work...");
console.log(eventPayload.entityId);
}
exports.applicationUpgraded = function (apiContext, eventPayload) {
console.log("Application Upgraded returned -- preparing for work...");
console.log(eventPayload.entityId);
}
var CustomerAccountResourceFactory = require('mozu-node-sdk/clients/commerce/customer/customerAccount');
var log = require('../util/logging').LogToConsole;
var report = require('../util/logging').ReportErrorToConsole;
exports.customerAccountCreated = function (apiContext, eventPayload) {
console.log("Customer Account Created returned -- preparing for work...");
console.log(eventPayload.entityId);
};
exports.customerAccountUpdated = function (apiContext, eventPayload) {
console.log("Customer Account Updated returned -- preparing for work...");
console.log(eventPayload.entityId);
var customerAccountResource = CustomerAccountResourceFactory(apiContext);
customerAccountResource.getAccount({ accountId: eventPayload.entityId })
.then(log)
.catch(report);
};
exports.customerAccountDeleted = function(apiContext, eventPayload) {
console.log("Customer Account Deleted returned -- preparing for work...");
console.log(eventPayload.entityId);
};
var topic = require('./event-names.js');
var ApplicationEventHandlers = require('../event-handlers/ApplicationEventHandlers');
var ProductAttributeEventHandlers = require('../event-handlers/ProductAttributeEventHandlers');
var CartEventHandlers = require('../event-handlers/CartEventHandlers');
var CategoryEventHandlers = require('../event-handlers/CategoryEventHandlers');
var CreditEventHandlers = require('../event-handlers/CreditEventsHandlers');
var CustomerAccountEventHandlers = require('../event-handlers/CustomerAccountEventHandlers');
var CustomerSegmentEventHandlers = require('../event-handlers/CustomerSegmentEventHandlers');
var DiscountEventHandlers = require('../event-handlers/DiscountEventHandlers');
var EmailEventHandlers = require('../event-handlers/EmailEventHandlers');
var FacetEventHandlers = require('../event-handlers/FacetEventHandlers');
var LocationTypeEventHandlers = require('../event-handlers/LocationTypeEventHandlers');
var OrderEventHandlers = require('../event-handlers/OrderEventHandlers');
var ProductEventHandlers = require('../event-handlers/ProductEventHandlers');
var ProductTypeEventHandlers = require('../event-handlers/ProductTypeEventHandlers');
var ReturnEventHandlers = require('../event-handlers/ReturnEventHandlers');
var SearchSettingsEventHandlers = require('../event-handlers/SearchSettingsEventHandlers');
var ShipmentEventHandlers = require('../event-handlers/ShipmentEventHandlers');
var SiteEventHandlers = require('../event-handlers/SiteEventHandlers');
var TenantEventHandlers = require('../event-handlers/TenantEventHandlers');
var WishlistEventHandlers = require('../event-handlers/WishlistEventHandlers');
var Dispatcher = {};
//Application Events
Dispatcher[topic.APPLICATIONDISABLED] = ApplicationEventHandlers.applicationDisabled;
Dispatcher[topic.APPLICATIONENABLED] = ApplicationEventHandlers.applicationEnabled;
Dispatcher[topic.APPLICATIONINSTALLED] = ApplicationEventHandlers.applicationInstalled;
Dispatcher[topic.APPLICATIONUNINSTALLED] = ApplicationEventHandlers.applicationUninstalled;
Dispatcher[topic.APPLICATIONUPGRADED] = ApplicationEventHandlers.applicationUpgraded,
//Product Attribute Events
Dispatcher[topic.ATTRIBUTECREATED] = ProductAttributeEventHandlers.attributeCreated;
Dispatcher[topic.ATTRIBUTEDELETED] = ProductAttributeEventHandlers.attributeDeleted;
Dispatcher[topic.ATTRIBUTEUPDATED] = ProductAttributeEventHandlers.attributeUpdated;
//Cart Events
Dispatcher[topic.CARTCREATED] = CartEventHandlers.cartCreated;
Dispatcher[topic.CARTDELETED] = CartEventHandlers.cartDeleted;
Dispatcher[topic.CARTUPDATED] = CartEventHandlers.cartUpdated;
//Category Events
Dispatcher[topic.CATEGORYCREATED] = CategoryEventHandlers.categoryCreated;
Dispatcher[topic.CATEGORYDELETED] = CategoryEventHandlers.categoryDeleted;
Dispatcher[topic.CATEGORYUPDATED] = CategoryEventHandlers.categoryUpdated;
//Credit Events
Dispatcher[topic.CREDITCREATED] = CreditEventHandlers.creditCreated;
Dispatcher[topic.CREDITDELETED] = CreditEventHandlers.creditDeleted;
Dispatcher[topic.CREDITUPDATED] = CreditEventHandlers.creditUpdated;
//Customer Account Events
Dispatcher[topic.CUSTOMERACCOUNTCREATED] = CustomerAccountEventHandlers.customerAccountCreated;
Dispatcher[topic.CUSTOMERACCOUNTUPDATED] = CustomerAccountEventHandlers.customerAccountUpdated;
Dispatcher[topic.CUSTOMERACCOUNTDELETED] = CustomerAccountEventHandlers.customerAccountDeleted;
//Customer Segment Events
Dispatcher[topic.CUSTOMERSEGMENTCREATE] = CustomerSegmentEventHandlers.customerSegmentCreated;
Dispatcher[topic.CUSTOMERSEGMENTCUSTOMERADDED] = CustomerSegmentEventHandlers.customerSegmentCustomerAdded;
Dispatcher[topic.CUSTOMERSEGMENTCUSTOMERREMOVED] = CustomerSegmentEventHandlers.customerSegmentCustomerRemoved;
Dispatcher[topic.CUSTOMERSEGMENTDELETE] = CustomerSegmentEventHandlers.customerSegmentDeleted;
Dispatcher[topic.CUSTOMERSEGMENTUPDATED] = CustomerSegmentEventHandlers.customerSegmentUpdated;
//Discount Events
Dispatcher[topic.DISCOUNTCREATED] = DiscountEventHandlers.discountCreated;
Dispatcher[topic.DISCOUNTDELETED] = DiscountEventHandlers.discountDeleted;
Dispatcher[topic.DISCOUNTEXPIRED] = DiscountEventHandlers.discountExpired;
Dispatcher[topic.DISCOUNTUPDATED] = DiscountEventHandlers.discountUpdated;
//Email Events
Dispatcher[topic.EMAILREQUESTED] = EmailEventHandlers.emailRequested;
//Facet Events
Dispatcher[topic.FACETCREATED] = FacetEventHandlers.facetCreated;
Dispatcher[topic.FACETDELETED] = FacetEventHandlers.facetDeleted;
Dispatcher[topic.FACETUPDATED] = FacetEventHandlers.facetUpdated;
//Location Type Events
Dispatcher[topic.LOCATIONTYPECREATED] = LocationTypeEventHandlers.locationTypeCreated;
Dispatcher[topic.LOCATIONTYPEDELETED] = LocationTypeEventHandlers.locationTypeDeleted;
Dispatcher[topic.LOCATIONTYPEUPDATED] = LocationTypeEventHandlers.locationTypeUpdated;
//Order Events
Dispatcher[topic.ORDERABANDONED] = OrderEventHandlers.orderAbandoned;
Dispatcher[topic.ORDERCANCELLED] = OrderEventHandlers.orderCancelled;
Dispatcher[topic.ORDERCLOSED] = OrderEventHandlers.orderClosed;
Dispatcher[topic.ORDERFULFILLED] = OrderEventHandlers.orderFulfilled;
Dispatcher[topic.ORDEROPENED] = OrderEventHandlers.orderOpened;
Dispatcher[topic.ORDERPENDINGREVIEW] = OrderEventHandlers.orderPendingReview;
Dispatcher[topic.ORDERUPDATED] = OrderEventHandlers.orderUpdated;
//Product Events
Dispatcher[topic.PRODUCTCODERENAMED] = ProductEventHandlers.productCodeRenamed;
Dispatcher[topic.PRODUCTCREATED] = ProductEventHandlers.productCreated;
Dispatcher[topic.PRODUCTDELETED] = ProductEventHandlers.productDeleted;
Dispatcher[topic.PRODUCTUPDATED] = ProductEventHandlers.productUpdated;
//Product Publishing Events
Dispatcher[topic.PRODUCTDRAFTCREATED] = ProductEventHandlers.productDraftCreated;
Dispatcher[topic.PRODUCTDRAFTDELETED] = ProductEventHandlers.productDraftDeleted;
Dispatcher[topic.PRODUCTDRAFTDISCARDED] = ProductEventHandlers.productDraftDiscarded;
Dispatcher[topic.PRODUCTDRAFTPUBLISHED] = ProductEventHandlers.productDraftPublished;
Dispatcher[topic.PRODUCTDRAFTUPDATED] = ProductEventHandlers.productDraftUpdated;
//Product Inventory Events
Dispatcher[topic.PRODUCTINVENTORYINSTOCK] = ProductEventHandlers.productInventoryInStock;
Dispatcher[topic.PRODUCTINVENTORYOUTOFSTOCK] = ProductEventHandlers.productInventoryOutOfStock;
Dispatcher[topic.PRODUCTINVENTORYUPDATED] = ProductEventHandlers.productInventoryUpdated;
//Produt Type Events
Dispatcher[topic.PRODUCTTYPECREATED] = ProductTypeEventHandlers.productTypeCreated;
Dispatcher[topic.PRODUCTTYPEDELETED] = ProductTypeEventHandlers.productTypeDeleted;
Dispatcher[topic.PRODUCTTYPEUPDATED] = ProductTypeEventHandlers.productTypeUpdated;
//Return Events
Dispatcher[topic.RETURNCANCELLED] = ReturnEventHandlers.returnCancelled;
Dispatcher[topic.RETURNCLOSED] = ReturnEventHandlers.returnClosed;
Dispatcher[topic.RETURNOPENED] = ReturnEventHandlers.returnOpened;
Dispatcher[topic.RETURNREJECTED] = ReturnEventHandlers.returnRejected;
Dispatcher[topic.RETURNUPDATED] = ReturnEventHandlers.returnUpdated;
//Search Settings Events
Dispatcher[topic.SEARCHSETTINGSUPDATED] = SearchSettingsEventHandlers.searchSettingsUpdated;
//Shipment Events
Dispatcher[topic.SHIPMENTFULFILLED] = ShipmentEventHandlers.shipmentFulfilled;
//Site Events
Dispatcher[topic.SITECLONED] = SiteEventHandlers.siteCloned;
Dispatcher[topic.SITECREATED] = SiteEventHandlers.siteCreated;
Dispatcher[topic.SITEDELETED] = SiteEventHandlers.siteDeleted;
Dispatcher[topic.SITEUPDATED] = SiteEventHandlers.siteUpdated;
//Tenant Events
Dispatcher[topic.TENANTDELETED] = TenantEventHandlers.tenantDeleted;
Dispatcher[topic.TENANTUPDATED] = TenantEventHandlers.tenantUpdated;
//Wishlist Events
Dispatcher[topic.WISHLISTCREATED] = WishlistEventHandlers.wishlistCreated;
Dispatcher[topic.WISHLISTDELETED] = WishlistEventHandlers.wishlistDeleted;
Dispatcher[topic.WISHLISTUPDATED] = WishlistEventHandlers.wishlistUpdated;
module.exports = Dispatcher;
module.exports = {
APPLICATIONDISABLED: "application.disabled",
APPLICATIONENABLED: "application.enabled",
APPLICATIONINSTALLED: "application.installed",
APPLICATIONUNINSTALLED: "application.uninstalled",
APPLICATIONUPGRADED: "application.upgraded",
ATTRIBUTECREATED: "attribute.created",
ATTRIBUTEDELETED: "attribute.deleted",
ATTRIBUTEUPDATED: "attribute.updated",
CARTCREATED: "cart.created",
CARTDELETED: "cart.deleted",
CARTUPDATED: "cart.updated",
CATEGORYCREATED: "category.created",
CATEGORYDELETED: "category.deleted",
CATEGORYUPDATED: "category.updated",
CREDITCREATED: "credit.created",
CREDITDELETED: "credit.deleted",
CREDITUPDATED: "credit.updated",
CUSTOMERACCOUNTCREATED: "customeraccount.created",
CUSTOMERACCOUNTDELETED: "customeraccount.deleted",
CUSTOMERACCOUNTUPDATED: "customeraccount.updated",
CUSTOMERSEGMENTCREATED: "customersegment.created",
CUSTOMERSEGMENTCUSTOMERADDED: "customersegment.customeradded",
CUSTOMERSEGMENTCUSTOMERREMOVED: "customersegment.customerremoved",
CUSTOMERSEGMENTDELETED: "customersegment.deleted",
CUSTOMERSEGMENTUPDATED: "customersegment.updated",
DISCOUNTCREATED: "discount.created",
DISCOUNTDELETED: "discount.deleted",
DISCOUNTEXPIRED: "discount.expired",
DISCOUNTUPDATED: "discount.updated",
EMAILREQUESTED: "email.requested",
FACETCREATED: "facet.created",
FACETDELETED: "facet.deleted",
FACETUPDATED: "facet.updated",
LOCATIONTYPECREATED: "locationtype.created",
LOCATIONTYPEDELETED: "locationtype.deleted",
LOCATIONTYPEUPDATED: "locationtype.updated",
ORDERABANDONED: "order.abandoned",
ORDERCANCELLED: "order.cancelled",
ORDERCLOSED: "order.closed",
ORDERFULFILLED: "order.fulfilled",
ORDEROPENED: "order.opened",
ORDERPENDINGREVIEW: "order.pendingreview",
ORDERUPDATED: "order.updated",
PRODUCTCODERENAMED: "product.coderenamed",
PRODUCTCREATED: "product.created",
PRODUCTDELETED: "product.deleted",
PRODUCTUPDATED: "product.updated",
PRODUCTDRAFTCREATED: "productdraft.created",
PRODUCTDRAFTDELETED: "productdraft.deleted",
PRODUCTDRAFTDISCARDED: "productdraft.discarded",
PRODUCTDRAFTPUBLISHED: "productdraft.published",
PRODUCTDRAFTUPDATED: "productdraft.updated",
PRODUCTINVENTORYINSTOCK: "productinventory.instock",
PRODUCTINVENTORYOUTOFSTOCK: "productinventory.outofstock",
PRODUCTINVENTORYUPDATED: "productinventory.updated",
PRODUCTTYPECREATED: "producttype.created",
PRODUCTTYPEDELETED: "producttype.deleted",
PRODUCTTYPEUPDATED: "producttype.updated",
RETURNCANCELLED: "return.cancelled",
RETURNCLOSED: "return.closed",
RETURNOPENED: "return.opened",
RETURNREJECTED: "return.rejected",
RETURNUPDATED: "return.updated",
SEARCHSETTINGSUPDATED: "searchsettings.updated",
SHIPMENTFULFILLED: "shipment.fulfilled",
SITECLONED: "site.cloned",
SITECREATED: "site.created",
SITEDELETED: "site.deleted",
SITEUPDATED: "site.updated",
TENANTDELETED: "tenant.deleted",
TENANTUPDATED: "tenant.updated",
WISHLISTCREATED: "wishlist.created",
WISHLISTDELETED: "wishlist.deleted",
WISHLISTUPDATED: "wishlist.updated"
}
extends layout
block content
h1= title
p My route to #{title} is working!
var express = require('express');
var router = express.Router();
var Dispatcher = require('../util/event-dispatcher');
var apiContext = require('mozu-node-sdk/clients/platform/application')();
var isRequestValid = require('mozu-node-sdk/security/is-request-valid');
var transformContext = require('../util/transform-apiContext');
/* GET /mozu.events */
router.get('/', function (req, res, next) {
res.render('events', { title: 'Eventing' });
});
//Mozu Validation Middleware
router.use(function (req, res, next) {
isRequestValid(apiContext.context, req, function (err) {
if (err) {
res.status(401);
res.render('error', { message: err.message, error: err });
} else {
req.mozu = { isValid: true };
next();
}
});
});
/* POST against /mozu.events */
router.post('/', function (req, res, next) {
res.sendStatus(200);
transformContext(req.headers, apiContext, function (err, newApiContext) {
if (err) {
console.error(err);
} else {
console.log("Is Valid? " + (req.mozu.isValid ? "\u2713" : "x"));
var EventHandler = Dispatcher[req.body.topic];
EventHandler(newApiContext, req.body);
}
});
});
module.exports = router;
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('events', { title: 'Mozu Eventing' });
});
router.post('/', function(req, res, next) {
console.log("Received POST request...");
console.log(req.body);
res.sendStatus(200);
});
module.exports = router;
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('events', { title: 'Mozu Eventing' });
});
module.exports = router;
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('events', { title: 'Mozu Eventing' });
});
router.post('/', function(req, res, next) {
console.log("Received POST request...");
console.log(req.body);
if(req.body.topic == "application.upgraded") {
console.log("Well what do you know? Your application was upgraded!");
}
res.sendStatus(200);
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment