Skip to content

Instantly share code, notes, and snippets.

@jacksonsouza
Created January 9, 2019 22:10
Show Gist options
  • Save jacksonsouza/059e8c81e8a4e62aaca5e80c2d8837a9 to your computer and use it in GitHub Desktop.
Save jacksonsouza/059e8c81e8a4e62aaca5e80c2d8837a9 to your computer and use it in GitHub Desktop.
code_sample.js
const Request = require( 'request-promise-native' );
const _ = require( 'lodash' );
const Pry = require( 'pryjs' );
var keymakerClient = process.env[ 'KEYMAKER_CLIENT' ];
var keymakerSecret = process.env[ 'KEYMAKER_SECRET' ];
var keymakerUrl = process.env[ 'UNIMATRIX_AUTHORIZATION_API_URL' ];
var unimatrixUrl = process.env[ 'UNIMATRIX_API_URL' ]
var accessToken = null;
function operation( verb, entity, options ){
return new Promise( ( resolve, reject ) => {
var request = {
url: unimatrixUrl + "/realms/" + options.realmUuid + "/" + entity,
method: verb,
json: true
}
request[ 'qs' ] = _.merge(
_.get( options, 'query', {} ),
{ 'access_token': accessToken.token }
)
if ( _.has( options, "body" )) {
request[ 'body' ] = options.body
}
if ( _.has( options, "url" )) {
request[ 'url' ] = options.url
}
Request( request )
.then(( body ) => {
if ( isValid( body ) ){
if ( isBlank( entity, body ) ) {
body[ entity ] = []
}
resolve( body )
}
else {
console.log ( "Unimatrix operation response not valid: " + body )
reject( body );
}
})
.catch( ( error ) => {
reject( error );
})
})
}
function isBlank( entity_type, response ) {
response = response[ '$this' ]
return ( response.name == entity_type && response.unlimited_count == 0 )
}
function isValid( response ) {
return ( ( _.has( response, '$this' ) ) &&
( !_.has( response, 'errors' ) || response[ 'errors' ] == [] ))
}
module.exports = {
Operation: {
//Options hash example:
//{
//"batchSize": 1, //optional
//"query": { //optional
//"type_name": "schedule_episode_artifact",
//"language": "es",
//"uuid": "acc015a4c70821265a0a67df3fab6ac0"
//},
//"body": { //optional
//"name": "Las Rosas del Milagro"
//}
//}
read: function read( entity, options ){
var collatedResponse = [];
var batchSize = _.get( options, 'batchSize', 1 )
var total;
//Stash all response data in options obj. so that it can be passed to each iteration of read()
if( _.has( options, "collatedResponse" )){
collatedResponse = options.collatedResponse
delete options.collatedResponse
}
options.realmUuid = this.realmUuid
options.query.count = batchSize
return operation( "GET", entity, options )
.then( ( body ) => {
return new Promise( ( resolve, reject ) => {
var count = body[ '$this' ][ 'count' ]
var offset = body[ '$this' ][ 'offset' ]
total = body[ '$this' ][ 'unlimited_count' ]
var response = {}
if ( _.has( options, "query.include" ) ){
//Response is an object with all included entities as separate keys
response[ entity ] = body[ entity ]
_.mapKeys( options.query.include, ( v, k ) => {
response[ k ] = body[ k ]
})
} else {
//Response is the entity directly as an array
response = body[ entity ]
}
collatedResponse = _.concat( collatedResponse, response )
if( offset < total - 1 && offset + count < total ) {
options.query.offset = offset + batchSize
options.collatedResponse = collatedResponse
resolve( read( entity, options ))
} else {
resolve( collatedResponse )
}
})
})
},
write: function write( entity, options ){
var collatedResponse = [];
var batchSize = _.get( options, 'batchSize', 1 )
options.realmUuid = this.realmUuid
//Stash all segments and current segment count in options obj. so that it can be passed to each iteration of write()
if( !_.has( options, "segments" )){
options.segments = _.chunk( options.body[ entity ], batchSize )
options.currentSegment = 0
}
//Stash all response data in options obj. so that it can be passed to each iteration of write()
if( _.has( options, "collatedResponse" )){
collatedResponse = options.collatedResponse
delete options.collatedResponse
}
options.body[ entity ] = options.segments[ options.currentSegment ]
return operation( "POST", entity, options )
.then( ( body ) => {
return new Promise( ( resolve, reject ) => {
collatedResponse = _.concat( collatedResponse, body[ entity ])
if( options.currentSegment < options.segments.length - 1 ) {
options.collatedResponse = collatedResponse
options.currentSegment += 1
resolve( write( entity, options ))
} else {
resolve( collatedResponse )
}
})
})
.catch( ( error ) => {
console.log ( "Unimatrix operation error: " + error )
reject( error );
})
},
remove: function remove( entity, options ){
options.realmUuid = this.realmUuid
return operation( "DELETE", entity, options )
.then( ( body ) => {
return new Promise( ( resolve, reject ) => {
resolve( body )
})
})
.catch( ( error ) => {
console.log ( "Unimatrix operation error: " + error )
reject( error );
})
}
},
getAccessToken: function() {
return new Promise( ( resolve, reject ) => {
if ( accessToken &&
( accessToken.expiry == undefined || accessToken.expiry > new Date() )) {
resolve( accessToken );
} else {
var request = {
url: keymakerUrl + '/token?grant_type=client_credentials',
method: 'POST',
auth: {
user: keymakerClient,
pass: keymakerSecret
}
}
Request( request )
.then(( body ) => {
var body = JSON.parse( body );
var expiry;
if ( _.has( body, "expires_in" )) {
expiry = new Date( new Date().getTime() + ( body.expires_in * 1000 ) );
}
accessToken = {
token: body.access_token,
expiry: expiry
};
resolve( accessToken );
})
.catch(( error ) => {
console.log ( "ERROR: " + error )
reject( error );
})
}
})
},
parseMessage: function( message ) {
return new Promise( ( resolve, reject ) => {
var result = null;
try {
result = JSON.parse( message );
} catch( error ) {
reject( error )
}
resolve( result );
})
},
terminateLambda: function( result, context ){
return new Promise( ( resolve, reject ) => {
if ( result == null ) {
//Ignore message
context.succeed();
resolve()
} else {
console.log( "INFO: Lambda has successfully completed processing..." )
context.succeed();
resolve()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment