Guest User

Untitled

a guest
Jan 10th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.27 KB | None | 0 0
  1. const Request = require( 'request-promise-native' );
  2. const _ = require( 'lodash' );
  3. const Pry = require( 'pryjs' );
  4.  
  5. var keymakerClient = process.env[ 'KEYMAKER_CLIENT' ];
  6. var keymakerSecret = process.env[ 'KEYMAKER_SECRET' ];
  7. var keymakerUrl = process.env[ 'UNIMATRIX_AUTHORIZATION_API_URL' ];
  8. var unimatrixUrl = process.env[ 'UNIMATRIX_API_URL' ]
  9.  
  10. var accessToken = null;
  11.  
  12. function operation( verb, entity, options ){
  13. return new Promise( ( resolve, reject ) => {
  14. var request = {
  15. url: unimatrixUrl + "/realms/" + options.realmUuid + "/" + entity,
  16. method: verb,
  17. json: true
  18. }
  19.  
  20. request[ 'qs' ] = _.merge(
  21. _.get( options, 'query', {} ),
  22. { 'access_token': accessToken.token }
  23. )
  24.  
  25. if ( _.has( options, "body" )) {
  26. request[ 'body' ] = options.body
  27. }
  28.  
  29. if ( _.has( options, "url" )) {
  30. request[ 'url' ] = options.url
  31. }
  32.  
  33. Request( request )
  34. .then(( body ) => {
  35. if ( isValid( body ) ){
  36.  
  37. if ( isBlank( entity, body ) ) {
  38. body[ entity ] = []
  39. }
  40.  
  41. resolve( body )
  42. }
  43. else {
  44. console.log ( "Unimatrix operation response not valid: " + body )
  45. reject( body );
  46.  
  47. }
  48. })
  49.  
  50. .catch( ( error ) => {
  51. reject( error );
  52. })
  53. })
  54. }
  55.  
  56. function isBlank( entity_type, response ) {
  57. response = response[ '$this' ]
  58. return ( response.name == entity_type && response.unlimited_count == 0 )
  59. }
  60.  
  61. function isValid( response ) {
  62. return ( ( _.has( response, '$this' ) ) &&
  63. ( !_.has( response, 'errors' ) || response[ 'errors' ] == [] ))
  64. }
  65.  
  66. module.exports = {
  67. Operation: {
  68.  
  69. //Options hash example:
  70. //{
  71. //"batchSize": 1, //optional
  72. //"query": { //optional
  73. //"type_name": "schedule_episode_artifact",
  74. //"language": "es",
  75. //"uuid": "acc015a4c70821265a0a67df3fab6ac0"
  76. //},
  77. //"body": { //optional
  78. //"name": "Las Rosas del Milagro"
  79. //}
  80. //}
  81.  
  82. read: function read( entity, options ){
  83. var collatedResponse = [];
  84. var batchSize = _.get( options, 'batchSize', 1 )
  85. var total;
  86.  
  87. //Stash all response data in options obj. so that it can be passed to each iteration of read()
  88. if( _.has( options, "collatedResponse" )){
  89. collatedResponse = options.collatedResponse
  90. delete options.collatedResponse
  91. }
  92.  
  93. options.realmUuid = this.realmUuid
  94. options.query.count = batchSize
  95.  
  96. return operation( "GET", entity, options )
  97. .then( ( body ) => {
  98. return new Promise( ( resolve, reject ) => {
  99. var count = body[ '$this' ][ 'count' ]
  100. var offset = body[ '$this' ][ 'offset' ]
  101.  
  102. total = body[ '$this' ][ 'unlimited_count' ]
  103.  
  104. var response = {}
  105.  
  106. if ( _.has( options, "query.include" ) ){
  107. //Response is an object with all included entities as separate keys
  108. response[ entity ] = body[ entity ]
  109.  
  110. _.mapKeys( options.query.include, ( v, k ) => {
  111. response[ k ] = body[ k ]
  112. })
  113. } else {
  114. //Response is the entity directly as an array
  115. response = body[ entity ]
  116. }
  117.  
  118. collatedResponse = _.concat( collatedResponse, response )
  119.  
  120. if( offset < total - 1 && offset + count < total ) {
  121. options.query.offset = offset + batchSize
  122. options.collatedResponse = collatedResponse
  123.  
  124. resolve( read( entity, options ))
  125. } else {
  126. resolve( collatedResponse )
  127. }
  128. })
  129. })
  130. },
  131.  
  132. write: function write( entity, options ){
  133. var collatedResponse = [];
  134. var batchSize = _.get( options, 'batchSize', 1 )
  135.  
  136. options.realmUuid = this.realmUuid
  137.  
  138. //Stash all segments and current segment count in options obj. so that it can be passed to each iteration of write()
  139. if( !_.has( options, "segments" )){
  140. options.segments = _.chunk( options.body[ entity ], batchSize )
  141. options.currentSegment = 0
  142. }
  143.  
  144. //Stash all response data in options obj. so that it can be passed to each iteration of write()
  145. if( _.has( options, "collatedResponse" )){
  146. collatedResponse = options.collatedResponse
  147. delete options.collatedResponse
  148. }
  149.  
  150. options.body[ entity ] = options.segments[ options.currentSegment ]
  151.  
  152. return operation( "POST", entity, options )
  153. .then( ( body ) => {
  154. return new Promise( ( resolve, reject ) => {
  155. collatedResponse = _.concat( collatedResponse, body[ entity ])
  156.  
  157. if( options.currentSegment < options.segments.length - 1 ) {
  158. options.collatedResponse = collatedResponse
  159. options.currentSegment += 1
  160.  
  161. resolve( write( entity, options ))
  162. } else {
  163. resolve( collatedResponse )
  164.  
  165. }
  166. })
  167. })
  168. .catch( ( error ) => {
  169. console.log ( "Unimatrix operation error: " + error )
  170. reject( error );
  171.  
  172. })
  173.  
  174.  
  175. },
  176.  
  177. remove: function remove( entity, options ){
  178. options.realmUuid = this.realmUuid
  179.  
  180. return operation( "DELETE", entity, options )
  181. .then( ( body ) => {
  182. return new Promise( ( resolve, reject ) => {
  183. resolve( body )
  184.  
  185. })
  186. })
  187. .catch( ( error ) => {
  188. console.log ( "Unimatrix operation error: " + error )
  189. reject( error );
  190.  
  191. })
  192. }
  193. },
  194.  
  195. getAccessToken: function() {
  196. return new Promise( ( resolve, reject ) => {
  197. if ( accessToken &&
  198. ( accessToken.expiry == undefined || accessToken.expiry > new Date() )) {
  199.  
  200. resolve( accessToken );
  201.  
  202. } else {
  203.  
  204. var request = {
  205. url: keymakerUrl + '/token?grant_type=client_credentials',
  206. method: 'POST',
  207. auth: {
  208. user: keymakerClient,
  209. pass: keymakerSecret
  210. }
  211. }
  212.  
  213. Request( request )
  214. .then(( body ) => {
  215. var body = JSON.parse( body );
  216. var expiry;
  217.  
  218. if ( _.has( body, "expires_in" )) {
  219. expiry = new Date( new Date().getTime() + ( body.expires_in * 1000 ) );
  220. }
  221.  
  222. accessToken = {
  223. token: body.access_token,
  224. expiry: expiry
  225. };
  226.  
  227. resolve( accessToken );
  228.  
  229. })
  230. .catch(( error ) => {
  231. console.log ( "ERROR: " + error )
  232. reject( error );
  233.  
  234. })
  235. }
  236. })
  237. },
  238.  
  239. parseMessage: function( message ) {
  240. return new Promise( ( resolve, reject ) => {
  241. var result = null;
  242.  
  243. try {
  244. result = JSON.parse( message );
  245.  
  246. } catch( error ) {
  247. reject( error )
  248.  
  249. }
  250.  
  251. resolve( result );
  252. })
  253. },
  254.  
  255. terminateLambda: function( result, context ){
  256. return new Promise( ( resolve, reject ) => {
  257. if ( result == null ) {
  258. //Ignore message
  259. context.succeed();
  260. resolve()
  261.  
  262. } else {
  263. console.log( "INFO: Lambda has successfully completed processing..." )
  264. context.succeed();
  265. resolve()
  266.  
  267. }
  268. })
  269. }
  270.  
  271. }
Add Comment
Please, Sign In to add comment