Mocking AJAX responses by using a Media type string

When you want to test how your code handles API requests, or any AJAX requests – you will most likely find yourself in a situation where you don’t actually test the code responsible for the request, but just a “hardcoded” response that you provide in the code.

it might look like that:

if (testEnv) {
    doSomethingWithTheResponse({
        foo: 'bar'
    });
} else {
    $.get('/api/get_response_url').success(function(res) {
        doSomethingWithTheResponse(res)});
    }
}

in most cases it will do just fine – but what if there is a complex and crucial functionality within the .success callback?

the answer would be: Mock AJAX response while preserving the actual request code block. like this:

var url = '/api/get_response_url';

if (testEnv) {
    url = 'data:application/json,{"foo":"bar"}';
}

$.get(url).success(function(res) {
    doSomethingWithTheResponse(res);
});

in the above example we are setting the request url to be a media type string, which consists of:

  • top level type: data
  • type: application
  • subtype: json
  • parameters: {“foo”: “bar”}

you can read more about media types and their syntax here.

The request we do now returns what it has in the media type parameter – which is a completely valid, actual AJAX request with our mock response.

JavaScript events debugging with monitorEvents()

A fancy method to debug JS events, and log all or some of them.

simply call the monitorEvents() function in your JS console, and you will see the events flow.

monitorEvents(document.getElementById('monitor-me'), 'click');

monitorEvents

the first argument is the object to monitor, and the second argument is the optional filter. for example – show only click events.

to unbind the listener, you can use unmonitorEvents(document.getElementById(‘monitor-me’))

Maintain cursor position after changing an input value programatically

Sometimes you want to programatically change an input value, like in a case of input validation.
replacing an input value is easy, but has a common drawback – the cursor position will reset.

to overcome it, we can use this simple JS snippet:


function handleInputValueChange(e) {

    var cursorStart = e.target.selectionStart,
        cursorEnd = e.target.selectionEnd;

        // value manipulations...

    e.target.setSelectionRange(cursorStart, cursorEnd);
}

* note that this specific snippet relies on passing an event, onChange for instance.

setState not being updated on time

Say you have two functions in your React app that call setState(), and are dependant one on the other. you might stumble upon a case where the second function excepts to have the new state – but doesn’t.

That happens because setState() doesn’t immediately mutate the state (this.state) but creates a pending state transition. therefore, accessing this.state might return the existing value.

to overcome this, this.setState supports a callback function to be triggered once it’s been updated.

this.setState(newStateObj, () => {});

React, Redux and WebPack environment config

A brief description of the project at hand:

The task is to move existing sections that were built on top of RoR, with assets served with the rails asset pipeline. the files should be completely independent, loaded in a smart & efficient way.

The stack we decided to use was React with Redux, and Webpack as our build tool.

Folder & file structure

At first we started working with the standard redux structure, that goes like this:

folder-structure-1

It felt like a good start, because everything, literally – was in one place. all reducers, all actions, all components – in one place. it was quite easy to kick start and dive into work.

but, as the application grew, and more components were added, we reached to a point where the navigation in the code became complex and time consuming.
at this point we decided to look for a better solution.

The best solution we found for our needs was to use what’s called a folder by domain/feature structure, which looks like this:

folder-structure-2

Inspired by this lovely article.

It allows us to better consolidate components, and their respective actions, reducers and constants. basically a complete separation of mostly independent components.

Another perk by using this approach – the navigation in your IDE became much easier, and you don’t have to rely on seeing in which directory your file is located.

Building the webpack.config file(s).

  1. entry & output
    Because we need to work on multiple sections that will be built with react, and we don’t want to configure same settings over and over, we want webpack to output a dependencies file, and section file(s).

dependencies file – will hold any cross section relevant dependancies, like react, react-dom, react-router, isomorphic-fetch, etc.
section file(s) – each file will be name as react-<section>.js and will hold only it’s section relevant code.

entry: {
    killer_feature: './src/killer-feature/router',
    dependencies: [
        'react',
        'react-dom',
        'react-router',
        'redux',
        'react-redux',
        'redux-thunk',
        'immutable',
        'es6-promise',
        'isomorphic-fetch',
        'history/lib/createBrowserHistory'
    ]
},
output: {
    path: './build/',
    filename: "react-[name].js.erb"
}

The snippet above contains these entry points:
“killer_feature” – a section file entry point, in our case it’s the router config file that handles the killer_feature’s routes
“dependencies” – a list of all global modules that will be used by all other sections, like our killer_feature

and the output will be:
react-killer_feature.js.erb
react-dependencies.js.erb

* note the .js.erb suffix – it’s ruby on rails file, that outputs as an ordinary .js file

 

2. externals configuration

externals are modules that we don’t want to include in our webpack build, but we do want it to be accessible from within our modules.
in my case I need lodash to be external, as it’s already being loaded in the rails app (not covered here)

externals: {
    'lodash': '_'
} 

the ‘_’ is the object name by whom it will be referenced.

3. WebPack plugins

List of plugins that are used to optimize webpack’s output.

plugins: [
     new webpack.ProvidePlugin({
         React: 'react',
         ReactDOM: 'react-dom',
         ReactRouter: 'react-router',
         ReactRedux: 'react-redux',
         Redux: 'redux',
         ReduxThunk: 'redux-thunk',
         Immutable: 'immutable',
         fetch: 'isomorphic-fetch',
         Autocomplete: 'react-autocomplete'
     }),
     new webpack.DefinePlugin({
         'process.env': {
             'NODE_ENV': JSON.stringify('production')
         }
     }),
     new webpack.optimize.OccurrenceOrderPlugin(),
     new webpack.optimize.DedupePlugin(),
     new webpack.optimize.CommonsChunkPlugin({
         name: 'dependencies',
         minChunks: Infinity
     }),
     new webpack.optimize.UglifyJsPlugin({
         test: /\.js\.erb/i,
         output: {
             quote_style: 3 
         },
         compressor: {
             warnings: false
         }
     })
 ] 

a few words about the used plugins:

ProvidePlugin – allows us to provide the modules in the list as plugins, available globally in any file, instead of requiring them every time at the top of each file. we do that for our dependancies files. (not recommended to use for non globally used files).
DefinePlugin – defines a global variable, that holds our NODE_ENV var. to be used to separate production/dev/test builds for instance.

OccurrenceOrderPlugin –  Assign the module and chunk ids by occurrence count. Ids that are used often get lower (shorter) ids. This make ids predictable, reduces to total file size and is recommended.

DedupePlugin – Search for equal or similar files and deduplicate them in the output.
CommonsChunkPlugin – Allows webpack to determine commonly used chunks of code, and pull them into a single separate file.

UglifyJsPlugin – Minifies & uglifies the output, reduces the output size drastically.

for further reference, check this doc: https://webpack.github.io/docs/list-of-plugins.html

Geekcon Pets Hackathon 2016

On Feb. 19-20, 2016, once again – I was lucky enough to participate in Geekcon Pets Hackathon.

This hackathon did not revolve around prize(s), but rather pure fun experience to try and conceive a product that somehow will help pets and their owners.

The team & The product

We were a team of 5; Liat, Natanel, Elad, Rafi & I.

And the product we decided to work on, was a smart collar that will sound an alarming sound, or the dog’s owner’s voice, whenever the dog gets near “forbidden” areas – a sofa for example. or your slippers.

We decided to call it the NoGo Collar.

Most of us had very little experience with physical products development & Arduino, so in terms of learning new tech – it was a blast!

NoGo-collar-logo

Tech behind the NoGo Collar

We used Arduino as our main board, on top of it we used NFC shield, an SD card reader, an external scrap speaker and a bunch of Passive tags to trigger the alarm.

IMG_0532

And to wrap it all up, we used a 3d printed fancy packing.

We had a lot of fun during this experience, and you can judge it yourself by the pics & the video attached!

IMG_0523