Advertisement
Guest User

Untitled

a guest
Sep 7th, 2017
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.90 KB | None | 0 0
  1. const async = require('async');
  2. const _ = require('lodash');
  3. const moment = require('moment');
  4. const Client = require('node-rest-client').Client;
  5. const fs = require('fs');
  6.  
  7. const input = require('./TestFull.json');
  8.  
  9. module.exports = () => {
  10. const filename = `./eventfulFails-${new moment().format("YYYY-MM-DD-HHmmss")}.json`;
  11. console.log('Start Time: ', new moment().format("HH:mm:ss"));
  12.  
  13. let failedObjects = {
  14. events: [],
  15. venues: [],
  16. performers: []
  17. };
  18.  
  19. async.parallel([
  20. async.apply(processVenues, input.venues, failedObjects),
  21. async.apply(processPerformers, input.performers, failedObjects)
  22. ], (lookupErr) => {
  23. if (lookupErr) {
  24. return console.error('Error processing venues and performers.', lookupErr);
  25. }
  26. console.log('Start Events: ', new moment().format("HH:mm:ss"));
  27.  
  28. async.waterfall([
  29. async.apply(processEvents, input.events, failedObjects)
  30. ], (eventErr) => {
  31. if (eventErr) {
  32. console.log('Time of Failure: ', new moment().format("HH:mm:ss"));
  33. return console.error('Error processing events.', eventErr);
  34. }
  35. console.log('End Time: ', new moment().format("HH:mm:ss"));
  36.  
  37. if (failedObjects.events.length || failedObjects.venues.length || failedObjects.performers.length) {
  38. const stream = fs.createWriteStream(filename);
  39. stream.once('open', function(fd) {
  40. stream.write(JSON.stringify(failedObjects));
  41. stream.end();
  42. });
  43. }
  44. });
  45. });
  46. };
  47.  
  48. function processVenues(venues, failedObjects, callback) {
  49. const calls = [];
  50.  
  51. for (let i = 0; i < venues.length; i++) {
  52. const v = venues[i];
  53.  
  54. calls.push(async.apply((venue, postCallback) => {
  55. const client = new Client();
  56. const args = {
  57. data: venue,
  58. headers: {"Content-Type": "application/json"}
  59. };
  60.  
  61. client.post('https://hm1br4yo34.execute-api.us-west-2.amazonaws.com/dev/eventful-venue', args, (data, response) => {
  62. if (response.statusCode !== 200 && response.statusCode !== 201) {
  63. failedObjects.venues.push({
  64. venue,
  65. response
  66. });
  67. console.log('venue status code: ', response);
  68. console.log('venue data: ', venue);
  69. }
  70. return postCallback(null);
  71. });
  72. }, v));
  73. }
  74.  
  75. async.waterfall(calls, callback);
  76. }
  77.  
  78. function processPerformers(performers, failedObjects, callback) {
  79. const calls = [];
  80.  
  81. for (let i = 0; i < performers.length; i++) {
  82. const v = performers[i];
  83.  
  84. calls.push(async.apply((performer, postCallback) => {
  85. const client = new Client();
  86. const args = {
  87. data: performer,
  88. headers: {"Content-Type": "application/json"}
  89. };
  90.  
  91. client.post('https://hm1br4yo34.execute-api.us-west-2.amazonaws.com/dev/eventful-performer', args, (data, response) => {
  92. if (response.statusCode !== 200 && response.statusCode !== 201) {
  93. failedObjects.performers.push({
  94. performer,
  95. response
  96. });
  97. console.log('performer status code: ', response);
  98. console.log('performer data: ', performer);
  99. }
  100. return postCallback(null);
  101. });
  102. }, v));
  103. }
  104.  
  105. async.waterfall(calls, callback);
  106. }
  107.  
  108. function processEvents(events, failedObjects, callback) {
  109. const calls = [];
  110.  
  111. for (let i = 0; i < events.length; i++) {
  112. const v = events[i];
  113.  
  114. calls.push(async.apply((event, postCallback) => {
  115. const client = new Client();
  116. const args = {
  117. data: event,
  118. headers: {"Content-Type": "application/json"}
  119. };
  120. client.post('https://hm1br4yo34.execute-api.us-west-2.amazonaws.com/dev/eventful', args, (data, response) => {
  121. if (response.statusCode !== 200 && response.statusCode !== 201) {
  122. failedObjects.events.push({
  123. event,
  124. response
  125. });
  126. console.log('event status code: ', response);
  127. console.log('event data: ', event);
  128. }
  129. return postCallback(null);
  130. });
  131. }, v));
  132. }
  133.  
  134. async.waterfall(calls, callback);
  135. }
  136.  
  137. if (!module.parent) {
  138. module.exports();
  139. }
  140.  
  141. const _ = require('lodash');
  142. const AWS = require('aws-sdk');
  143. const async = require('async');
  144. const sdk = require('@consultwithmikellc/withify-sdk');
  145.  
  146. const host = process.env.aurora_host;
  147. const user = process.env.aurora_user;
  148. const database = process.env.aurora_database;
  149. let decryptedPassword;
  150.  
  151. const lambda = new AWS.Lambda({
  152. region: 'us-west-2' //your region
  153. });
  154.  
  155. class WithifyEventCreate extends sdk.Lambda {
  156. constructor(event, context, keysToDecrypt) {
  157. super(event, context, keysToDecrypt);
  158.  
  159. this.getLocation = this.getLocation.bind(this);
  160. this.insertLocations = this.insertLocations.bind(this);
  161. this.insertLocationImages = this.insertLocationImages.bind(this);
  162. }
  163.  
  164. decryptedKey(key, value) {
  165. switch (key) {
  166. case 'aurora_password':
  167. decryptedPassword = value;
  168. break;
  169. }
  170. }
  171.  
  172. initializeComplete() {
  173. this.connect(host, user, decryptedPassword, database, true);
  174. }
  175.  
  176. connectComplete() {
  177. async.waterfall(
  178. [
  179. this.getLocation,
  180. this.insertLocations,
  181. this.insertLocationImages
  182. ]
  183. );
  184. }
  185.  
  186. getLocation(callback) {
  187. const {id: eventfulLocationID} = this.body;
  188.  
  189. this.connection.query('SELECT * FROM `Location` WHERE `eventfulLocationID` = ?',
  190. [eventfulLocationID],
  191. (err, results) => {
  192. if (err) {
  193. // error call block
  194. return this.sendResponse(err, this.createResponse(500));
  195. } else if (results.length === 1) {
  196. console.log('Invoking withify-eventful-venue-update...');
  197. lambda.invoke({
  198. FunctionName: 'withify-eventful-venue-update',
  199. Payload: JSON.stringify(this.event)
  200. }, (error, data) => {
  201. return this.sendResponse(null, JSON.parse(data.Payload));
  202. });
  203. } else if (results.length > 1) {
  204. return this.sendResponse(`The location lookup produced multiple results. event:${JSON.stringify(this.body)}`, this.createResponse(500));
  205. } else {
  206. return callback(null);
  207. }
  208. }
  209. );
  210. }
  211.  
  212. insertLocations(callback) {
  213. const {name: locationName, address: street, city, region_abbr: state, postal_code,
  214. description, id: eventfulLocationID, latitude: lat, longitude: lng, withdrawn: locationWithdrawn} = this.body;
  215. let addresses = street.concat(', ', city, ', ', state, ', ', postal_code);
  216.  
  217. if (!description.length){
  218. var phones = "";
  219. }else{
  220. var re = /(([(][0-9]{3}[)][s][0-9]{3}[-][0-9]{4})|([0-9]{3}[-][0-9]{3}[-][0-9]{4})|([0-9]{3}[.][0-9]{3}[.][0-9]{4}))/i;
  221. this.body.found = description.match(re);
  222.  
  223. if (!this.body.found){
  224. var phone = "";
  225. }else{
  226. if (!this.body.found.length){
  227. var phone = "";
  228. }else{
  229. var phone = this.body.found[0];
  230. }
  231. }
  232. }
  233. this.connection.query('INSERT IGNORE INTO `Location` (`locationName`, `address`, ' +
  234. '`phone`, `lat`, `lng`, `eventfulLocationID`, `locationWithdrawn`) VALUES (?, ?, ?, ?, ?, ?, ?)',
  235. [locationName, addresses, phone, lat, lng, eventfulLocationID, locationWithdrawn],
  236. (err, results) => {
  237. if (err) {
  238. return this.sendResponse(err, this.createResponse(500));
  239. }
  240.  
  241. this.body.locationID = results.insertId;
  242. return callback(null);
  243. }
  244. );
  245. }
  246.  
  247. insertLocationImages(callback) {
  248. var altText = "";
  249. const images = _.flatten(this.body.images.map(im => {
  250. return _.map(im.sizes, (ims, idx) => {
  251. const title = `Image ${idx}`;
  252.  
  253. return [
  254. this.body.locationID,
  255. this.body.name,
  256. ims.url,
  257. null,
  258. null,
  259. this.body.id,
  260. ims.width,
  261. ims.height
  262. ];
  263. });
  264. }));
  265. if(!images[0]){
  266. return this.sendResponse(null, this.createResponse(201, this.body));
  267. }
  268. this.connection.query('INSERT IGNORE INTO `LocationImage` (`locationID`, `imageTitle`, `imageUrl`, ' +
  269. '`imageName`, `altText`, `eventfulLocationID`, `width`, `height`) VALUES ?',
  270. [images],
  271. (err, results) => {
  272. if (err) {
  273. return this.sendResponse(err, this.createResponse(500));
  274. } else if (results.affectedRows !== images.length) {
  275. return this.sendResponse('The image inserts did not affect the right number' +
  276. ' of rows.', this.createResponse(500));
  277. }
  278.  
  279. return this.sendResponse(null, this.createResponse(201, this.body));
  280. }
  281. );
  282. }
  283. }
  284.  
  285. exports.handler = (event, context) => {
  286. const withifyEventCreate = new WithifyEventCreate(event, context, ['aurora_password']);
  287. withifyEventCreate.initialize([decryptedPassword]);
  288. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement