<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oto Dočkal on Medium]]></title>
        <description><![CDATA[Stories by Oto Dočkal on Medium]]></description>
        <link>https://medium.com/@otodockal?source=rss-1ab92bccb23e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LxIVHE5aYdRyKbGK4Is43g.jpeg</url>
            <title>Stories by Oto Dočkal on Medium</title>
            <link>https://medium.com/@otodockal?source=rss-1ab92bccb23e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:59:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@otodockal/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cache invalidation in AngularJS]]></title>
            <link>https://medium.com/@otodockal/cache-invalidation-in-angularjs-7b72c5194122?source=rss-1ab92bccb23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b72c5194122</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Oto Dočkal]]></dc:creator>
            <pubDate>Wed, 20 Apr 2016 07:11:38 GMT</pubDate>
            <atom:updated>2016-04-22T11:12:19.354Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>AngularJS</strong> offers possibility of caching your requests and I want to simply demonstrate how to cache and delete resources and make invalidation correct on simple example…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31c2d36173b9a5a187418afe2a83e4aa/href">https://medium.com/media/31c2d36173b9a5a187418afe2a83e4aa/href</a></iframe><p><em>This is mostly pseudocode for easy demonstration. It is presumed previous injection of dollar($) methods etc. Code is written in ES2015.</em></p><h4>Use case</h4><blockquote><em>This can be an example of infinite scroll list with caching of items on offset 0 only. Cache is invalidated on ‘$destroy’ event.</em></blockquote><p>Imagine tree of components, components “cmp2.0” and “cmp2.1” are siblings and user can switch between each other. Both are lists of items with infinite scrolling. Components are also probably stateful and load resources by themselves. Resources are cached only on offset 0, otherwise cashing is turned off.</p><blockquote>Disclaimer: Make your components as stateless(pure) as possible! This is only demonstration of cache invalidation in AngularJS $http module.</blockquote><p>Each switch between sibling components without caching can cause new XHR and it doesn&#39;t have to be desirable like from UX as well as from API server perspective (but it depends on the use case of course). <strong>But</strong> when you navigate to completely different part of app like “cmp0.1”, cache should be invalidated, because data can be stale and also because of better memory mangement of our app.</p><p>So delete cache on “$destroy” event in parent component “cmp1.0” is the way. When you navigate back to sibling components (cmp2.0, cmp2.1), fresh data are loaded.</p><h4>And…</h4><p>As you can imagine cache invalidation is hard and it’s not hard to do it but when to do it. And it will be always hard because…</p><blockquote>There are only two hard things in Computer Science: cache invalidation and naming things.</blockquote><blockquote>— Phil Karlton</blockquote><p>So that’s it :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b72c5194122" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hapi.js v4.x.x]]></title>
            <link>https://medium.com/@otodockal/hapi-js-v4-x-x-51e3d9bdac59?source=rss-1ab92bccb23e------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e3d9bdac59</guid>
            <dc:creator><![CDATA[Oto Dočkal]]></dc:creator>
            <pubDate>Mon, 31 Mar 2014 19:22:53 GMT</pubDate>
            <atom:updated>2014-05-13T22:31:09.618Z</atom:updated>
            <content:encoded><![CDATA[<h4>Hapi’s cafe — Getting started tutorial.</h4><h3>Hapi</h3><p>Hapi.js is one of the many Node.js frameworks. It shines with essential built-in features that your API server or webpage mostly needs. No like others, hapi is configuration-centric, so that, much more declarative. Hapi is built by Walmart labs (<a href="https://github.com/spumko">Spumko</a>, <a href="http://nodejs.org/video/">Eran Hammer</a>). Pretty well battle tested by their <a href="https://twitter.com/search?q=%23nodebf&amp;src=hash">mobile app customers</a>, production ready!</p><p>This getting started tutorial is called Hapi’s cafe, because without coffee I couldn’t be hapi.☺</p><p>All described code is available on <a href="https://github.com/otodockal/hapi-tutorial">GitHub</a>. So, don&#39;t waste the time and let&#39;s start.</p><h4>But, first of all…</h4><p>[NPM expert should skip this part] <a href="https://blog.heroku.com/archives/2014/3/11/node-habits">10 Habits of a Happy Node Hacker</a>.</p><h4>OK, NPM is well known, let&#39;s install Hapi</h4><p>Install your package.json.</p><pre>npm init</pre><p>Install Hapi.</p><pre>npm install hapi --save</pre><p>Our app is using Gulp for server start and testing, so let&#39;s install the rest of dependencies.</p><pre>npm install gulp --save-dev</pre><pre>npm install gulp-nodemon --save-dev</pre><p>And that&#39;s all for the start. Let&#39;s code our first step of the tutorial.</p><h4>App overview</h4><p>App is composed from eight parts and each has its own git tag. From <a href="https://github.com/otodockal/hapi-tutorial">Github</a> repository you can get always one part by following command.</p><pre>git checkout step-*</pre><p>App has following parts</p><ul><li>Step-1 — Hello world</li><li>Step-2 — Routing</li><li>Step-3 — Validation</li><li>Step-4 — Server methods</li><li>Step-5 — Plugins</li><li>Step-6 — Caching</li><li>Step-7 — Views</li><li>Step-8 — Testing</li></ul><p>So, if you want app with plugins, use the following command</p><pre>git checkout step-5</pre><h4>Step-1 — Hello World</h4><p>Hello world app is always mandatory, so here is a sample.</p><p>We should create <strong>server.js</strong> file and define following script for running our server.</p><pre>var Hapi = require(&#39;hapi&#39;);</pre><pre>// Create a server with a host and port<br>var server = Hapi.createServer(&#39;localhost&#39;, 8000);</pre><pre>// Homepage route<br>server.route({<br>  method: &#39;GET&#39;,<br>  path: &#39;/&#39;,<br>  config: {<br>    handler: function (request, reply) {<br>      reply(&#39;Hapi.js getting started tutorial Hapi\&#39;s cafe.&#39;);<br>    }<br>  }<br>});</pre><pre>// Start the server<br>server.start(function () {<br>  console.log(&#39;Server started at port &#39; + server.info.port);<br>});</pre><p>Server can start also without defining any route and it returns “No Found”.</p><pre>{“statusCode”:404,”error”:”Not Found”}</pre><p>But “Hello World” part wouldn&#39;t be complete without this route. By the way, the whole server routing table could be viewed by <a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#servertablehost">server.table</a> method.</p><p>Node.js is long live process so it must be repeatedly restarted for app review. But because of we are using Gulp task runner, we don’t have to do it. Let’s define our <strong>gulpfile.js</strong> task.</p><pre>var gulp = require(‘gulp’);<br>var nodemon = require(‘gulp-nodemon’);</pre><pre>// Restart the server for changes.<br>gulp.task(‘default’, function () {<br> nodemon({ script: ‘server.js’, ext: ‘html js’ });<br>});</pre><p>Well, let&#39;s start our server by</p><pre>gulp</pre><p>So app is running on <strong>localhost:8000</strong> as the server.start method informs in console.</p><p>You can check out this part by command</p><pre>git checkout step-1</pre><h4>Step-2 — <a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#serverrouteoptions">Routing</a></h4><p>Hapi routing is strong part of the framework. For the people familiar with Express.js framework, routing is little bit verbose. The main reason is that each route is also route config, so that, you always define an object. In the end, it&#39;s even clearer, believe me!</p><p>This part only extend <strong>server.js</strong> file by four routes.</p><ul><li>/</li><li>/coffee</li><li>/coffee/{id}</li><li>/coffeemakers</li><li>/coffeemakers/{id}</li></ul><p>You can check out this part by command</p><pre>git checkout step-2</pre><h4>Step-3 — <a href="https://github.com/spumko/joi">Validation</a></h4><p>Validation is very important and this important feature is very nicely supported. For this, Hapi needs module Joi (also from spumko family). Joi usage is as simple as it should be. No more dangerous custom validation methods, Joi’s validation is strictly declarative, safe and straightforward.</p><p>Now, we should install Joi npm module</p><pre>npm install joi --save</pre><p>and extend our routes by validation objects (./server.js).</p><pre>// Coffee routes<br>server.route({<br>  method: ‘GET’,<br>  path: ‘/coffee’,<br>  config: {<br>    handler: function (request, reply) {<br>      reply(‘List of coffee.’);<br>    },<br>    <strong>validate: {<br>      query: {<br>        page: Joi.number().min(1)<br>      }<br>    }</strong><br>  }<br>});</pre><pre>server.route({<br>  method: ‘GET’,<br>  path: ‘/coffee/{id}’,<br>  config: {<br>    handler: function (request, reply) {<br>      reply(&#39;Coffee view - &#39; + request.params.id + &#39;.&#39;);<br>    },<br>   <strong> validate: {<br>      path: {<br>        id: Joi.number().min(1)<br>      }<br>    }</strong><br>  }<br>});</pre><p><em>NOTE: Rest of the routes are defined on Github repo.</em></p><p>First “/coffee” route validates “query” page param. It can&#39;t be less then one, otherwise it returns “Bad request”.</p><pre>{&quot;statusCode&quot;:400,&quot;error&quot;:&quot;Bad Request&quot;,&quot;message&quot;:&quot;the value of page must be larger than or equal to 1&quot;,&quot;validation&quot;:{&quot;source&quot;:&quot;query&quot;,&quot;keys&quot;:[&quot;page&quot;]}}</pre><p><strong>Joi</strong> always returns very precise description of error!</p><p>Second route “/coffee/{id}” validates “path” id, that should by larger than or equal to 1.</p><p>Our very simple app doesn&#39;t need more, but any other could. <strong>Joi</strong> repo has many more examples. <a href="https://github.com/spumko/joi">Check it out</a>!</p><p>You can check out this part by command</p><pre>git checkout step-3</pre><h4>Step-4 — <a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#plugin-interface">Plugins</a></h4><p>Above “one-file” solution was pretty ugly. Now it&#39;s time to break our app (server.js file) into plugins. Plugins are something like private npm modules. Each plugin must be loaded either by <a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#packregisterplugin-options-callback"><strong>pack.register(plugin, options, callback</strong></a><strong>)</strong> method, where plugin object is registered directly as a first param of the method</p><pre>// Homepage plugin<br>server.pack.<strong>register</strong>(require(‘./plugin/homepage/index’).register, function (err) {<br>   if (err) {<br>     console.log(‘Failed loading plugin: Homepage’);<br>   }<br>});</pre><p>or by <a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#packrequirename-options-callback"><strong>pack.require(name, [options], callback)</strong></a><strong> </strong>method</p><pre>// Coffee plugin<br>server.pack.<strong>require</strong>(‘./plugin/coffee’, function (err) {<br>   if (err) {<br>     console.log(‘Failed loading plugin: Coffee’);<br>   }<br>});</pre><p><em>NOTE: Coffee maker plugin is using also the same require method. (./server.js)</em></p><p>These solutions are very convenient, it&#39;s up to you, what you prefer. Second “<a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#packrequirename-options-callback">require</a>” solution requires <strong>package.json</strong> declaration in plugin directory.</p><pre>{<br> “name”: “Coffee”,<br> “description”: “Coffee from coffee maker!”,<br> “version”: “0.0.1&quot;<br>}</pre><p>Does not remind you something? Yeah, NPM ☺.</p><p>Also, there is third option for registering list of plugins</p><pre><a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#packrequirenames-callback">pack.require(names, callback)</a></pre><p>So now, we have three plugins</p><ul><li>Coffee</li><li>Coffee maker</li><li>Homepage</li></ul><p>Shortened example of Coffee plugin (./plugin/coffee/index.js)</p><pre>exports.register = function (plugin, options, next) {</pre><pre>  // Coffe routes<br>  plugin.route({<br>    method: &#39;GET&#39;,<br>    path: &#39;/coffee&#39;,<br>    config: {<br>      handler: function (request, reply) {<br>        reply(&#39;List of coffee.&#39;);<br>      },<br>      validate: {<br>        query: {<br>          page: Joi.number().min(1)<br>        }<br>      }<br>    }<br>  });</pre><pre> // and more …<br> next();<br>}</pre><p>Each plugin has its own directory and app structure is much better.</p><p>Check it out by command</p><pre>git checkout step-4</pre><p>Plugins are using for precise teams distribution. Even more, you can publish plugin as a npm module and easily plug into your hapi application. So powerful, so nice.</p><h4><strong>Step-5 — </strong><a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#servermethodmethod"><strong>Server methods</strong></a></h4><p>Server methods extends your server object with custom methods. The big advantage is that methods can be easily <strong>cached</strong>.</p><p>Now, we added <strong>two data models — coffee and coffee maker model. </strong>Coffee maker model contains two server methods “getRandomCoffeemakers” and “getCoffeemakerById”. In this step, methods are not cached (step-6)☺.</p><p>Register of Coffee maker plugin <strong>methods </strong>(./plugin/coffeemaker/model.js)</p><pre>module.exports = function (plugin) {<br>  <strong>plugin.method</strong>(‘getRandomCoffeemakers’, function (next) {<br>    next(null, shuffle(data));<br>  });<br>  <strong>plugin.method</strong>(‘getCoffeemakerById’, function (id, next) {<br>    var coffeemaker = getCoffeemakerById(id);<br>    if (!coffeemaker) {<br>      next(new Error(‘Not found’));<br>    }<br>    next(null, coffeemaker);<br>  });<br>}</pre><p>and methods are called like this one (./plugin/coffeemaker/index.js)</p><pre><strong>plugin.methods.getRandomCoffeemakers</strong>(function (err, coffeeMakers) {<br>  if (err) {<br>    return reply(<strong>Boom.notFound()</strong>);<br>  }<br>  reply(coffeeMakers);<br>});</pre><p>You can see, that we are using <a href="https://github.com/spumko/boom"><strong>Boom</strong></a> module. Boom module is also from spumko family and is using for HTTP-friendly error response. So install it by npm</p><pre>npm install boom --save</pre><p>Complete source code of this part can be downloaded by command</p><pre>git checkout step-5</pre><h4>Step-6 — <a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#servercachename-options">Caching</a></h4><p>Built-in caching mechanisms is composed from features like</p><ul><li>time — expiresIn, expiresAt, staleIn, staleTimeout</li><li>and manual invalidation.</li></ul><h3>Twitter / hapijs: @strathmeyer Sorry. It&#39;s ...</h3><p>I just wrote up a tutorial on caching your API with @hapijs. http://vawks.com/blog/2014/03/15/caching-with-hapi/ ... #cacheruleseverythingaroundme</p><p>Also supports memory, MongoDB, Redis, Riak, Memcached store by spunko modul called <a href="https://github.com/spumko/catbox"><strong>Catbox</strong></a>.</p><p>Our app for simplification using <strong>memory</strong> caching and correct behavior is shown on random serving of items on each request. Because of caching, items are randomly served only each five seconds. Cache is applied on plugin method “getRandomCoffeemakers” (./plugin/coffeemaker/model.js)</p><pre> plugin.method(‘getRandomCoffeemakers’, function (next) {<br>   next(null, shuffle(data));<br> },{<br><strong>   cache: {<br>     expiresIn: 5000<br>   }</strong><br> });</pre><p>and for demonstration on “/coffee” route, that returns “cache-control” header. (./plugin/coffee/index.js)</p><pre>// Coffee<br>plugin.route({<br>  method: &#39;GET&#39;,<br>  path: &#39;/coffee&#39;,<br>  config: {<br>    handler: function (request, reply) {<br>      reply(model.getCoffeeList());<br>    },<br>    validate: {<br>      query: {<br>        page: Joi.number().min(1)<br>      }<br>    },<br>    <strong>cache: {expiresIn: 60 * 60 * 1000}</strong><br>  }<br>});</pre><p>Complete source code of this part can be downloaded by command</p><pre>git checkout step-6</pre><h4>Step-7 — <a href="https://github.com/spumko/hapi/blob/master/docs/Reference.md#serverviewsoptions">Views</a></h4><p>Now, we will use templates to generate responses instead of JSON or strings. Hapi doesn&#39;t support any template engine directly, but you can config most of them through the config object in <strong>plugin.views() </strong>or server.views() of course.</p><p>In our app we are using Handlebars, so let&#39;s config our mandatory items</p><ul><li>partialsPath — the root file path where partials are located</li><li>layout — true|false, for our app “true”</li></ul><p>and we should also install npm module handlebars</p><pre>npm install handlebars --save</pre><p>Coffee plugin view config (./plugin/coffee/index.js):</p><pre> // Templates<br> plugin.views({<br>   engines: {<br>     html: ‘handlebars’<br>   },<br>   path: ‘./templates’,<br>   partialsPath: ‘./templates’,<br>   layout: true,<br>   layoutPath: ‘./../homepage/templates’<br> });</pre><p>Complete source code of this part can be downloaded by command</p><pre>git checkout step-7</pre><h4>Step-8 — <a href="https://github.com/spumko/lab">Testing</a></h4><p>Each test should be written immediately, but for the better clarity of the tutorial, I decided for alone last part.</p><p>The part is last, but maybe the most important. In Node.js exists bunch of test frameworks like Mocha, Jasmine, NodeUnit etc. But <strong>Hapi</strong> has its own, called <a href="https://github.com/spumko/lab"><strong>Lab</strong></a>. It&#39;s originally fork of Mocha.</p><p>So, let&#39;s install Lab</p><pre>npm install lab --save-dev</pre><p>Well, now we need to change little bit our server.js file. We need to export server object for the testing purposes.</p><pre>var server = <strong>module.exports =</strong> Hapi.createServer(‘localhost’, 8000);</pre><pre>// … code of the server.js</pre><pre>// Start the server<br><strong>if (!module.parent) {</strong><br>  server.start(function () {<br>    console.log(‘Server started at port ‘ + server.info.port);<br>  });<br>}</pre><p>And finally we can write tests.</p><pre>var Hapi = require(‘hapi’);<br>var Lab = require(‘lab’);<br>var server = require(‘./../../server’);<br>var expect = Lab.expect;<br>var describe = Lab.experiment;<br>var it = Lab.test;</pre><pre>describe(‘Server’, function () {</pre><pre> it(‘calls /’, function (done) {<br>   server.inject({ method: ‘GET’, url: ‘/’ }, function (res) {<br>     // code<br>     expect(res.statusCode).to.equal(200);<br>     // headers<br>     expect(res.headers[‘content-type’]).to.equal(‘text/html; charset=utf-8&#39;);<br>     expect(res.headers[‘content-length’]).to.equal(752);<br>     expect(res.headers[‘cache-control’]).to.equal(‘no-cache’);<br>     done();<br>   });<br> });<br>});</pre><p>Run tests by command</p><pre>gulp test</pre><p>Test result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJigO6fsuqDC7TLsxwU2FQ.png" /></figure><p>Complete source code of this part can be downloaded by command</p><pre>git checkout -f master</pre><h4><strong>Conclusion</strong></h4><p>Tutorial focused on eight parts of the framework and could be much larger, because Hapi is much bigger then I could coverage in one document.</p><p>So, be hapi with Hapi! ☺</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e3d9bdac59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>