Friday, September 29, 2017

Javascript/React project template

After doing our first big React SPA (Single Page Application) I decided to take all the project setup out and make a template project from it.   So for future projects we just unzip the project into our repository and we can start programming.

Github React Template

Here's the synopsis from the README.md

react-redux-template

Base template for enterprise react-redux projects with feature based layout. Includes setup for the following:
  • React
  • Redux with sagas
  • React-Router v4
  • SASS CSS processing
    • Global variables
    • File per component layout
  • Feature based layout - directory for each feature
    • Container
    • Styles
    • Actions & Constants
    • Reducer
    • Saga
  • Express Server
    • Public folder for security
    • Route controllers
    • HTTPS with default key
    • Async/Await syntax
    • Winston logging
      • Log level modification service
      • Logging setup parameters including automatic file rotation/deletion
    • Multi-threading
    • Hot reloading client code in dev mode
    • Hot reloading server code in dev mode
  • Production ready webpack with compression and latest javascript syntax

Wednesday, April 12, 2017

AWS config getCredentials as a promise

Getting AWS to work with async/await took some doing.   Finally have a nice little library using 
aws-sdk and aws-api-gateway-client.


// AWS API Gateway Setup - Test Inventory Callconst AWS = require('aws-sdk');
const apigClientFactory = require('aws-api-gateway-client');

const { INVENTORYLOOKUP } = appSettings.service_endpoints;

async function getAwsConfig() {
    return new Promise(function (resolve, reject) {
        AWS.config.getCredentials(async function(err) {
            if (err) {
                console.log('Error getting credentials', err);
                return reject(err);
            } else {
                resolve({
                    accessKey: AWS.config.credentials.accessKeyId,
                    secretKey: AWS.config.credentials.secretAccessKey,
                    sessionToken: AWS.config.credentials.sessionToken,
                    region: 'us-west-2'                });
            }
        });
    });
}

async function invokeAWS(targetURL, body) {

        let config = await getAwsConfig();
        config.invokeUrl = targetURL;

        console.log('config=', config);

        const apigClient = apigClientFactory.newClient(config);

        // config, url, method, header, body        let prom = apigClient.invokeApi({}, '/', 'POST', {
            'Content-Type': 'application/json',
            'Accept': 'application/json'        }, body);

        return prom;
    }
}

Monday, April 3, 2017

To the promised land, with async/await and Node 7

So you want to synchronously call asynchronous commands?   What?!?!?   But there are times when you do need to, such as stringing together dependent calls.   Request-Promise did make this a bit cleaner, but the code still gets messy.  This is where Node 7 and async/await come to save the day.

First, say we have 2 calls to request data, then 2 calls that need that data and need to be called in order.   I was able to solve this problem with request promise, but it is not ideal.   First, the very straightforward RP solution.

