BVB Source Codes

parse-server Show StatusHandler.js Source code

Return Download parse-server: download StatusHandler.js Source code - Download parse-server Source code - Type:.js
  1. import { md5Hash, newObjectId } from './cryptoUtils';
  2. import { logger }               from './logger';
  3.  
  4. const PUSH_STATUS_COLLECTION = '_PushStatus';
  5. const JOB_STATUS_COLLECTION = '_JobStatus';
  6.  
  7. const incrementOp = function(object = {}, key, amount = 1) {
  8.   if (!object[key]) {
  9.     object[key] = {__op: 'Increment', amount: amount}
  10.   } else {
  11.     object[key].amount += amount;
  12.   }
  13.   return object[key];
  14. }
  15.  
  16. export function flatten(array) {
  17.   var flattened = [];
  18.   for(var i = 0; i < array.length; i++) {
  19.     if(Array.isArray(array[i])) {
  20.       flattened = flattened.concat(flatten(array[i]));
  21.     } else {
  22.       flattened.push(array[i]);
  23.     }
  24.   }
  25.   return flattened;
  26. }
  27.  
  28. function statusHandler(className, database) {
  29.   let lastPromise = Promise.resolve();
  30.  
  31.   function create(object) {
  32.     lastPromise = lastPromise.then(() => {
  33.       return database.create(className, object).then(() => {
  34.         return Promise.resolve(object);
  35.       });
  36.     });
  37.     return lastPromise;
  38.   }
  39.  
  40.   function update(where, object) {
  41.     lastPromise = lastPromise.then(() => {
  42.       return database.update(className, where, object);
  43.     });
  44.     return lastPromise;
  45.   }
  46.  
  47.   return Object.freeze({
  48.     create,
  49.     update
  50.   })
  51. }
  52.  
  53. export function jobStatusHandler(config) {
  54.   let jobStatus;
  55.   const objectId = newObjectId();
  56.   const database = config.database;
  57.   const handler = statusHandler(JOB_STATUS_COLLECTION, database);
  58.   const setRunning = function(jobName, params) {
  59.     const now = new Date();
  60.     jobStatus = {
  61.       objectId,
  62.       jobName,
  63.       params,
  64.       status: 'running',
  65.       source: 'api',
  66.       createdAt: now,
  67.       // lockdown!
  68.       ACL: {}
  69.     }
  70.  
  71.     return handler.create(jobStatus);
  72.   }
  73.  
  74.   const setMessage = function(message) {
  75.     if (!message || typeof message !== 'string') {
  76.       return Promise.resolve();
  77.     }
  78.     return handler.update({ objectId }, { message });
  79.   }
  80.  
  81.   const setSucceeded = function(message) {
  82.     return setFinalStatus('succeeded', message);
  83.   }
  84.  
  85.   const setFailed = function(message) {
  86.     return setFinalStatus('failed', message);
  87.   }
  88.  
  89.   const setFinalStatus = function(status, message = undefined) {
  90.     const finishedAt = new Date();
  91.     const update = { status, finishedAt };
  92.     if (message && typeof message === 'string') {
  93.       update.message = message;
  94.     }
  95.     return handler.update({ objectId }, update);
  96.   }
  97.  
  98.   return Object.freeze({
  99.     setRunning,
  100.     setSucceeded,
  101.     setMessage,
  102.     setFailed
  103.   });
  104. }
  105.  
  106. export function pushStatusHandler(config, objectId = newObjectId()) {
  107.  
  108.   let pushStatus;
  109.   const database = config.database;
  110.   const handler = statusHandler(PUSH_STATUS_COLLECTION, database);
  111.   const setInitial = function(body = {}, where, options = {source: 'rest'}) {
  112.     const now = new Date();
  113.     let pushTime = new Date();
  114.     let status = 'pending';
  115.     if (body.hasOwnProperty('push_time')) {
  116.       if (config.hasPushScheduledSupport) {
  117.         pushTime = body.push_time;
  118.         status = 'scheduled';
  119.       } else {
  120.         logger.warn('Trying to schedule a push while server is not configured.');
  121.         logger.warn('Push will be sent immediately');
  122.       }
  123.     }
  124.  
  125.     const data =  body.data || {};
  126.     const payloadString = JSON.stringify(data);
  127.     let pushHash;
  128.     if (typeof data.alert === 'string') {
  129.       pushHash = md5Hash(data.alert);
  130.     } else if (typeof data.alert === 'object') {
  131.       pushHash = md5Hash(JSON.stringify(data.alert));
  132.     } else {
  133.       pushHash = 'd41d8cd98f00b204e9800998ecf8427e';
  134.     }
  135.     const object = {
  136.       objectId,
  137.       createdAt: now,
  138.       pushTime: pushTime.toISOString(),
  139.       query: JSON.stringify(where),
  140.       payload: payloadString,
  141.       source: options.source,
  142.       title: options.title,
  143.       expiry: body.expiration_time,
  144.       status: status,
  145.       numSent: 0,
  146.       pushHash,
  147.       // lockdown!
  148.       ACL: {}
  149.     }
  150.  
  151.     return handler.create(object).then(() => {
  152.       pushStatus = {
  153.         objectId
  154.       };
  155.       return Promise.resolve(pushStatus);
  156.     });
  157.   }
  158.  
  159.   const setRunning = function(count) {
  160.     logger.verbose(`_PushStatus ${objectId}: sending push to %d installations`, count);
  161.     return handler.update({status:"pending", objectId: objectId},
  162.         {status: "running", updatedAt: new Date(), count });
  163.   }
  164.  
  165.   const trackSent = function(results) {
  166.     const update = {
  167.       updatedAt: new Date(),
  168.       numSent: 0,
  169.       numFailed: 0
  170.     };
  171.     if (Array.isArray(results)) {
  172.       results = flatten(results);
  173.       results.reduce((memo, result) => {
  174.         // Cannot handle that
  175.         if (!result || !result.device || !result.device.deviceType) {
  176.           return memo;
  177.         }
  178.         const deviceType = result.device.deviceType;
  179.         const key = result.transmitted ? `sentPerType.${deviceType}` : `failedPerType.${deviceType}`;
  180.         memo[key] = incrementOp(memo, key);
  181.         if (result.transmitted) {
  182.           memo.numSent++;
  183.         } else {
  184.           memo.numFailed++;
  185.         }
  186.         return memo;
  187.       }, update);
  188.       incrementOp(update, 'count', -results.length);
  189.     }
  190.  
  191.     logger.verbose(`_PushStatus ${objectId}: sent push! %d success, %d failures`, update.numSent, update.numFailed);
  192.  
  193.     ['numSent', 'numFailed'].forEach((key) => {
  194.       if (update[key] > 0) {
  195.         update[key] = {
  196.           __op: 'Increment',
  197.           amount: update[key]
  198.         };
  199.       } else {
  200.         delete update[key];
  201.       }
  202.     });
  203.  
  204.     return handler.update({ objectId }, update).then((res) => {
  205.       if (res && res.count === 0) {
  206.         return this.complete();
  207.       }
  208.     })
  209.   }
  210.  
  211.   const complete = function() {
  212.     return handler.update({ objectId }, {
  213.       status: 'succeeded',
  214.       count: {__op: 'Delete'},
  215.       updatedAt: new Date()
  216.     });
  217.   }
  218.  
  219.   const fail = function(err) {
  220.     const update = {
  221.       errorMessage: JSON.stringify(err),
  222.       status: 'failed',
  223.       updatedAt: new Date()
  224.     }
  225.     logger.warn(`_PushStatus ${objectId}: error while sending push`, err);
  226.     return handler.update({ objectId }, update);
  227.   }
  228.  
  229.   return Object.freeze({
  230.     objectId,
  231.     setInitial,
  232.     setRunning,
  233.     trackSent,
  234.     complete,
  235.     fail
  236.   })
  237. }
  238.  
downloadStatusHandler.js Source code - Download parse-server Source code
Related Source Codes/Software:
react-boilerplate - 2017-06-07
webtorrent - Streaming torrent client for the web ... 2017-06-06
machine-learning-for-software-engineers - A complete daily plan for studying to become a mac... 2017-06-06
upterm - A terminal emulator for the 21st century. 2017-06-06
lottie-android - Render After Effects animations natively on Androi... 2017-06-07
AsyncDisplayKit - Smooth asynchronous user interfaces for iOS apps. ... 2017-06-07
ionicons - The premium icon font for Ionic ... 2017-06-07
storybook - 2017-06-07
prettier - Prettier is an opinionated JavaScript formatter. ... 2017-06-08
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top