rp(restCall1)
    .then(function(response1) {
        // processCall1        })
    .catch(function(error) {
        // handle error from Call1    })

This is fine for a single call, but now make 2 calls, with the 2nd dependent on the 1st call.
rp(restCall1)
    .then(function(response1) {
        // processCall1        rp(restCall2)
            .then(function(response2) {
                // processCall2            })
            .catch(function(error2) {

            })
    })
    .catch(function(error1) {
        // handle error from Call1    })

That's managable, but getting messy.   Make 3 or 4 calls and it becomes an indentation nightmare.  You can unwind the nightmare a bit by using callback functions instead of putting them inline.

function processCall1(response1) {
    rp(restCall2).then(processCall2).catch(processError)
}

function processCall2(response2) {
    rp(restCall3).then(processCall3).catch(processError)
}

function processCall3(response2) {
    rp(restCall4).then(processCall4).catch(processError)
}

function processCall4(response4) {
    // Do final processing.}
    
function processError(error) {
    
}

rp(restCall1).then(processCall1).catch(processError1);

But now to show the process, you need to document carefully, name functions carefully and still when you go back and look at it, you have to really trace through each call to figure out what happens and in what order.   It's confusing and takes time if you wrote the code.   It's even harder if someone else is looking at the code.

Enter async and await.  You can wait for any promise.   You just need to make sure it's returned from the method you are calling.    The rp call returns the actual promise with rp().promise().   So now the code gets much simpler and more readable.

async function doComplicatedProcess(input) {
    try {
        let response1 = await processCall1(input);
        let response2 = await processCall2(response1);
        let response3 = await processCall3(response2);
        let response4 = await processCall4(response3);
    } catch (error) {
        console.log(error);
    }
}

async function processCall1(input) {
    return rp(restCall1).promise();
}

async function processCall2(response1) {
    return rp(restCall2).promise();
}

async function processCall3(response2) {
    return rp(restCall3).promise();
}

async function processCall4(response3) {
    return rp(restCall4).promise();
}
Now it reads like it is supposed to.   Do call 1, then 2, then 3, then 4.   Simple and easy.   Any function that returns a promise you can wait for with await.   Easier to understand also means easier to maintain.

Now what if process1 and process2 aren't needed until process4?  And they do take some time to execute?   Now we have the power to make our call even faster.
async function doComplicatedProcess(input) {
    try {
        let promise1 =  processCall1(input);
        let promise2 =  processCall2(input);
        let response3 = await processCall3(input);
        let [response1, response2] = await Promise.all([promise1, promise2]);
        let response4 = await processCall4(response1, response2);
    } catch (error) {
        console.log(error);
    }
}

async function processCall1(input) {
    return rp(restCall1).promise();
}

async function processCall2(input) {
    return rp(restCall2).promise();
}

async function processCall3(input) {
    return rp(restCall3).promise();
}

async function processCall4(response1, response2) {
    return rp(restCall4).promise();
}

Now call 1 and call 2 are processing while call 3 is being processed.   Then the await Promise.all makes sure call1 and call2 are done before going on to call 4.   It's a beautiful thing.   I reduced the average call time by 30% in my app which improved customer response time.   It also made it so that co-workers understand the code and what it's doing by looking, rather than having to trace through.

Thursday, July 21, 2016

OpenUI5 DataBinding and setModel(model) vs setModel(model, "myModel")

The data binding has been driving me crazy and I wasn't able to find an explanation of the different syntaxes used in many of the examples I've seen.

var model = new JSONModel({
   "isValid" : true
});

If I do this.getView().setModel(model), how is that different from this.getView().setModel(model, "myModel")?   How do I reference them from the xml view definition?

The setModel(model) version

When you do this.getView().setModel(model) it actually sets the data into the model in an "undefined" area of the model.  (Check in the browser debugger).   So when you reference it in the xml view, you use a system like:

<Text text="{isValid}"/>

It appears if you try and set 2 models this way, one will not be set and will be unavailable.

The setModel(model, "myModel") version

When you do this.getView().setModel(model, "myModel) you are now seting the data into the model with the "myModel" name.   So if you look in the browser debugger it will be nicely nested inside the view's model data structure.  So now to reference it you use the ">" notation to tell it to grab the named model instead of the generic one.  So it looks like this:

<Text text = "{myModel>/isValid}"/>

If you are referencing array data like in a list or table, then you drop the / after the > to make it a relative reference:

<Text text = "{myModel>isValid}"/>

Wednesday, May 18, 2016

OpenUI5 - Don't use console.log!

Sap has a built in logging functionality.   You can set your logging level and leave in all your log statements.

jQuery.sap.log.debug("onInit");
jQuery.sap.log.error("failed to get id");

Then you can set up your logging level in the javascript, so in dev/qa you could have:
jQuery.sap.log.setLevel(jQuery.sap.log.Level.DEBUG);
But in production, you can do:
jQuery.sap.log.setLevel(jQuery.sap.log.Level.NONE);

Friday, April 29, 2016

OpenUI5 - Data Binding a fragment from within the XML View definition

When using fragments I had terrible trouble finding how to bind the fragment to
my data from my XML view.  Every example showed the code binding version:
this._MyDialog.bindElement("/myData");

But when using a code fragment in an XML view I didn't want to have to 
bind it from the controller.  Finally I found the answer!

<VBox>
    <core:Fragment binding="{/billingAddress}" fragmentName="myApp.Address" type="XML"
                   id="billingAddress"
    />

    <core:Fragment binding="{/shippingAddress}" fragmentName="myApp.Address" type="XML"
                   id="shippingAddress"
    />
</VBox>


This links the fragment to the billingAddress in the view's Model.   Now 
everything in the fragment is relative to that link.  
Here is the fragment definition:

<core:FragmentDefinition
        xmlns:core="sap.ui.core"
        xmlns="sap.m">
                <VBox>
                    <Input
                            id="address"
                            value="{address}"
                            tooltip="Enter Street Address"
                    />
                    <Input
                            id="city"
                            value="{city}"
                            tooltip="Enter City"
                            description="City"
                    />
                    <Input
                            id="state"
                            value="{state}"
                            tooltip="Enter State"
                            description="State"
                    />
                </VBox>
</core:FragmentDefinition>

So when the fragment is shown on the screen, the first fragment will 
update the billingAddress object and the second fragment will update
 this shippingAddress object.

Thursday, April 28, 2016

OpenUI5 - Adding a background image to a Panel

<Panel    class="my-panel-background">
</Panel

Then in your CSS (you are using a CSS right?) Put

.my-panel-background {
    background-image: url('../background.jpg');
    background-repeat: no-repeat;
    background-size: contain;
    opacity: 1;
}

background-size: contain; will size the background to match your panel size

The URL entry is relative to your CSS file, so path accordingly.