<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Matt Goldspink</title>
	<atom:link href="https://www.mattgoldspink.co.uk/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mattgoldspink.co.uk</link>
	<description>Salesforce Developer with Vlocity Inc</description>
	<lastBuildDate>Tue, 12 Nov 2019 09:16:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.6.7</generator>
<site xmlns="com-wordpress:feed-additions:1">45832172</site>	<item>
		<title>SalesforceWay Podcast Interview &#8211; Locker Service</title>
		<link>https://www.mattgoldspink.co.uk/salesforceway-podcast-interview-locker-service/</link>
					<comments>https://www.mattgoldspink.co.uk/salesforceway-podcast-interview-locker-service/#comments</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Fri, 08 Nov 2019 00:59:45 +0000</pubDate>
				<category><![CDATA[Random]]></category>
		<guid isPermaLink="false">https://www.mattgoldspink.co.uk/?p=16726</guid>

					<description><![CDATA[<p>I was very fortunate to be invited by Xi, the host of SalesforceWay Podcast, to come on the show and talk about Locker Service. Locker Service is one those of weird technologies that many people don&#8217;t fully understand or see the benefit of. In fact I&#8217;d go so far as to say that many Salesforce ...</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/salesforceway-podcast-interview-locker-service/">SalesforceWay Podcast Interview &#8211; Locker Service</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>I was very fortunate to be invited by Xi, the host of SalesforceWay Podcast, to come on the show and talk about Locker Service.</p>



<figure class="wp-block-embed-wordpress wp-block-embed is-type-wp-embed is-provider-salesforceway"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="kCtyvOAEZa"><a href="https://salesforceway.com/podcast/locker-service/">29. Salesforce Lightning Locker Service</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted" src="https://salesforceway.com/podcast/locker-service/embed/#?secret=kCtyvOAEZa" data-secret="kCtyvOAEZa" width="600" height="338" title="&#8220;29. Salesforce Lightning Locker Service&#8221; &#8212; SalesforceWay" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>



<p>Locker Service is one those of weird technologies that many people don&#8217;t fully understand or see the benefit of. In fact I&#8217;d go so far as to say that many Salesforce developers see it as a blocker to being able to freely develop on Salesforce.</p>



<p>This is 100% not true and comes down to what I believe is a misunderstanding of firstly why we need Locker and secondly what Locker actually does.</p>



<p>I think Xi picked out one of the most of the best parts of the podcast in this YouTube video in which I try break down the reason we need Locker on the Salesforce platform. I highly recommend watching it if you&#8217;ve never really understand why it&#8217;s there (it&#8217;s only a minute long):</p>



<iframe width="560" height="315" src="https://www.youtube.com/embed/aHtUb_0XyTI" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe>



<p>Understanding the reasoning for its existence hopefully helps you see how it&#8217;s benefiting you as a developer.</p>



<p>I recommend listening to the whole podcast to learn more about Locker:</p>



<p><a href="https://salesforceway.com/podcast/locker-service/">https://salesforceway.com/podcast/locker-service/</a></p>



<p>Be sure to check out the other episodes on SalesforceWay for great interviews with people like Don Robins, Andrew Davies, Andy Fawcett and other amazing TrailBlazers from the Salesforce world:</p>



<p><a href="https://salesforceway.com/podcast">https://salesforceway.com/podcast</a></p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/salesforceway-podcast-interview-locker-service/">SalesforceWay Podcast Interview &#8211; Locker Service</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/salesforceway-podcast-interview-locker-service/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16726</post-id>	</item>
		<item>
		<title>Debugging LWC Tests in VS Code</title>
		<link>https://www.mattgoldspink.co.uk/debugging-lwc-tests-vs-code/</link>
					<comments>https://www.mattgoldspink.co.uk/debugging-lwc-tests-vs-code/#comments</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Mon, 04 Feb 2019 13:07:22 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[jest]]></category>
		<category><![CDATA[Lightning Web Components]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[salesforce]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[testing]]></category>
		<guid isPermaLink="false">https://www.mattgoldspink.co.uk/?p=16687</guid>

					<description><![CDATA[<p>Sometimes you have a test that consistently fails and you just can't figure it out. Most of us are used to being able to debug a component in the browser but how do we do that with Jest tests in LWC? Well fortunately it's very simple!</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/debugging-lwc-tests-vs-code/">Debugging LWC Tests in VS Code</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Sometimes you have a test that consistently fails and you just can&#8217;t figure it out. Most of us are used to being able to debug a component in the browser but how do we do that with Jest tests in LWC? Well fortunately it&#8217;s very simple!</p>


<h2>Getting Started</h2>



<p>I&#8217;m going to start by setting up debugging on project from my last post on <a href="http://www.mattgoldspink.co.uk/testing-lightning-web-components/">Testing a Lightning Web Components.</a> The repo for that project is here:</p>



<p><a href="https://github.com/mattgoldspink/testing-lightning-web-components">https://github.com/mattgoldspink/testing-lightning-web-components</a></p>



<p>Clone this repo and open it up in Visual Studio. You&#8217;ll find our component in the <code>force-app/main/default/lwc/helloComponent</code> folder and you&#8217;ll also find the tests we wrote in the <code>__tests__</code> folder.</p>



<h2>Configuring the Debugger in VS Code</h2>



<p>First you&#8217;ll want to click the <code>debugger</code> icon in the left bar in Visual Studio Code to open the debugging view:</p>



<figure class="wp-block-image"><img loading="lazy" width="640" height="657" src="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.03.13.png?resize=640%2C657&#038;ssl=1" alt="Debugging view." class="wp-image-16699" srcset="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.03.13.png?w=696&amp;ssl=1 696w, https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.03.13.png?resize=292%2C300&amp;ssl=1 292w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></figure>



<p>At the top you&#8217;ll see it says <code>No Configurations</code>, click this and you&#8217;ll see an option to <code>Add Configuration...</code>. Clicking this will open a dialog prompting you to choose what type of configuration. Choose <code>Node.js</code>:</p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img loading="lazy" src="https://i1.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/6iJuHAPNri.gif?resize=640%2C157&#038;ssl=1" alt="Adding a new Debugger Configuration in Visual Studio Code." class="wp-image-16700" width="640" height="157" data-recalc-dims="1" /></figure></div>



<p>You&#8217;ll now have a new <code>launch.json</code> file stored in a <code>.vscode</code> folder in your project. This is what Visual Studio Code uses to know how to launch your application. </p>



<p><strong>I highly recommend checking this into your version control so other developers can easily debug too!</strong></p>



<p>Let&#8217;s edit the <code>launch.json</code> and replace the contents with this:</p>


<pre class="brush: jscript; title: ; notranslate">
{
    &quot;version&quot;: &quot;0.2.0&quot;,
    &quot;configurations&quot;: [
        {
            &quot;name&quot;: &quot;Debug Jest Tests&quot;,
            &quot;type&quot;: &quot;node&quot;,
            &quot;request&quot;: &quot;launch&quot;,
            &quot;env&quot;: { &quot;NODE_ENV&quot;: &quot;test&quot; },
            &quot;cwd&quot;: &quot;${workspaceRoot}&quot;,
            &quot;program&quot;: &quot;${workspaceRoot}/node_modules/.bin/lwc-jest&quot;,
            &quot;stopOnEntry&quot;: false,
            &quot;runtimeArgs&quot;: [&quot;--nolazy&quot;],
            &quot;console&quot;: &quot;internalConsole&quot;,
            &quot;sourceMaps&quot;: false,
            &quot;internalConsoleOptions&quot;: &quot;openOnSessionStart&quot;
        }
    ]
}
</pre>


<p>This basically tells Visual Studio Code to kick off the <code>lwc-jest</code> command (line 10) and connect to it. After saving this you&#8217;ll see the name <code>Debug Jest Tests</code> in the top left next to a green play button. Before we click it, let&#8217;s set a breakpoint in our test file.</p>



<h2>Setting Breakpoints</h2>



<p>Open the tests file named <code>helloComponent.test.js</code> &#8211; a quick way to do it is to press <code>cmd + p</code>(Mac) or<code>Ctrl + p</code>  (Windows/Linux) and type <code>helloComponent.test</code> and you should see it list the file in the dropdown. Use the arrow keys to select it and hit <code>Enter</code> to open it.</p>



<p>There&#8217;s 2 ways we can set a breakpoint. The first is to type the keyword <code>debugger</code> in the source code. For example in our first test we could add it like this on line 20:</p>


<pre class="brush: jscript; first-line: 14; highlight: [20]; title: ; notranslate">
    it('Renders with Hello World', () =&gt; {
        const element = createElement('c-hello-component', {
            is: HelloComponent,
        });
        document.body.appendChild(element);

        debugger

        const pTag = element.shadowRoot.querySelector('p');
        expect(pTag.textContent).toEqual('Hello, World!');
    });

</pre>


<p>The second way is to add a red breakpoint on a line in a file. This can be done by clicking to the left of the line number in editor like so:</p>



<figure class="wp-block-image"><img loading="lazy" width="640" height="537" src="https://i1.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/FoHE9s2sAY.gif?resize=640%2C537&#038;ssl=1" alt="How to add a break point in Visual Studio Code." class="wp-image-16701" data-recalc-dims="1"/></figure>



<p>It&#8217;s entirely your choice, but I&#8217;d be careful of using the <code>debugger</code> keyword in case you leave it in your code. For now I&#8217;ll do both so you can see them in action.</p>



<p>With your breakpoints in place hit the green play button and watch the as Visual Studio Code runs and stops at the first breakpoint:</p>



<figure class="wp-block-image"><img loading="lazy" width="640" height="351" src="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/nzgkKkIpSZ.gif?resize=640%2C351&#038;ssl=1" alt="" class="wp-image-16702" data-recalc-dims="1"/></figure>



<p>You&#8217;ll know you&#8217;re running in the debugger because Visual Studio Code changes the bottom status bar from blue to orange, and you&#8217;ll also see the debugger controls in the top of the window.</p>



<h2>Inspecting data</h2>



<p>Once you&#8217;ve hit your breakpoint there&#8217;s various ways you can inspect the variables.</p>



<p>The first way is to use the <code>Variables</code> view on the left hand side. Here you&#8217;ll be able to inspect all the variables in the available scopes. On the left you can also see the <code>Call Stack</code>, to see who called your function, and there&#8217;s also more advanced features like setting expressions to <code>Watch</code>.</p>



<p>The second way is to hover over the variables in the editor and you&#8217;ll get a popover with the variable&#8217;s contents &#8211; a nice quick way to see what&#8217;s going on:</p>



<figure class="wp-block-image"><img loading="lazy" width="640" height="406" src="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.49.22.png?resize=640%2C406&#038;ssl=1" alt="Inspecting a variables value by hovering in Visual Studio Code." class="wp-image-16704" srcset="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.49.22.png?w=1594&amp;ssl=1 1594w, https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.49.22.png?resize=300%2C190&amp;ssl=1 300w, https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.49.22.png?resize=768%2C487&amp;ssl=1 768w, https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.49.22.png?resize=1024%2C649&amp;ssl=1 1024w, https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/Screenshot-2019-02-01-at-21.49.22.png?w=1280&amp;ssl=1 1280w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></figure>



<p>The third way is to use the <code>console</code> as you may be used to doing in browsers like Chrome.  The console is called the  <code>Debug Console</code> and is found in the bottom set of tabs of Visual Studio Code. In here you can type and evaluate expressions, like so:</p>



<figure class="wp-block-image"><img loading="lazy" width="640" height="228" src="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/02/4MosyI8fmF.gif?resize=640%2C228&#038;ssl=1" alt="Using the Debug Console in Visual Studio Code." class="wp-image-16705" data-recalc-dims="1"/></figure>



<p>You can of course step over, step up and continue the debugger using the buttons at the top of the window.</p>



<h2>Finding out more</h2>



<p>Now that you&#8217;re running in the debugger there&#8217;s plenty to explore! I won&#8217;t cover the features here, but I highly recommend reading the official Visual Studio Code docs to learn more: <a href="https://code.visualstudio.com/docs/editor/debugging">https://code.visualstudio.com/docs/editor/debugging</a></p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/debugging-lwc-tests-vs-code/">Debugging LWC Tests in VS Code</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/debugging-lwc-tests-vs-code/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16687</post-id>	</item>
		<item>
		<title>Testing Lightning Web Components</title>
		<link>https://www.mattgoldspink.co.uk/testing-lightning-web-components/</link>
					<comments>https://www.mattgoldspink.co.uk/testing-lightning-web-components/#respond</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Thu, 24 Jan 2019 16:05:23 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Lightning Web Components]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[salesforce]]></category>
		<category><![CDATA[testing]]></category>
		<guid isPermaLink="false">https://www.mattgoldspink.co.uk/?p=16588</guid>

					<description><![CDATA[<p>Lightning Web Components come with powerful unit testing support out of the box. Let's walk through how to use it!</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/testing-lightning-web-components/">Testing Lightning Web Components</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>For anyone with experience of Aura component development, they&#8217;ve probably faced the issue of how to test the damned things! They were so heavily tied to the platform that they couldn&#8217;t easily be tested in isolation.</p>



<p>Fortunately Lightning Web Components has true TDD built in from the outset. It&#8217;s super simple to write tests and make assertions. Even better, if you&#8217;re used to writing tests with Jasmine, Mocha or Jest then you&#8217;ll be right at home.</p>



<h2>Setting up your project</h2>



<p>If you don&#8217;t yet have an LWC project I&#8217;d suggest following my <a href="https://www.mattgoldspink.co.uk/getting-started-with-lightning-web-components/">previous post</a>. In this post we&#8217;ll take what we did in that project and evolve to add some simple unit tests that we can run right from the command line on your computer&#8230; no need to upload code to the org! </p>



<p>Firstly we&#8217;ll need to add a <code>project.json</code> file to the root of our project. If you don&#8217;t have a <code>project.json</code>, just run <code>npm init</code> and follow the walkthrough &#8211; most options can be defaulted. After running this command you&#8217;ll need to add our test dependencies. On the command line run:</p>


<pre class="brush: plain; title: ; notranslate">
npm i -D jest @lwc/jest-preset @lwc/module-resolver @lwc/compiler @lwc/engine
</pre>


<p>This will install <a href="https://jestjs.io/">Jest</a> (a popular testing framework from Facebook used heavily on React) and Salesforce LWC Jest integrations, including the compiler and engine. Now open your <code>package.json</code> and under the <code>"scripts"</code> object add a <code>"test:unit"</code> property who&#8217;s value is simply <code>"jest"</code>.</p>


<pre class="brush: jscript; first-line: 5; highlight: [7]; title: ; notranslate">
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;scripts&quot;: {
    &quot;test:unit&quot;: &quot;jest&quot;
  },
  &quot;author&quot;: &quot;&quot;,
</pre>


<p>The final step is to add a <code>jest.config.js</code> file to the root of our project. The contents should simply look like:</p>


<pre class="brush: jscript; title: ; notranslate">
module.exports = {
    preset: '@lwc/jest-preset',
    moduleNameMapper: {
        '^(c)/(.+)$': '&lt;rootDir&gt;/force-app/main/default/lwc/$2/$2'
    },
    testPathIgnorePatterns: [
        '&lt;rootDir&gt;/node_modules/',
        '&lt;rootDir&gt;/test/specs/'
    ]
};
</pre>


<blockquote class="wp-block-quote"><p>This is mostly boilerplate and in fact Salesforce has a simpler option which is documented in the Salesforce Developer Guide:&nbsp;<a href="https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.unit_testing_using_jest_installation">https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.unit_testing_using_jest_installation</a></p></blockquote>



<p>With this setup you can run your tests on the command line by typing:</p>


<pre class="brush: bash; title: ; notranslate">
$ npm run test:unit
No tests found
In /Users/matthewgoldspink/Desktop/MyFirstLWCProject
  5 files checked.
  testMatch: **/__tests__/**/?(*.)(spec|test).js - 0 matches
  testPathIgnorePatterns: /Users/matthewgoldspink/Desktop/MyFirstLWCProject/node_modules/,/Users/matthewgoldspink/Desktop/MyFirstLWCProject/test/specs/ - 5 matches
Pattern:  - 0 matches
</pre>


<p>As you can see we don&#8217;t have any tests yet, so let&#8217;s go add one.</p>



<h2>BUT WAIT! There&#8217;s a simpler way</h2>



<p>We just saw a lot of configuration &#8211; <code>jest.config.js</code> files and multiple <code>npm installs</code>. I showed the above to reinforce that this is just standard Open Source Jest tooling &#8211; nothing Salesforce proprietary! However that doesn&#8217;t mean that the guys at Salesforce don&#8217;t want to make things easier, and they have! You can actually replace everything we just installed with one simple npm command:</p>


<pre class="brush: plain; title: ; notranslate">
npm i -D jest @salesforce/lwc-jest
</pre>


<p>This will install everything we installed last time but behind a <code>lwc-jest</code> wrapper command. You can safely delete references to <code>@lwc/jest-preset @lwc/module-resolver @lwc/compiler @lwc/engine</code> in your <code>package.json</code>.</p>



<p>Next you can delete your <code>jest.config.js</code> and update your <code>package.json</code> scripts to be:</p>


<pre class="brush: jscript; first-line: 5; highlight: [7]; title: ; notranslate">
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;scripts&quot;: {
    &quot;test:unit&quot;: &quot;lwc-jest&quot;
  },
  &quot;author&quot;: &quot;&quot;,
</pre>


<p>Now when you run <code>npm run test:unit</code> it will run the <code>lwc-jest</code> cli command which in turn will call <code>jest</code> with everything installed and configured for you!</p>



<h2>Adding a test to an LWC Component</h2>



<p>Each component can contain it&#8217;s own suite of tests, navigate to your component, in my project I&#8217;ll be working with a very simple <code>helloComponent</code> whose content is simply:</p>


<pre class="brush: xml; title: ; notranslate">
&lt;template&gt;
    &lt;div class=&quot;slds-m-around_medium&quot;&gt;
        &lt;p&gt;Hello, {person}!&lt;/p&gt;
    &lt;/div&gt;
&lt;/template&gt;
</pre>

<pre class="brush: jscript; title: ; notranslate">
import { LightningElement, api } from 'lwc';

export default class HelloComponent extends LightningElement {

    @api person = 'World';

}
</pre>


<p>Add a folder called <code>__tests__</code>. Now create a file called <code>helloComponent.test.js</code>:</p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img loading="lazy" src="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-16-at-21.38.55.png?resize=298%2C252&#038;ssl=1" alt="Where to put your __tests__ folder for your lightning components." class="wp-image-16672" width="298" height="252" srcset="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-16-at-21.38.55.png?w=596&amp;ssl=1 596w, https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-16-at-21.38.55.png?resize=300%2C254&amp;ssl=1 300w" sizes="(max-width: 298px) 100vw, 298px" data-recalc-dims="1" /></figure></div>



<p>Inside this file we&#8217;ll add our first test:</p>


<pre class="brush: jscript; title: ; notranslate">
import { createElement } from 'lwc';
import HelloComponent from 'c/helloComponent';

describe('c-hello-component', () =&gt; {
    
    afterEach(() =&gt; {
        // The jsdom instance is shared across test cases in a 
        // single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    describe('Renders with Hello World', () =&gt; {
        const element = createElement('c-hello-component', {
            is: HelloComponent,
        });
        document.body.appendChild(element);

        const pTag = element.shadowRoot.querySelector('p');
        expect(pTag.textContent).toEqual('Hello, World!');
    });

});
</pre>


<p>There&#8217;s a lot here so let me try describe it in chunks:</p>


<pre class="brush: jscript; title: ; notranslate">
import { createElement } from 'lwc';
import HelloComponent from 'c/helloComponent';
</pre>


<p>These first 2 lines import the <code>createElement</code> function from the <code>lwc</code> framework. This is the magic which knows how to take an LWC class and turn it into an HTML Element. We&#8217;ll use this further down. The second line is how we import our component that we want to test. The <code>c/</code> prefix is simply the namespace of it &#8211; in Salesforce orgs the default namespace is usually <code>c</code>.</p>


<pre class="brush: jscript; first-line: 4; title: ; notranslate">
describe('c-hello-component', () =&gt; {
    
    afterEach(() =&gt; {
        // The jsdom instance is shared across test cases in a 
        // single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });
</pre>


<p>Next we add our first <code>describe</code>, this is essentially the wrapper around where our tests live. We also add an <code>afterEach</code> hook. The code here will be run after every test and as stated in the comment it basically resets the DOM. In other words, it will remove any LWC elements we rendered after each test so that the next test has a clean slate.</p>


<pre class="brush: jscript; first-line: 14; title: ; notranslate">
    describe('Renders with Hello World', () =&gt; {
        const element = createElement('c-hello-component', {
            is: HelloComponent,
        });
        document.body.appendChild(element);

        const pTag = element.shadowRoot.querySelector('p');
        expect(pTag.textContent).toEqual('Hello, World!');
    });

});
</pre>


<p>Finally our test! We use the <code>createElement</code> from the <code>lwc</code> import earlier to turn our <code>HelloComponent</code> into a real DOM element. Then we insert it into the body of our page. And finally we run our assertion &#8211; in this case I expect that there should be a <code>&lt;p&gt;</code> tag whose text content is <code>Hello, World</code>. If you re-run <code>npm run test:unit</code> you&#8217;ll get a nice happy test!</p>


<pre class="brush: bash; title: ; notranslate">
$ npm run test:unit
 PASS  force-app/main/default/lwc/helloComponent/__tests__/helloComponent.test.js
  c-hello-component
    ✓ Renders with Hello World (25ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.508s
</pre>


<h2>Testing a property change</h2>



<p>Whilst a passing test is nice, it&#8217;s not really covering all our logic. One thing we should do is verify that if we set the <code>person</code> property to a different value, then that value is reflected in the DOM too. Let&#8217;s add a new test for that. After your existing test add the following:</p>


<pre class="brush: jscript; first-line: 24; title: ; notranslate">
    it('Renders with Hello Matt', () =&gt; {
        const element = createElement('c-hello-component', {
            is: HelloComponent,
        });
        element.person = &quot;Matt&quot;
        document.body.appendChild(element);

        const pTag = element.shadowRoot.querySelector('p');
        expect(pTag.textContent).toEqual('Hello, Matt!');
    });
</pre>


<p>This test is pretty much the same as before except we&#8217;re now changing the value of <code>person</code> on the element to <code>Matt</code> and we&#8217;re updating our expectation to verify it now says <code>Hello, Matt!</code> instead. Let&#8217;s run it and see what happens:</p>


<pre class="brush: bash; title: ; notranslate">
$ npm run test

&gt; myfirstlwcproject@1.0.0 test /Users/matthewgoldspink/Desktop/MyFirstLWCProject
&gt; jest

 PASS  force-app/main/default/lwc/helloComponent/__tests__/helloComponent.test.js
  c-hello-component
    ✓ Renders with Hello World (25ms)
    ✓ Renders with Hello Matt (3ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.678s
Ran all test suites.
</pre>


<p>Hurray &#8211; It works!</p>



<h2 id="mce_3">Testing a property change Part 2</h2>



<p>Now I want to show something that will likely catch a lot of people out. Let&#8217;s take the same test as we just did, but we&#8217;re going to move one line:</p>


<pre class="brush: jscript; first-line: 24; title: ; notranslate">
    it('Renders with Hello Matt', () =&gt; {
        const element = createElement('c-hello-component', {
            is: HelloComponent,
        });
        document.body.appendChild(element);

        element.person = &quot;Matt&quot;

        const pTag = element.shadowRoot.querySelector('p');
        expect(pTag.textContent).toEqual('Hello, Matt!');
    });
</pre>


<p>I&#8217;ve shifted the <code>element.person = "Matt"</code> line to be run after the element has been inserted into the DOM. If you run the tests now you should see:</p>


<pre class="brush: plain; title: ; notranslate">
$ npm run test

&gt; myfirstlwcproject@1.0.0 test /Users/matthewgoldspink/Desktop/MyFirstLWCProject
&gt; jest

 FAIL  force-app/main/default/lwc/helloComponent/__tests__/helloComponent.test.js
  c-hello-component
    ✓ Renders with Hello World (33ms)
    ✕ Renders with Hello Matt (13ms)

  ● c-hello-component › Renders with Hello Matt

    expect(received).toEqual(expected)

    Expected value to equal:
      &quot;Hello, Matt!&quot;
    Received:
      &quot;Hello, World!&quot;

      31 |
      32 |         const pTag = element.shadowRoot.querySelector('p');
    &gt; 33 |         expect(pTag.textContent).toEqual('Hello, Matt!');
         |         ^
      34 |     });
      35 |
      36 | });

      at Object.expect (force-app/main/default/lwc/helloComponent/__tests__/helloComponent.test.js:33:9)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        3.251s
Ran all test suites.
</pre>


<p>Oh man! It fails!!! How can moving one line break a test?</p>



<p>The difference between the two versions of this test are that in the first version of the test we set the value of <code>person</code> <strong><em>before</em></strong> we inserted the element into the DOM, therefore when the element is inserted it has the value of <code>Matt</code> and renders it immediately. In the second version we set the value of <code>person</code> <strong><em>after</em></strong> the element has been inserted. This means that the component needs to be re-rendered in order to update the DOM&#8230; and rendering is <strong><em>asynchronous</em></strong>. So when we do our expectation immediately after setting the new value, the DOM hasn&#8217;t been re-rendered and so we still see <code>Hello, World!</code>. </p>



<p>So how do we fix this up? We need to run our expectations <strong><em>after</em></strong> then DOM has been updated. Fortunately there&#8217;s a nice easy way to do it&#8230; use a Promise. Let&#8217;s see what this updated test looks like:</p>


<pre class="brush: jscript; first-line: 24; title: ; notranslate">
    it('Renders with Hello Matt', () =&gt; {
        const element = createElement('c-hello-component', {
            is: HelloComponent,
        });
        document.body.appendChild(element);

        element.person = &quot;Matt&quot;

        return Promise.resolve().then(() =&gt; {
            const pTag = element.shadowRoot.querySelector('p');
            expect(pTag.textContent).toEqual('Hello, Matt!');
        });
    });
</pre>


<p>The change above basically creates an immediately resolving Promise and then runs our assertions on the next tick of the browser. If you run the tests now you should see 2 passing tests:</p>


<pre class="brush: bash; title: ; notranslate">
$ npm run test

&gt; myfirstlwcproject@1.0.0 test /Users/matthewgoldspink/Desktop/MyFirstLWCProject
&gt; jest

 PASS  force-app/main/default/lwc/helloComponent/__tests__/helloComponent.test.js
  c-hello-component
    ✓ Renders with Hello World (25ms)
    ✓ Renders with Hello Matt (3ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.277s, estimated 3s
Ran all test suites.
</pre>


<blockquote class="wp-block-quote"><p><a href="https://github.com/mattgoldspink/testing-lightning-web-components">https://github.com/mattgoldspink/testing-lightning-web-components</a></p><cite>All the code from this post is available as a github project for you to clone and run.</cite></blockquote>



<h2>Next steps</h2>



<p>There&#8217;s a lot more things we can do with our tests which I&#8217;ll cover in future posts including:</p>



<ul><li>Triggering, capturing and asserting events</li><li>Mocking of Salesforce&#8217;s Lightning components</li><li>Mocking of data sources</li></ul>



<p>I&#8217;d highly recommend reading some of Salesforce&#8217;s own example tests like in the e-bikes app. Here&#8217;s some additional links for more information:</p>



<ul><li><a href="https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.testing">Salesforce&nbsp;Developer Guide&nbsp;&#8211; Test Lightning Web Components</a></li><li><a href="https://github.com/trailheadapps/ebikes-lwc/blob/master/force-app/main/default/lwc/productFilter/__tests__/productFilter.test.js">Example Jest tests in Ebikes</a></li><li><a href="https://jestjs.io/">Jest Documentation</a></li></ul>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/testing-lightning-web-components/">Testing Lightning Web Components</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/testing-lightning-web-components/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16588</post-id>	</item>
		<item>
		<title>Two Way Binding in Lightning Web Components</title>
		<link>https://www.mattgoldspink.co.uk/two-way-binding-lightning-web-components/</link>
					<comments>https://www.mattgoldspink.co.uk/two-way-binding-lightning-web-components/#comments</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Fri, 18 Jan 2019 09:30:42 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Lightning Web Components]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[salesforce]]></category>
		<guid isPermaLink="false">https://www.mattgoldspink.co.uk/?p=16637</guid>

					<description><![CDATA[<p>If you are migrating from Angular.js to Lightning Web Components (LWC), one of the first questions you'll have is about binding. How do I take bind a property from my JS into a form field and have changes in the form field update that property... i.e. how do I do two way binding in LWC? </p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/two-way-binding-lightning-web-components/">Two Way Binding in Lightning Web Components</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>If you are migrating from Angular.js to Lightning Web Components (LWC), one of the first questions you&#8217;ll have is about binding. How do I take bind a property from my JS into a form field and have changes in the form field update that property&#8230; i.e. how do I do two way binding in LWC?</p>
<p>Well the answer is&#8230; you don&#8217;t.</p>
<p>LWC is designed with a one way data binding approach. Initially this can feel frustrating, especially for people who have come to love the simplicity two way. Let&#8217;s review what two way binding is before looking at one way binding.</p>


<h2>Two way binding</h2>



<p>Two way binding allows a model to render data into a view and allows that view to update the data in model. This is mostly used in form fields, for example a text input renders a value from the model, and when the user types data into the field, it is automatically pushed back into the model. In Angular.js we do this with ng-model:</p>


<pre class="brush: xml; title: ; notranslate">
&lt;input type=&quot;text&quot; ng-model=&quot;model.name&quot; /&gt;
</pre>

<pre class="brush: jscript; title: ; notranslate">
angular.controller(&quot;ctrl&quot;, function($scope) {
    $scope.model = {
        name: &quot;Matt&quot;
    };
});
</pre>


<p>Whilst doing this is great, there are some downsides to two way binding. There&#8217;s a lot of complexity to support it behind the scenes, mostly from how to handle a chain of events that may be triggered from a change in the UI. This is one of the reasons that other frameworks like React, Knockout, and now Lighting Web Components, implemented one way binding.</p>



<h2>One way binding</h2>



<p>One way binding means that the model is rendered in the view, but in order to update the model if the view changes, you must fire an event and handle that event to update the code in your controller.</p>



<p>Let&#8217;s walk through an example to see how this works in Lightning Web Components.</p>


<pre class="brush: jscript; title: ; notranslate">
import { LightningElement, track } from 'lwc';

export default class OneWayExample extends LightningElement {

    @track name = 'Matt';

}
</pre>


<p>This is our simple LWC class. It uses the <code>@track</code> decorator to tell the LWC framework that our <code>name</code> property is reactive &#8211; i.e. that LWC should re-render the component when it changes.</p>



<blockquote class="wp-block-quote"><p><a href="https://developer.salesforce.com/docs/component-library/documentation/lwc/js_props_private_reactive">https://developer.salesforce.com/docs/component-library/documentation/lwc/js_props_private_reactive</a></p><cite>See the Salesforce Developer Guide for more details about <code>@track</code></cite></blockquote>



<p>In order to render this into our components HTML we use the <code>{name}</code> syntax:</p>


<pre class="brush: xml; title: ; notranslate">
&lt;template&gt;
   &lt;input type=&quot;text&quot; value={name} /&gt;
   &lt;p&gt;My name is {name}&lt;/p&gt;
&lt;/template&gt;
</pre>


<p>If we test out this code we&#8217;ll see the following:</p>



<figure class="wp-block-image"><img loading="lazy" width="640" height="313" src="https://i1.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/s0KgX4jk22.gif?resize=640%2C313&#038;ssl=1" alt="Demo of our initial code showing that two binding isn't out of the box in LWC" class="wp-image-16650" data-recalc-dims="1"/></figure>



<blockquote class="wp-block-quote"><p><a href="https://developer.salesforce.com/docs/component-library/tools/playground">https://developer.salesforce.com/docs/component-library/tools/playground</a></p><cite>Another incredibly cool product that came out with LWC is the Playground where you can quickly test some simple components without deploying to an org.</cite></blockquote>



<p>It does&#8230; well nothing! </p>



<p>And that&#8217;s because we have only one way binding. So how do we get the changes to update the model? We need to add an event listener.</p>



<h2>Event Listeners</h2>



<p>This is one of my favourite things about LWC. Event Listeners are just standard DOM event listeners. There&#8217;s no custom syntax, or event object, it&#8217;s just pure Web Standards. That means that the docs you read on sites like MDN (for example <a href="https://developer.mozilla.org/en-US/docs/Web/Events/click">https://developer.mozilla.org/en-US/docs/Web/Events/click</a>) apply to LWC! The only difference is that you can attach an event handler using the binding syntax of <code>onsomeevent={myEventHandler}</code>. Let&#8217;s add an <code>onkeyup</code> handler to our example:</p>


<pre class="brush: xml; title: ; notranslate">
&lt;template&gt;
   &lt;input type=&quot;text&quot; value={name} onkeyup={updateName} /&gt;
   &lt;p&gt;My name is {name}&lt;/p&gt;
&lt;/template&gt;
</pre>


<p>In the HTML all we do is add our <code>onkeyup</code> listener and tell it what function on our class to call when it&#8217;s fired. The class looks like this:</p>


<pre class="brush: jscript; title: ; notranslate">
import { LightningElement, track } from 'lwc';

export default class OneWayExample extends LightningElement {

    @track name = 'Matt';

    updateName(event) {
        this.name = event.target.value;
    }

}
</pre>


<p>Our <code>updateName</code> function get&#8217;s the target element (in this case the <code>&lt;input&nbsp;/&gt;</code>) and then it&#8217;s current <code>value</code> and assigns it to our <code>name</code> property in the class. Let&#8217;s see this in action now:</p>



<figure class="wp-block-image"><img loading="lazy" width="640" height="156" src="https://i1.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/REgF0dRs7B.gif?resize=640%2C156&#038;ssl=1" alt="Demo showing one way binding with event to update model." class="wp-image-16652" data-recalc-dims="1"/></figure>



<p>And now we can see the value is automatically updating as we change the text in the field.</p>



<p>And that&#8217;s really all there is to it!</p>



<h2>Where to go from here?</h2>



<p>Obviously this is a very simple example and as you create more and more complex applications how you represent state will get more complicated too. So one concept from React that I&#8217;ve found helpful as more and more components get nested is called <strong><a href="https://reactjs.org/docs/lifting-state-up.html">Lifting State&nbsp;Up</a></strong>. In a future post I&#8217;ll cover how this looks in the LWC world.</p>



<p>For further information check out the following links:</p>



<ul><li><a href="https://developer.salesforce.com/docs/component-library/documentation/lwc/js_props_getter">Salesforce Developer Guide &#8211; Binding in a template</a></li><li><a href="https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.events_handling">Salesforce Developer Guide &#8211; Handle Events</a></li><li><a href="https://www.mattgoldspink.co.uk/getting-started-with-lightning-web-components/">Getting Started with Lightning Web Components</a></li></ul>



<p></p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/two-way-binding-lightning-web-components/">Two Way Binding in Lightning Web Components</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/two-way-binding-lightning-web-components/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16637</post-id>	</item>
		<item>
		<title>Getting Started with Lightning Web Components</title>
		<link>https://www.mattgoldspink.co.uk/getting-started-with-lightning-web-components/</link>
					<comments>https://www.mattgoldspink.co.uk/getting-started-with-lightning-web-components/#comments</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Sun, 13 Jan 2019 15:43:54 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Lightning Web Components]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[salesforce]]></category>
		<guid isPermaLink="false">https://www.mattgoldspink.co.uk/?p=16594</guid>

					<description><![CDATA[<p>Salesforce have just announced one of the most exciting changes to the platform and to web development in general: Lightning Web Components (or LWC) This is a new way to write UI code on the Salesforce platform using modern web standards. This means as web developers we can finally write standard HTML, DOM and JavaScript with little to no proprietary syntax. I'm talking about pure ES6 JavaScript classes, import statements, normal DOM Events, Template DOM nodes and more!</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/getting-started-with-lightning-web-components/">Getting Started with Lightning Web Components</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Salesforce have just announced one of the most exciting changes to the platform and to web development in general:</p>



<h1>Lightning Web Components (or LWC)</h1>



<hr class="wp-block-separator"/>



<p style="text-align:right"><em>See the official announcement on Salesforce here: </em><a href="https://www.salesforce.com/blog/2018/12/introducing-lightning-web-components-with-javascript"><em>https://www.salesforce.com/blog/2018/12/introducing-lightning-web-components-with-javascript</em></a></p>



<hr class="wp-block-separator"/>



<p>This is a new way to write UI code on the Salesforce platform using modern web standards. This means as web developers we can finally write standard HTML, DOM and JavaScript with little to no proprietary&nbsp;syntax. I&#8217;m talking about pure ES6 JavaScript classes, import statements, normal DOM Events, Template DOM nodes and more!</p>



<p>In this post I&#8217;ll cover how to get started with your first Lightning Web Component on Salesforce.</p>



<h2>1. Getting a Salesforce Org</h2>



<p>First go to <a href="https://www.salesforce.com/form/signup/prerelease-spring19/"></a><a href="https://www.salesforce.com/form/signup/prerelease-spring19/">https://www.salesforce.com/form/signup/prerelease-spring19/</a> and signup for a pre-release &#8220;Developer&#8221; org (be sure to choose Developer in the last step).</p>



<p>You&#8217;ll receive a confirmation email to verify your account. Click through the link and setup a password. You should be logged into your org&#8217;s settings screen. Using &#8220;Quick Search&#8221; on the left sidebar enter &#8220;Dev Hub&#8221; and choose the &#8220;Dev Hub&#8221; option.</p>



<figure class="wp-block-image"><img loading="lazy" width="640" height="361" src="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-09.49.27.png?resize=640%2C361&#038;ssl=1" alt="How to enable dev hub" class="wp-image-16596" srcset="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-09.49.27.png?w=3360&amp;ssl=1 3360w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-09.49.27.png?resize=300%2C169&amp;ssl=1 300w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-09.49.27.png?resize=768%2C433&amp;ssl=1 768w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-09.49.27.png?resize=1024%2C577&amp;ssl=1 1024w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-09.49.27.png?w=1280&amp;ssl=1 1280w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-09.49.27.png?w=1920&amp;ssl=1 1920w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></figure>



<h2>2. Install the Salesforce DX CLI tools</h2>



<p>The CLI tool will help deploy your code to the org. Install it from: <a href="https://developer.salesforce.com/tools/sfdxcli">https://developer.salesforce.com/tools/sfdxcli</a></p>



<p>We need to use the pre-release version of the tool at the moment whilst LWC is in pre-release. You&#8217;ll need to open a command prompt/terminal and enter the following:</p>



<pre class="wp-block-preformatted">sfdx plugins:install salesforcedx@pre-release</pre>



<p>This will install the pre-release version of dx which should be version 45.0.12 or higher. You can verify this by running:</p>



<pre class="wp-block-preformatted">sfdx plugins</pre>



<div class="wp-block-image"><figure class="aligncenter"><a href="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-10.06.58.png?ssl=1"><img loading="lazy" width="640" height="137" src="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-10.06.58.png?resize=640%2C137&#038;ssl=1" alt="CLI - how to update the SFDX to pre-release" class="wp-image-16598" srcset="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-10.06.58.png?w=1112&amp;ssl=1 1112w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-10.06.58.png?resize=300%2C64&amp;ssl=1 300w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-10.06.58.png?resize=768%2C164&amp;ssl=1 768w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-10.06.58.png?resize=1024%2C219&amp;ssl=1 1024w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></a></figure></div>



<hr class="wp-block-separator"/>



<p style="text-align:right"><em>Salesforce DX has a lot of cool features. I highly recommend following the </em><a href="https://trailhead.salesforce.com/en/content/learn/projects/quick-start-salesforce-dx"><em>Getting Started with DX Trailhead</em></a></p>



<hr class="wp-block-separator"/>



<h2>3. Install Visual Studio Code</h2>



<p>Next up we&#8217;ll be using Visual Studio Code to write our components. Whilst there are other editors out there, Salesforce has written plugins to simplify LWC development. Download the latest version from: <a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a>.</p>



<p>Once it&#8217;s installed and running, click the Extensions icon in the left sidebar and you&#8217;ll need to install 2 extensions:</p>



<ul><li>Salesforce Extension Pack</li><li>Lightning Web Components</li></ul>



<p>You&#8217;ll need to restart Visual Studio Code after installing these, click the blue &#8220;Restart&#8221; button. You should see a list similar to this if they installed correctly:</p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><a href="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.01.49.png?ssl=1"><img loading="lazy" src="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.01.49.png?resize=221%2C512&#038;ssl=1" alt="Extensions in VS Code" class="wp-image-16602" width="221" height="512" srcset="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.01.49.png?resize=441%2C1024&amp;ssl=1 441w, https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.01.49.png?resize=129%2C300&amp;ssl=1 129w, https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.01.49.png?w=684&amp;ssl=1 684w" sizes="(max-width: 221px) 100vw, 221px" data-recalc-dims="1" /></a></figure></div>



<h2>4. Creating our first project</h2>



<p>Now with the plugins installed we can start our project! Firstly we&#8217;ll use the tool to bootstrap a new project for us. Press&nbsp;<strong>Command + Shift + P&nbsp;</strong>on Mac, or&nbsp;<strong>Ctrl + Shift + P</strong>&nbsp;on Windows, and in the box type &#8220;<strong>sfdx: create project</strong>&#8220;. It will prompt you to enter a project name, I chose <strong>MyFirstLWCProject</strong>, and a folder to place the project:</p>



<div class="wp-block-image"><figure class="aligncenter"><a href="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/tJUCf8g2XH.gif?ssl=1"><img loading="lazy" width="640" height="448" src="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/tJUCf8g2XH.gif?resize=640%2C448&#038;ssl=1" alt="How to create an SFDX project in VS Code" class="wp-image-16603" data-recalc-dims="1"/></a></figure></div>



<p>Now let&#8217;s write some code. Press&nbsp;<strong>Command + Shift + P&nbsp;</strong>on Mac, or&nbsp;<strong>Ctrl + Shift + P</strong>&nbsp;on Windows, and enter &#8220;<strong>sfdx: create lightning web component</strong>&#8220;, choose the suggested directory by hitting <strong>Enter</strong> and name it &#8220;<strong>helloComponent</strong>&#8220;:</p>



<div class="wp-block-image"><figure class="aligncenter"><a href="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/kh9qIJybV0.gif?ssl=1"><img loading="lazy" width="640" height="448" src="https://i0.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/kh9qIJybV0.gif?resize=640%2C448&#038;ssl=1" alt="How to create an LWC in VS Code" class="wp-image-16604" data-recalc-dims="1"/></a></figure></div>



<p>From here open the <strong>helloComponent.html</strong>&nbsp;file and enter:</p>


<pre class="brush: xml; title: ; notranslate">
&lt;template&gt;
    &lt;lightning-card title=&quot;Hello World&quot; icon-name=&quot;custom:custom103&quot;&gt;
        &lt;div class=&quot;slds-m-around_medium&quot;&gt;
            &lt;p&gt;Hello, {person}!&lt;/p&gt;
            &lt;lightning-input label=&quot;Name&quot; value={person} onchange={updatePerson}&gt;&lt;/lightning-input&gt;
        &lt;/div&gt;
    &lt;/lightning-card&gt;
&lt;/template&gt;
</pre>


<p>And in the <strong>helloComponent.js</strong> replace the contents with:</p>


<pre class="brush: jscript; title: ; notranslate">
import { LightningElement, track } from 'lwc';
 
export default class HelloComponent extends LightningElement {

     @track person = 'World';

     updatePerson(event) {
         this.person = event.target.value;
     }

 }
</pre>


<p>Then finally, we need to update the&nbsp;<strong>helloComponent.js-meta.xml</strong> with:</p>


<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; 
&lt;LightningComponentBundle
    xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot; 
    fqn=&quot;helloComponent&quot;&gt;
   &lt;apiVersion&gt;45.0&lt;/apiVersion&gt;
   &lt;isExposed&gt;true&lt;/isExposed&gt;
   &lt;targets&gt;
     &lt;target&gt;lightning__AppPage&lt;/target&gt;
     &lt;target&gt;lightning__RecordPage&lt;/target&gt;
     &lt;target&gt;lightning__HomePage&lt;/target&gt;
   &lt;/targets&gt;
&lt;/LightningComponentBundle&gt;
</pre>


<p><span class="token operator">Now save all your changes and we&#8217;re ready to deploy the code to our org.<br /></span></p>



<h2>5. Connecting to our org</h2>



<p>We need to get Visual Studio Code connected to our org, so first we need to authorize our newly created Dev Hub. Press <strong>Command + Shift + P </strong>on Mac, or <strong>Ctrl + Shift + P</strong> on Windows, and enter &#8220;<strong>sfdx: authorize a dev hub</strong>&#8220;, this will launch your browser and ask you to log in with your newly created Salesforce org. If you don&#8217;t remember the username for it then check the email you got sent with the verification link:</p>



<div class="wp-block-image"><figure class="aligncenter"><a href="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.40.43.png?ssl=1"><img loading="lazy" width="224" height="300" src="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.40.43.png?resize=224%2C300&#038;ssl=1" alt="Connecting SFDX in VS Code to the org." class="wp-image-16605" srcset="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.40.43.png?resize=224%2C300&amp;ssl=1 224w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.40.43.png?resize=768%2C1029&amp;ssl=1 768w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.40.43.png?resize=764%2C1024&amp;ssl=1 764w, https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/Screenshot-2019-01-13-at-12.40.43.png?w=788&amp;ssl=1 788w" sizes="(max-width: 224px) 100vw, 224px" data-recalc-dims="1" /></a></figure></div>



<p>After being logged into return to Visual Studio Code and next we&#8217;ll create a Scratch Org to use.&nbsp;Press&nbsp;<strong>Command + Shift + P&nbsp;</strong>on Mac, or&nbsp;<strong>Ctrl + Shift + P</strong>&nbsp;on Windows, and enter &#8220;<strong>sfdx: create a default scratch org</strong>&#8220;. Hit <strong>Enter</strong> to set the default for&nbsp;<strong>project-scratch-def.json&nbsp;</strong>and then enter the name as <strong>MyFirstLwcScratchOrg</strong>. This usually takes a minute or so to complete.</p>



<h2>&nbsp;6. Pushing code to the org</h2>



<p>Now we&#8217;re ready to push code to the org. Press&nbsp;<strong>Command + Shift + P</strong>&nbsp;on a Mac or&nbsp;<strong>Ctrl + Shift + P</strong>&nbsp;on Windows (this will be muscle memory soon!), and type &#8220;<strong>sfdx: push source to default scratch org</strong>&#8220;.&nbsp;</p>



<h2>7. Viewing it in the org</h2>



<p>After it&#8217;s been pushed we can go view it in the org.&nbsp;Press&nbsp;<strong>Command + Shift + P</strong>&nbsp;on a Mac or&nbsp;<strong>Ctrl + Shift + P</strong>&nbsp;on Windows and type &#8220;<strong>sfdx: open default org</strong>&#8220;. This will open the org in your browser. Click the App launcher in the top left corner and choose the &#8220;<strong>Sales</strong>&#8221; app. Click the &#8220;<strong>Gear</strong>&#8221; icon in the top right and choose &#8220;<strong>Edit page</strong>&#8220;. This will open <strong>App Builder</strong>, use the search in the left column and type &#8220;<strong>helloComponent</strong>&#8220;. Drag and drop your component to the canvas in the middle in the top of the right column. Finally hit &#8220;<strong>Save</strong>&#8220;, this will ask if you want to activate this page as default in the org. Hit &#8220;<strong>Activate</strong>&#8220;, then &#8220;<strong>Assign as Org Default</strong>&#8220;. Then hit &#8220;<strong>Save</strong>&#8221; in App Builder one last time before hitting &#8220;<strong>Back</strong>&#8220;.</p>



<div class="wp-block-image"><figure class="aligncenter"><a href="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/YuKYJdY46t.gif?ssl=1"><img loading="lazy" width="640" height="342" src="https://i2.wp.com/www.mattgoldspink.co.uk/wp-content/uploads/2019/01/YuKYJdY46t.gif?resize=640%2C342&#038;ssl=1" alt="Adding our LWC to a page" class="wp-image-16607" data-recalc-dims="1"/></a></figure></div>



<p>Now if you don&#8217;t see your component refresh your browser tab. After that you should see your first Lightning Web Component! Try changing the text in the input box and you should see the text in the message also update!</p>



<hr class="wp-block-separator"/>



<p style="text-align:right"><em>For more information about Lightning Web Components check out the great post by </em>Christophe Coenraets<em> over on the Salesforce Developer blog: </em><a href="https://developer.salesforce.com/blogs/2018/12/introducing-lightning-web-components.html"><em>https://developer.salesforce.com/blogs/2018/12/introducing-lightning-web-components.html</em></a></p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/getting-started-with-lightning-web-components/">Getting Started with Lightning Web Components</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/getting-started-with-lightning-web-components/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16594</post-id>	</item>
		<item>
		<title>Node.js Best Practices</title>
		<link>https://www.mattgoldspink.co.uk/node-js-best-practices/</link>
					<comments>https://www.mattgoldspink.co.uk/node-js-best-practices/#respond</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Mon, 29 Aug 2016 11:42:28 +0000</pubDate>
				<category><![CDATA[Node]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[programming]]></category>
		<guid isPermaLink="false">http://www.mattgoldspink.co.uk/?p=16542</guid>

					<description><![CDATA[<p>Node.js Best Practices This article was originally published on Codementor.io Node.js has become one of the most popular platforms over the last couple of years. It sure is easy to get started on those Node.js projects, but once you get beyond the basic Hello World app, knowing how to best structure your code and how ...</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/node-js-best-practices/">Node.js Best Practices</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Node.js Best Practices</p>
<p>This article was originally published on<a href="https://www.codementor.io/nodejs/tutorial/nodejs-best-practices" target="_blank"> Codementor.io</a></p>
<p>Node.js has become one of the <a href="https://www.codementor.io/learn-programming/beginner-programming-language-job-salary-community">most popular platforms</a> over the last couple of years. It sure is easy to get started on those Node.js projects, but once you get beyond the basic <code>Hello World</code> app, knowing how to best structure your code and how to deal with errors can sometimes become a nightmare (as with most languages and frameworks).</p>
<p>And unfortunately, that nightmare makes all the difference between a rock solid production application and a launch disaster.</p>
<p>With that said, let&#8217;s take a look at a few best Node.js practices that will keep you safe from the most common Node.js traps.</p>
<h2>1. Start all projects with <code>npm init</code></h2>
<p>Most people are familiar with NPM as a way to install dependencies, but it is so much more than this. First, I highly recommend creating a new project using <code>npm init</code>, like so:</p>
<pre class="brush: bash; title: ; notranslate">
$ mkdir my-new-project
$ cd my-new-project
$ npm init
</pre>
<p>This will create a new <code>package.json</code> for you which allows you to add a bunch of metadata to help others working on the project have the same setup as you.</p>
<p>For example, I usually open the <code>package.json</code> and add a specific version of Node.js I plan to run on, by adding:</p>
<pre class="brush: jscript; title: ; notranslate">
&quot;engines&quot;: {
&quot;node&quot;: &quot;6.2.0&quot;
}
</pre>
<hr />
<p><em style="color: #808080;">Read more: <a href="https://www.codementor.io/nodejs/tutorial/how-to-use-json-files-in-node-js">How to Use JSON files in Node.js</a></em></p>
<hr />
<h2>2. Setup <code>.npmrc</code></h2>
<p>If you’ve used npm before, you may have come across the <code>- -save</code> flag which updates the <code>package.json</code> with the dependency. When other developers clone the project, they can be sure to have the right dependencies because of this. Unfortunately, remembering to add the flag can be a problem.</p>
<p>In addition, NPM adds a leading caret <code>^</code> to all versions. Consequently, when someone runs <code>npm install</code>, they may get different versions of the modules than what you have. While updating <a href="https://www.codementor.io/nodejs/tutorial/list-of-useful-nodejs-modules">modules</a> is always a good practice, having a team of developers all running against slightly different versions of dependencies can lead to differences in behaviour or availability of APIs.</p>
<p>Therefore, it’s a good idea to have everyone on the same version. To make this easier for everyone, the <code>.npmrc</code> file has some useful properties that can make sure <code>npm install</code> always updates the <code>package.json</code> and enforces the version of installed dependency to be an exact match.</p>
<p>Simply run the following lines in your terminal:</p>
<pre class="brush: bash; title: ; notranslate">
$ npm config set save=true
$ npm config set save-exact=true
</pre>
<p>Now when you run <code>npm install</code>, you can be sure the dependency is saved and will be locked down to the version you installed.</p>
<h2>3. Add scripts to your <code>package.json</code></h2>
<p>If there’s one thing all applications need, it’s a launch script. Knowing which file to call first and with what arguments can be an epic adventure of discovery on some projects. Good thing NPM has a standard way to start all node applications.</p>
<p>Simply add a <code>scripts</code> property and object to your <code>package.json</code> with a <code>start</code> key. It’s value should be the command to launch your app. For example:</p>
<pre class="brush: jscript; title: ; notranslate">
&quot;scripts&quot;: {
&quot;start&quot;: &quot;node myapp.js&quot;
}
</pre>
<p>As soon as someone runs <code>npm start</code>, NPM will run <code>node myapp.js</code> with all the dependencies from <code>node_modules/.bin</code> on your <code>$PATH</code>. This means you can avoid having to do global installs of NPM modules.</p>
<p>There’s a couple of other script hooks worth knowing:</p>
<pre class="brush: jscript; title: ; notranslate">
&quot;scripts&quot;: {
&quot;postinstall&quot;: &quot;bower install &amp;amp;&amp;amp; grunt build&quot;,
&quot;start&quot;: &quot;node myapp.js&quot;,
&quot;test&quot;: &quot;node ./node_modules/jasmine/bin/jasmine.js&quot;
}
</pre>
<p>The <code>postinstall</code> script is run after <code>npm install</code> is run. There’s also <code>preinstall</code> if you need to run something before all the NPM dependencies are installed.</p>
<p>The <code>test</code> script is run when someone runs <code>npm test</code>. This is a nice simple way for someone to be able to run your tests without figuring out if you’ve chosen to use <a href="http://jasmine.github.io/">Jasmine</a>, <a href="https://mochajs.org/">Mocha</a>, <a href="http://www.seleniumhq.org/">Selenium</a>, etc.</p>
<p>You can add your own custom scripts here, too. They can then be run using <code>npm run-script {name}</code> — a simple way for you to give your team a central set of launch scripts.</p>
<h2>4. Use environment variables</h2>
<p>Configuration management is always a big topic in any language. How do you decouple your code from the databases, services, etc. that it has to use during development, QA, and production?</p>
<p>The recommended way in Node.js is to use environment variables and to look up the values from  <code>process.env</code> in your code. For example, to figure out which environment you’re running on, check the <code>NODE_ENV</code> environment variables:</p>
<pre class="brush: jscript; title: ; notranslate">
console.log(&quot;Running in :&quot;  + process.env.NODE_ENV);
</pre>
<p>This is now a standard variable name used across most cloud-hosting vendors.</p>
<p>If you need to load further configurations, you can use a module like <a href="https://github.com/indexzero/nconf">https://github.com/indexzero/nconf</a>.</p>
<h2>5. Use a style guide</h2>
<p>I know we’ve all had those moments where we open a new file from another project for the first time or the file came from a different developer, we then spend the next hour reformatting the braces to be on different lines, changing the spaces to tabs, and vice versa. The problem here is a mixture of opinionated developers and no team/company standard style guide.</p>
<p>It’s far easier to understand code on a codebase if it’s all written in a consistent style. It also reduces the cognitive overhead of whether you should be writing with tabs or spaces. If the style is dictated (and enforced using JSHint or JSCS) then all of sudden, the codebase becomes a lot more manageable.</p>
<p>You don’t have to come out with your own rules either, sometimes it’s better to pick an existing set of guidelines and follow them. Here are some good examples:</p>
<ul>
<li>Airbnb &#8211; <a href="https://github.com/airbnb/javascript">https://github.com/airbnb/javascript</a></li>
<li>Google &#8211; <a href="https://google.github.io/styleguide/javascriptguide.xml">https://google.github.io/styleguide/javascriptguide.xml</a></li>
<li>jQuery &#8211; <a href="https://contribute.jquery.org/style-guide/js/">https://contribute.jquery.org/style-guide/js/</a></li>
</ul>
<p>Just pick one and stick with it!</p>
<h2>6. Embrace async</h2>
<p>I’m sure you’ve heard all the hype about <em>promises</em>, maybe even heard a little about <em>async / await</em> and <em>generators</em> in ES2016. The key idea behind all these techniques is making your code <em>async</em>.</p>
<p>The problem with synchronous functions in JavaScript is that they block any other code from running until they complete. However, synchronous code makes the flow of your application logic easy to understand. On the other hand, async structures like <em>promises</em> actually bring back a lot of that reasoning while keeping your code free from blockages.</p>
<p>So first, I highly recommend running your app (during development only) with the <code>--trace-sync-io</code> flag. This will print a warning and stack trace whenever your application uses a synchronous API.</p>
<p>There are plenty of great articles about how to use <em>promises</em>, <em>generators</em> and <em>async / await</em>. I don&#8217;t need to duplicate other great work that&#8217;s already available, so here’s a few links to get you started:</p>
<ul>
<li>Promises &#8211; <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">http://www.html5rocks.com/en/tutorials/es6/promises/</a></li>
<li>Async / Await &#8211; <a href="https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html">https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html</a></li>
<li>Generators &#8211; <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Iterators_and_Generators">https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Iterators_and_Generators</a></li>
</ul>
<h2>7. Handle errors</h2>
<p>Having an error bring down your entire app in production is never a great experience. Good exception management is important for any app, and the best way to deal with errors is to use the async structures above. For example, <em>promises</em> provide a <code>.catch()</code> handler that will propagate all errors to be dealt with, cleanly.</p>
<p>Let’s say you have a chain of promises, and any one of which could suddenly fail, you can easily handle the error like so:</p>
<pre class="brush: jscript; title: ; notranslate">
doSomething()
.then(doNextStage)
.then(recordTheWorkSoFar)
.then(updateAnyInterestedParties)
.then(tidyUp)
.catch(errorHandler);
</pre>
<p>In the example above, it doesn’t matter which of the earlier functions could have failed, any error will end up in the <code>errorHandler</code>.</p>
<h2>8. Ensure your app automatically restarts</h2>
<p>Okay, so you followed the best practice to handle errors. Unfortunately, some error from a dependency still, somehow, brought down your app 🙁</p>
<p>This is where it’s important to ensure you use a <em>process manager</em> to make sure the app recovers gracefully from a runtime error. The other scenario where you need it to restart is if the entire server you’re running on went down. In that situation, you want minimal downtime and for you application to restart as soon as the server is alive again!</p>
<p>I’d recommend using KeyMetric’s <strong>PM2</strong> <a href="http://pm2.keymetrics.io/">http://pm2.keymetrics.io/</a> to manage your process.</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/0abd382233f3d175eda8c9b4.png" alt="enter image description here" title="enter image title here"/></p>
<p>First, install it as a global module:</p>
<pre class="brush: bash; title: ; notranslate">
$ npm install pm2 -g
</pre>
<p>Then to launch your process, you should run:</p>
<pre class="brush: bash; title: ; notranslate">
$ pm2 start myApp.js
</pre>
<p>To handle restarting after the server crashes, you can follow the PM2 guide for you platform:</p>
<ul>
<li><a href="http://pm2.keymetrics.io/docs/usage/startup/">http://pm2.keymetrics.io/docs/usage/startup/</a></li>
</ul>
<h2>9. Cluster your app to improve performance and reliability</h2>
<p>By default Node.js is run in a single process. Ideally, you want one process for each CPU core so that you can distribute the work load across all the cores. This improves scalability of web apps processing HTTP requests and performance in general. In addition to this, if one worker crashes, the others are still available to handle requests.</p>
<p>One of the other benefits of using a process manager like PM2 is that it supports clustering out of the box:</p>
<ul>
<li><a href="http://pm2.keymetrics.io/docs/usage/cluster-mode/">http://pm2.keymetrics.io/docs/usage/cluster-mode/</a></li>
</ul>
<p>To start up multiple instances of your app for each core on a machine, you’d simply run:</p>
<pre class="brush: bash; title: ; notranslate">
$ pm2 start myApp.js -i max
</pre>
<p>One thing to bear in mind is that each process is standalone — they don’t share memory, or resources. Each process will open it’s own connections to databases, for example. Always keep that in mind as you code. A useful tool people use to share session state, for example,  is <a href="https://www.sitepoint.com/using-redis-node-js/">Redis</a>, this provides an in-memory datastore that can be quickly accessed by all the processes to store session related data.</p>
<h2>10. Require all your dependencies up front</h2>
<p>I’ve seen many developers write code like this:</p>
<pre class="brush: jscript; title: ; notranslate">
app.get(&quot;/my-service&quot;, function(request, response) {
var datastore = require(&quot;myDataStoreDep&quot;)(someConfig);

datastore.get(req.query.someKey)
// etc, ...
});
</pre>
<p>The problem with the code above is that when someone makes a request to <code>/my-service</code>, the code will now load all files required by <code>myDataStoreDep</code> — any of which could throw an exception. Additionally, when the configuration is passed on, there could also be an error at that point which can bring down the entire process. In addition, we don’t know how long that <strong>synchronous</strong> setup of a resource will take. At this point in the code, we essentially block <strong>all</strong> other requests from being handled!</p>
<p>So you should always load all your dependencies upfront and configure them upfront. That way, you&#8217;ll know from the startup if there is a problem, not three to four hours after your app has gone live in production!</p>
<h2>11. Use a logging library to increase errors visibility</h2>
<p><code>console.log</code> is great but it has limits in a production application. Trying to sift through thousands of lines of logs to find the cause of the bug… which I guarantee you <strong>will</strong> have to do at some point, is painful!</p>
<p>A mature logging library can help with this. First, they allow you to set levels for each log message — whether it’s a <code>debug</code>, <code>info</code>, <code>warning</code>, or <code>error</code>. In addition, they typically allow you to log to different files or even remote datastore.</p>
<p>In my applications, for example, I typically log to <a href="https://www.loggly.com/">https://www.loggly.com/</a>. Loggly allows me to quickly search all my log messages using patterns. In addition, it can alert me if a threshold is reached — for example, if my web application starts returning <code>500 SERVER ERROR</code> messages to my users for a period longer than 30 seconds, Loggly can send me a message and I can figure out what’s going on.</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/f81901934cbd4dd81bc8e32d.jpg" alt="enter image description here" title="enter image title here"/></p>
<p>So what library should you use? Again this is always up for opinions. I personally like to use <code>winston</code> &#8211; <a href="https://github.com/winstonjs/winston.">https://github.com/winstonjs/winston.</a></p>
<h2>12. Use <code>Helmet</code> if you’re writing a web app</h2>
<p>If you’re writing a web application, there are a lot of common best practices that you should follow to secure your application:</p>
<ul>
<li>XSS Protection</li>
<li>Prevent Clickingjacking using <code>X-Frame-Options</code></li>
<li>Enforcing all connections to be HTTPS</li>
<li>Setting a <code>Context-Security-Policy</code> header</li>
<li>Disabling the <code>X-Powered-By</code> header so attackers can’t narrow down their attacks to specific software</li>
</ul>
<p>Instead of remembering to configure all these headers, Helmet will set them all to sensible defaults for you, and allow you to tweak the ones that you need.</p>
<p>It’s incredibly simple to set up on an Express.js application:</p>
<pre class="brush: bash; title: ; notranslate">
$ npm install helmet
</pre>
<p>And then in your code when setting up Express add:</p>
<pre class="brush: jscript; title: ; notranslate">
var helmet = require('helmet');
app.use(helmet());
</pre>
<h2>13. Monitor your applications</h2>
<p>Getting notified when something goes wrong with your application is critical on production applications. You don’t want to check your Twitter feed and see thousands of angry users telling you your <a href="https://www.codementor.io/learn-programming/server-down-what-to-do-when-my-server-crashes">servers are down</a> or your <a href="https://www.codementor.io/learn-programming/what-to-do-when-your-website-is-broken">app is broken</a> and has been for the last few hours. So having something <a href="https://www.codementor.io/javascript/tutorial/debug-monitor-performance-client-side-apps-datadog-pingdom-pagerduty-kibana-elastic">monitoring and alerting you</a> to critical issues or abnormal behaviour is important.</p>
<p>We already discussed PM2 for process management. In addition it’s developers <a href="https://keymetrics.io">KeyMetrics.io</a> run a process monitoring SaaS with integration with PM2 baked in. It’s very simple to enable and they have a free plan which is a great starting point for a lot of developers. Once you’ve signed up for KeyMetrics, you can simply run:</p>
<pre class="brush: bash; title: ; notranslate">
$ pm2 interact [public_key] [private_key] [machine_name]
</pre>
<p>This will start sending memory &amp; CPU usage data, plus exception reporting to key metrics servers to view from their dashboard. You can also view latency of your http requests, or set up events when problems occur (for example timeouts to downstream dependencies).</p>
<p>In addition, Loggly (that we mentioned earlier) also provides monitoring based off logs. Both tools in combination can provide you with a way to quickly react to problems before they get out of hand.</p>
<h2>14. Test your code</h2>
<blockquote><p>
  Yeah, yeah, yeah &#8211; I know I should be testing. TDD and all that jazz!</p></blockquote>
<p>Seriously though, testing will save your ass on many occasions. Like creating any new habit, it’s painful to start and keep up the momentum. It gets in the way of your <a href="https://www.codementor.io/learn-development/speed-up-web-development-process">speed of development</a>. However, I can talk from experience that once the first few production issues occur on a project with no tests, you’ll wish you had in the first place.</p>
<p>No matter what stage you are on a project, it’s never too late to introduce testing. My advice is start small, start simple. I’d also highly recommend writing a test for every bug that gets reported. That way you know:</p>
<ul>
<li>How to reproduce the bug (make sure your test fails first!)</li>
<li>That the bug is fixed (make sure you test passes after you fix the issue)</li>
<li>That the bug will never occur again (make sure you run your tests on every new deployment)</li>
</ul>
<p>There’s a lot of testing libraries. I personally stick with <a href="http://jasmine.github.io/2.0/node.html">Jasmine</a> because I’ve used it for a long time now, but <code>Mocha</code>,  <code>chai</code> or any other libraries are great too. If you’re writing a web application too I’d also highly recommend <a href="https://github.com/visionmedia/supertest">Supertest</a> to black box test your web end points.</p>
<hr />
<p><em style="color: #808080;">Interested with unit testing? Read the first part of our <a href="https://www.codementor.io/nodejs/tutorial/unit-testing-nodejs-tdd-mocha-sinon">Unit Testing and TDD in Node.js</a> series</em></p>
<hr />
<p>###Wrapping up</p>
<p>And with that, ladies and gentlemen, those are my nominees for the &#8220;top 14 best practices&#8221; of Node.js.</p>
<p>If you would like to nominate an additional Node.js best practices, please do so in the comments. Let&#8217;s save the world of Node.js projects together! 🙂</p>
<p>###Other tutorials you might be interested in</p>
<ul>
<li><a href="https://www.codementor.io/nodejs/tutorial/build-website-from-scratch-using-expressjs-and-bootstrap">Building a Website from Scratch with ExpressJS and Bootstrap</a></li>
<li><a href="https://www.codementor.io/nodejs/tutorial/introduction-to-nodejs-microservices-senecajs">Quick Intro to Node.JS Microservices: Seneca.JS</a></li>
<li><a href="https://www.codementor.io/nodejs/tutorial/integrate-mailchimp-with-nodejs-app">How to Integrate MailChimp with your NodeJS app</a></li>
<li><a href="https://www.codementor.io/nodejs/tutorial/how-to-write-a-web-scraper-in-nodejs">How to write a web scraper in Node.js</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/node-js-best-practices/">Node.js Best Practices</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/node-js-best-practices/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16542</post-id>	</item>
		<item>
		<title>How to Integrate MailChimp with your NodeJS app</title>
		<link>https://www.mattgoldspink.co.uk/integrate-mailchimp-nodejs-app/</link>
					<comments>https://www.mattgoldspink.co.uk/integrate-mailchimp-nodejs-app/#respond</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Wed, 27 Jul 2016 11:35:57 +0000</pubDate>
				<category><![CDATA[Node]]></category>
		<category><![CDATA[express]]></category>
		<category><![CDATA[mailchimp]]></category>
		<category><![CDATA[node.js]]></category>
		<guid isPermaLink="false">http://www.mattgoldspink.co.uk/?p=16539</guid>

					<description><![CDATA[<p>How to Integrate MailChimp with your NodeJS app This post was originally published on Codementor.io MailChimp is a well-known email marketing SaaS product. With its generous free tier option, it&#8217;s seen as the perfect solution for many startups and small businesses who want to set up and build u their mailing lists. But what many ...</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/integrate-mailchimp-nodejs-app/">How to Integrate MailChimp with your NodeJS app</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>How to Integrate MailChimp with your NodeJS app</p>
<p>This post was originally published on <a href="https://www.codementor.io/nodejs/tutorial/integrate-mailchimp-with-nodejs-app" target="_blank">Codementor.io</a></p>
<p><a href="https://mailchimp.com/">MailChimp</a> is a well-known email marketing SaaS product. With its generous free tier option, it&#8217;s seen as the perfect solution for many startups and small businesses who want to set up and build u their mailing lists.</p>
<p>But what many fail to notice is how rich it&#8217;s REST API is.</p>
<p>That&#8217;s why in this tutorial, I&#8217;d like to walk you through a few use<br />
 cases for how you may want to integrate MailChimp into your own Node.JS application, focusing on:</p>
<ol>
<li>Adding new users to your own mailing list in MailChimp. </li>
<li>Allowing users to import an existing list of contacts from their MailChimp account into your application and sync them back.</li>
</ol>
<p>We&#8217;ll be using the following Node.js libraries:<br />
&#8211; <a href="https://expressjs.com/">Express</a> for our backend<br />
&#8211; <a href="https://visionmedia.github.io/superagent/">Superagent</a> to make REST requests to MailChimp<br />
&#8211; A few other small libraries for performing OAuth</p>
<h2>1 &#8211; Adding new users to MailChimp</h2>
<p>First let&#8217;s start by setting up a very simple project on the command line:</p>
<pre class="brush: bash; title: ; notranslate">
$ npm init // feel free to enter whatever for these
$ npm install --save express body-parser superagent
$ touch index.js
</pre>
<p>This will install our core dependencies and create our launch file. Open <code>index.js</code> in your text editor of choice and paste the following:</p>
<pre class="brush: jscript; title: ; notranslate">
var express = require(&amp;#039;express&amp;#039;);
var bodyParser = require(&amp;#039;body-parser&amp;#039;);
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get(&amp;#039;/&amp;#039;, function (req, res) {
  res.send(&amp;#039;Hello World!&amp;#039;);
});

app.listen(3000, function () {
  console.log(&amp;#039;Example app listening on port 3000!&amp;#039;);
});
</pre>
<p>Then on the command line type:</p>
<pre class="brush: bash; title: ; notranslate">
$ node index.js
Example app listening on port 3000!
</pre>
<p>If you go into your browser to <code>http://localhost:3000/</code>, you should see a simple page which says &#8220;Hello World!&#8221;. With that set up, we can now start integrating a bit deeper.</p>
<h3>Adding a signup form</h3>
<p>We&#8217;ll create a very simple HTML page in <code>views/signup.html</code> which takes the first name, last name, and email address:</p>
<pre class="brush: xml; title: ; notranslate">
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
        &amp;lt;title&amp;gt;Sign Up&amp;lt;/title&amp;gt;
        &amp;lt;link href=&amp;quot;https://cdnjs.cloudflare.com/ajax/libs/spectre.css/0.1.25/spectre.min.css&amp;quot; rel=&amp;quot;stylesheet&amp;quot; crossorigin=&amp;quot;anonymous&amp;quot;&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;form action=&amp;quot;/signup&amp;quot; method=&amp;quot;POST&amp;quot; class=&amp;quot;centered mt-10 ml-10 mr-10&amp;quot;&amp;gt;
            &amp;lt;div class=&amp;quot;form-group&amp;quot;&amp;gt;
                &amp;lt;label class=&amp;quot;form-label&amp;quot; for=&amp;quot;firstname&amp;quot;&amp;gt;First Name&amp;lt;/label&amp;gt;
                &amp;lt;input class=&amp;quot;form-input&amp;quot; type=&amp;quot;text&amp;quot; name=&amp;quot;firstname&amp;quot; id=&amp;quot;firstname&amp;quot;/&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class=&amp;quot;form-group&amp;quot;&amp;gt;
                &amp;lt;label class=&amp;quot;form-label&amp;quot; for=&amp;quot;lastname&amp;quot;&amp;gt;Last Name&amp;lt;/label&amp;gt;
                &amp;lt;input class=&amp;quot;form-input&amp;quot; type=&amp;quot;text&amp;quot; name=&amp;quot;lastname&amp;quot; id=&amp;quot;lastname&amp;quot;/&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div class=&amp;quot;form-group&amp;quot;&amp;gt;
                &amp;lt;label class=&amp;quot;form-label&amp;quot; for=&amp;quot;email&amp;quot;&amp;gt;Email&amp;lt;/label&amp;gt;
                &amp;lt;input class=&amp;quot;form-input&amp;quot; type=&amp;quot;text&amp;quot; name=&amp;quot;email&amp;quot; id=&amp;quot;email&amp;quot;/&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;input type=&amp;quot;submit&amp;quot; class=&amp;quot;btn btn-primary&amp;quot; value=&amp;quot;Submit&amp;quot;/&amp;gt;
        &amp;lt;/form&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
</pre>
<p>In our <code>index.js</code> we need to serve up static files, so please add the following line:</p>
<pre class="brush: jscript; title: ; notranslate">
app.use(express.static(&amp;#039;views&amp;#039;));
</pre>
<p>We also want to handle the form submission; so for now add the following to <code>index.js</code></p>
<pre class="brush: jscript; title: ; notranslate">
app.post(&amp;#039;/signup&amp;#039;, function (req, res) {
  // save user details to your database.
  res.send(&amp;#039;Signed Up!&amp;#039;);
});
</pre>
<p>Now when you re-run the app and signup, you should see the following:</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/0dc2d14b4d877808068d5134.png" alt="Our Sign Up Page" title="Sign up Page" /></p>
<h3>Saving our new user to MailChimp</h3>
<p>I&#8217;m going to assume you have a database somewhere to save this user to, so let&#8217;s skip straight to saving this user to a new list in MailChimp.</p>
<p>We&#8217;ll need the following information from MailChimp to make the calls:</p>
<ul>
<li><strong>Your API token</strong> &#8211; Log in to your MailChimp account and go to <code>Profile</code> in the top right. Then on the <code>Profile</code> page go to <code>Extras</code> -> <code>API Keys</code>. Scroll down and if you don&#8217;t have any available then click <code>Create A Key</code>:<img src="https://www.mattgoldspink.co.uk/static/withheld.svg" alt="Generate MailChimp API Key" title="Generate MailChimp API Key" /></li>
<li><strong>Your Server Instance</strong> &#8211; This is also embedded in your API token. It is taken from the last characters after the <code>-</code>. For example my API token is <code>YOUR_MAILCHIMP_API_KEY-usX</code>, therefore my server instance is <code>us6</code>.</li>
<li><strong>The Unique List Id</strong> &#8211; this is for the list you want to add people to. For this, click on <code>Lists</code>, find your list, then on the right hand side click the dropdown arrow, then choose <code>Settings</code> and scroll down on this page to the bottom where you should see <code>Unique id for list &lt;your list name&gt;</code>:<img src="https://www.mattgoldspink.co.uk/static/article-images/f4970bbbd6b7599e28ceae06.gif" alt="Get List Unique ID" title="Get List Unique ID" /></li>
</ul>
<p>With all of these, we&#8217;re ready to make some REST calls! I personally prefer using a library called <strong><a href="https://visionmedia.github.io/superagent/">SuperAgent</a></strong> to make rest calls (we installed it with our initial <code>npm</code> modules).</p>
<p>At the top of our <code>index.js</code> load superagent:</p>
<pre class="brush: jscript; title: ; notranslate">
var request = require(&amp;#039;superagent&amp;#039;);
</pre>
<p>Then we&#8217;ll update our <code>signup</code> method:</p>
<pre class="brush: jscript; title: ; notranslate">
var mailchimpInstance   = &amp;#039;us6&amp;#039;,
    listUniqueId        = &amp;#039;b6a82d89f0&amp;#039;,
    mailchimpApiKey     = &amp;#039;YOUR_MAILCHIMP_API_KEY-usX&amp;#039;;

app.post(&amp;#039;/signup&amp;#039;, function (req, res) {
    request
        .post(&amp;#039;https://&amp;#039; + mailchimpInstance + &amp;#039;.api.mailchimp.com/3.0/lists/&amp;#039; + listUniqueId + &amp;#039;/members/&amp;#039;)
        .set(&amp;#039;Content-Type&amp;#039;, &amp;#039;application/json;charset=utf-8&amp;#039;)
        .set(&amp;#039;Authorization&amp;#039;, &amp;#039;Basic &amp;#039; + new Buffer(&amp;#039;any:&amp;#039; + mailchimpApiKey ).toString(&amp;#039;base64&amp;#039;))
        .send({
          &amp;#039;email_address&amp;#039;: req.body.email,
          &amp;#039;status&amp;#039;: &amp;#039;subscribed&amp;#039;,
          &amp;#039;merge_fields&amp;#039;: {
            &amp;#039;FNAME&amp;#039;: req.body.firstName,
            &amp;#039;LNAME&amp;#039;: req.body.lastName
          }
        })
            .end(function(err, response) {
              if (response.status &amp;lt; 300 || (response.status === 400 &amp;amp;&amp;amp; response.body.title === &amp;quot;Member Exists&amp;quot;)) {
                res.send(&amp;#039;Signed Up!&amp;#039;);
              } else {
                res.send(&amp;#039;Sign Up Failed :(&amp;#039;);
              }
          });
});
</pre>
<p>Here we&#8217;ve added variables for our three important pieces of information: MailChimp instance, unique list ID, and our API key. Then in our <code>post</code> handler, we&#8217;re making a <code>POST</code> request to the MailChimp list management REST API. We set the following HTTP Headers:</p>
<ul>
<li><code>Content-Type</code> &#8211; to be JSON and utf-8 characters</li>
<li><code>Authorization</code> &#8211; we base64 encode our MailChimp API key and pass it as the Basic auth token.</li>
</ul>
<p>Next we send the data for the new contact we want to add, including:</p>
<ul>
<li>Their email address;</li>
<li>What we want their status to be on the mailing list. This can be one-off: <code>subscribed</code>, <code>unsubscribed</code>, <code>pending</code>, and <code>cleaned</code>; and</li>
<li>The values we want to set for the <code>merge_fields</code> on this list. Merge fields allow you to add extra data to a contact in a mailing list. For example you could store phone numbers, dates of births, company names, etc. In this example we&#8217;ll just add the first name and last name</li>
</ul>
<p>Finally we listen for the response by registering an <code>end</code> handler. In here we check for two states initially. If the status is less than 300 it means the user was successfully added, or if we get back a HTTP status 400 but the title in the response says <code>Member Exists</code>, then the email address is already in this list. In both cases we can report back to the user that they have successfully signed up. If we get any other status code then something went wrong. In this situation, you&#8217;d likely want to let the user try again or raise an alert to yourself and manually fix it.</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/a996ec62b980f9addd55abaa.gif" alt="Testing Sign Up" title="Testing Sign Up" /></p>
<p>And if we go check out our MailChimp list, we should see one new member:</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/ddd85db9624ee571c7457cb3.png" alt="New Member Added To MailChimp" title="New Member Added To MailChimp" /></p>
<h2>2 &#8211; Letting your users integrate with their MailChimp account</h2>
<p>Now we&#8217;re adding our own users, wouldn&#8217;t it be awesome to let our users integrate our app with their MailChimp account? Some common use cases are:</p>
<ul>
<li>Perhaps you want to offer mailing list functionality without writing it yourself—for example if you&#8217;re writing a CRM, shopping platform, or a blogging service;</li>
<li>Import contacts to pre-fill your users contact list; or to</li>
<li>Create and Send campaign emails on their behalf from within your app.</li>
</ul>
<p>In our example, we take a quick look at how we could import all the contacts from an existing Mailing List in MailChimp into our own data store. We&#8217;ll do this in 3 stages:</p>
<ol>
<li>We&#8217;ll use OAuth and let the user grant us access to their MailChimp account</li>
<li>With that authentication granted we&#8217;ll grab the available Lists and pick which one they want to sync the members from</li>
<li>We&#8217;ll grab all the members and store them!</li>
</ol>
<p>So let&#8217;s get cracking!</p>
<h3>Using OAuth to get access to the users account</h3>
<p>In order to access another user&#8217;s account on MailChimp, we need to register ourselves as an App on the platform:</p>
<ul>
<li>Log in to your MailChimp account and go to <code>Profile</code> on the top right. Then on the <code>Profile</code> page, go to <code>Extras</code> -> <code>Registered apps</code>. Click <code>Register An App</code>. You&#8217;ll then be presented with a form to fill in the details of your app:</li>
</ul>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/1b8945281fbef62fac53199c.gif" alt="enter image description here" title="enter image title here" /></p>
<p>For the most part you can set these values to whatever makes sense. The really important one though is <code>Redirect URI</code>. This is the url in our application where MailChimp will redirect users once they&#8217;ve been authenticated. Since we&#8217;re going to run this on our local machine for now, we need to set this to:</p>
<p><code>http://127.0.0.1:3000/mailchimp/auth/callback</code></p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/d1fbfd6b85c0a076803a5858.png" alt="enter image description here" title="enter image title here" /></p>
<p>Once you&#8217;ve clicked <code>Create App</code> you&#8217;ll be told your app is created. On this page, scroll down and you&#8217;ll find two very important pieces of information:</p>
<ul>
<li><code>Client ID</code></li>
<li><code>Client Secret</code></li>
</ul>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/ab96efda42a3ae72c1c72a23.png" alt="enter image description here" title="enter image title here" /></p>
<p>Now let&#8217;s create a simple page in our <code>views</code> directory which will trigger our flow called <code>integrated-mailchimp.html</code>:</p>
<pre class="brush: xml; title: ; notranslate">
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
        &amp;lt;title&amp;gt;Integrate MailChimp&amp;lt;/title&amp;gt;
        &amp;lt;link href=&amp;quot;https://cdnjs.cloudflare.com/ajax/libs/spectre.css/0.1.25/spectre.min.css&amp;quot; rel=&amp;quot;stylesheet&amp;quot; crossorigin=&amp;quot;anonymous&amp;quot;&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;a class=&amp;quot;btn btn-primary&amp;quot; href=&amp;quot;/mailchimp/auth/authorize&amp;quot;&amp;gt;Connect with MailChimp&amp;lt;/a&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
</pre>
<p>Next we need to hook up an <code>express</code> handler to process the call to <code>/mailchimp/auth/authorize</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
var querystring = require(&amp;#039;querystring&amp;#039;);
var mailchimpClientId = &amp;#039;xxxxxxxxxxxxxxxx&amp;#039;;

app.get(&amp;#039;/mailchimp/auth/authorize&amp;#039;, function(req, res) {
  res.redirect(&amp;#039;https://login.mailchimp.com/oauth2/authorize?&amp;#039; +
            querystring.stringify({
                &amp;#039;response_type&amp;#039;: &amp;#039;code&amp;#039;,
                &amp;#039;client_id&amp;#039;: mailchimpClientId,
                &amp;#039;redirect_uri&amp;#039;: &amp;#039;http://127.0.0.1:3000/mailchimp/auth/callback&amp;#039;
            }));
});
</pre>
<p>Insert your MailChimp Client ID from earlier and then restart your server and hit our new page: <code>http://localhost:3000/integrate-mailchimp.html</code>:</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/d48340dba052aa6502101819.gif" alt="enter image description here" title="enter image title here" /></p>
<p>If you try it out, you should see that when you click the button you&#8217;re asked to log into MailChimp. Then afterwards you&#8217;re returned to a page on your local machine —this is perfect. Now we need to handle the OAuth callback from MailChimp.</p>
<p>The OAuth callback needs to do the following:</p>
<ul>
<li>Request an <code>access_token</code> for the user. This is needed to make all future requests for this user</li>
<li>Request for the OAuth <code>metadata</code> for the use. This provides information about which API Endpoint we need to talk to for this user</li>
<li>Save the above information for the user for future interactions with MailChimp</li>
</ul>
<p>Let&#8217;s see the code for this:</p>
<pre class="brush: jscript; title: ; notranslate">
var mailchimpSecretKey = &amp;#039;xxxxxxxxxxxxxxxxxxxx&amp;#039;;
var dataStore = require(&amp;#039;./dataStore.js&amp;#039;);

app.get(&amp;#039;/mailchimp/auth/callback&amp;#039;, function(req, res) {
  request.post(&amp;#039;https://login.mailchimp.com/oauth2/token&amp;#039;)
         .send(querystring.stringify({
            &amp;#039;grant_type&amp;#039;: &amp;#039;authorization_code&amp;#039;,
            &amp;#039;client_id&amp;#039;: mailchimpClientId,
            &amp;#039;client_secret&amp;#039;: mailchimpSecretKey,
            &amp;#039;redirect_uri&amp;#039;: &amp;#039;http://127.0.0.1:3000/mailchimp/auth/callback&amp;#039;,
            &amp;#039;code&amp;#039;: req.query.code
          }))
            .end((err, result) =&amp;gt; {
                if (err) {
                    res.send(&amp;#039;An unexpected error occured while trying to perform MailChimp oAuth&amp;#039;);
                } else {
                  // we need to get the metadata for the user
                  request.get(&amp;#039;https://login.mailchimp.com/oauth2/metadata&amp;#039;)
                    .set(&amp;#039;Accept&amp;#039;, &amp;#039;application/json&amp;#039;)
                    .set(&amp;#039;Authorization&amp;#039;, &amp;#039;OAuth &amp;#039; + result.body.access_token)
                        .end((err, metaResult) =&amp;gt; {
                            if (err) {
                                res.send(&amp;#039;An unexpected error occured while trying to get MailChimp meta oAuth&amp;#039;);
                            } else {
                                // save the result.body.access_token
                                // save the metadata in metaResult.body
                                // against the current user
                                var mailchimpConf = metaResult;
                                mailchimpConf.access_token = result.body.access_token;
                                dataStore.saveMailChimpForUser(mailchimpConf.login.email, metaResult);
                                res.redirect(&amp;#039;/pick-a-list.html?email=&amp;#039; + mailchimpConf.login.email)
                            }
                        });
                }
            });
});
</pre>
<p>To remind ourselves, the above handler will get called after the user has logged into MailChimp for us, and we&#8217;re given a temporary <code>code</code> with which we can request the long-lived <code>access_token</code>. Once we get the <code>access_token</code>, we immediately make a second REST call to get our user&#8217;s <code>metadata</code>. The <code>metadata</code> returned looks like:</p>
<p>{<br />
    &quot;dc&quot;: &quot;us6&quot;,<br />
    &quot;role&quot;: &quot;owner&quot;,<br />
    &quot;accountname&quot;: &quot;mattgoldspink&quot;,<br />
    &quot;user_id&quot;: 15048915,<br />
    &quot;login&quot;: {<br />
        &quot;email&quot;: &quot;mattgoldspink1@gmail.com&quot;,<br />
        &quot;avatar&quot;: null,<br />
        &quot;login_id&quot;: 15048915,<br />
        &quot;login_name&quot;: &quot;mattgoldspink&quot;,<br />
        &quot;login_email&quot;: &quot;mattgoldspink1@gmail.com&quot;<br />
    },<br />
    &quot;login_url&quot;: &quot;https://login.mailchimp.com&quot;,<br />
    &quot;api_endpoint&quot;: &quot;https://us6.api.mailchimp.com&quot;<br />
}</p>
<p>In the above JSON response, the most important piece of information is the <code>api_endpoint</code>. All future REST requests for this user to MailChimp must be made to this server.</p>
<p>For simplicity, I&#8217;ve created a very simple in memory <code>dataStore.js</code> file which looks like:</p>
<pre class="brush: jscript; title: ; notranslate">
var simpleInMemoryDataStore = {
    mailchimpConf: {}
};

module.exports = {
    saveMailChimpForUser: function(email, mailchimpConf) {
        simpleInMemoryDataStore.mailchimpConf[email] = mailchimpConf;
    },
    getMailChimpForUser: function(email) {
        return simpleInMemoryDataStore.mailchimpConf[email];
    }
};
</pre>
<p>I shall leave the real exercise of saving this information and the <code>access_token</code> as an exercise for the reader since everyone&#8217;s data storage solution is different.</p>
<h3>Getting the user&#8217;s lists</h3>
<p>Now we can start building a simple UI which lets the user select their List and then imports the Members. After connecting to MailChimp, we redirect the user to the <code>pick-a-list.html</code> page.</p>
<p>Let&#8217;s write this page:</p>
<pre class="brush: xml; title: ; notranslate">
&amp;lt;!doctype html&amp;gt;
&amp;lt;html&amp;gt;
    &amp;lt;head&amp;gt;
        &amp;lt;title&amp;gt;Pick A List From MailChimp&amp;lt;/title&amp;gt;
        &amp;lt;link href=&amp;quot;https://cdnjs.cloudflare.com/ajax/libs/spectre.css/0.1.25/spectre.min.css&amp;quot; rel=&amp;quot;stylesheet&amp;quot; crossorigin=&amp;quot;anonymous&amp;quot;&amp;gt;
    &amp;lt;/head&amp;gt;
    &amp;lt;body&amp;gt;
        &amp;lt;h1&amp;gt;Pick a List&amp;lt;/h1&amp;gt;
        &amp;lt;p&amp;gt;Choose which list to sync your Members from:
            &amp;lt;select id=&amp;quot;lists&amp;quot;&amp;gt;
                &amp;lt;option value=&amp;quot;null&amp;quot;&amp;gt;&amp;lt;/option&amp;gt;
            &amp;lt;/select&amp;gt;
        &amp;lt;/p&amp;gt;
        &amp;lt;script src=&amp;quot;https://code.jquery.com/jquery-2.2.4.min.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
        &amp;lt;script&amp;gt;
            $(function() {
                var queryParams = new URLSearchParams(location.search.slice(1));
                var mailingListSelect = $(&amp;#039;#lists&amp;#039;);
                // 1. make AJAX call for the list of Lists
                $.get(&amp;#039;/mailchimp/lists?email=&amp;#039; + queryParams.get(&amp;#039;email&amp;#039;), function(data) {
                    // 2. insert lists into DOM
                   data.forEach(function(mailchimpList) {
                        mailingListSelect.append(&amp;#039;&amp;lt;option value=&amp;quot;&amp;#039; + mailchimpList.id + &amp;#039;&amp;quot;&amp;gt;&amp;#039;+ mailchimpList.name + &amp;#039;(&amp;#039; + mailchimpList.stats.member_count  + &amp;#039; Members)&amp;#039; + &amp;#039;&amp;lt;/option&amp;gt;&amp;#039;);
                    });
                });
            });
        &amp;lt;/script&amp;gt;
    &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
</pre>
<p>I&#8217;ve kept the logic very simple here. When the page loads we get the <code>email</code> address from the url using <code>URLSearchParams</code>. Then we simply perform an ajax request to our backend to get all the mailing lists for the current user. Once that returns, we add them as <code>&lt;option&gt;</code>&#8216;s into our <code>select</code>.</p>
<p>The backend service that powers this looks like:</p>
<pre class="brush: jscript; title: ; notranslate">
app.get(&amp;#039;/mailchimp/lists&amp;#039;, function(req, res) {
  var mailchimpConf = dataStore.getMailChimpForUser(req.query.email);
  request.get(mailchimpConf.api_endpoint + &amp;#039;/3.0/lists&amp;#039;)
                .set(&amp;#039;Accept&amp;#039;, &amp;#039;application/json&amp;#039;)
                .set(&amp;#039;Authorization&amp;#039;, &amp;#039;OAuth &amp;#039; + mailchimpConf.access_token)
                    .end((err, result) =&amp;gt; {
                        if (err) {
                            res.status(500).json(err);
                        } else {
                            res.json(result.body.lists);
                        }
                    });
});
</pre>
<p>We simply retrieve the MailChimp configuration for the user from our <code>dataStore</code> and make a REST request to MailChimp&#8217;s list API. Notice that we construct the MailChimp REST API using the <code>api_endpoint</code> we stored for the user. We also have to pass the OAuth <code>access_token</code> for the user in order to authenticate to their account.</p>
<p>If you restart your server and re-authenticate with MailChimp, you should now see the <code>select</code> list in the page populated with your mailing lists!</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/102f59938f38c75017ffbed8.png" alt="enter image description here" title="enter image title here" /></p>
<h3>Getting a list&#8217;s members</h3>
<p>Now that we have all the user&#8217;s Mailing Lists when they choose one, we should go retrieve all the contacts in that list so that we can:</p>
<ul>
<li>display them in the UI</li>
<li>sync them to our database for the user.</li>
</ul>
<p>First, on our client side, we&#8217;ll update our <code>pick-a-list.html</code> page by adding:</p>
<ul>
<li>a simple HTML table to show the members </li>
<li>and a jQuery handler to listen to the selection change:</li>
</ul>
<pre class="brush: xml; title: ; notranslate">
        &amp;lt;h2&amp;gt;Members&amp;lt;/h2&amp;gt;
        &amp;lt;table id=&amp;quot;members&amp;quot; class=&amp;quot;table&amp;quot;&amp;gt;
            &amp;lt;thead&amp;gt;
                &amp;lt;th&amp;gt;Email&amp;lt;/th&amp;gt;
                &amp;lt;th&amp;gt;First Name&amp;lt;/th&amp;gt;
                &amp;lt;th&amp;gt;Last Name&amp;lt;/th&amp;gt;
            &amp;lt;/thead&amp;gt;
            &amp;lt;tbody&amp;gt;
            &amp;lt;/tbody&amp;gt;
        &amp;lt;/table&amp;gt;
        &amp;lt;script src=&amp;quot;https://code.jquery.com/jquery-2.2.4.min.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
        &amp;lt;script&amp;gt;
            $(function() {
                var queryParams = new URLSearchParams(location.search.slice(1));
                var mailingListSelect = $(&amp;#039;#lists&amp;#039;);
                // 1. make AJAX call for the list of Lists
                $.get(&amp;#039;/mailchimp/lists?email=&amp;#039; + queryParams.get(&amp;#039;email&amp;#039;),
                    // code from previous step
                );

                mailingListSelect.change(function() {
                    // 3. when an option is select then download the list of members
                    $.get(&amp;#039;/mailchimp/list/members/&amp;#039; + mailingListSelect.val() + &amp;#039;?email=&amp;#039; + queryParams.get(&amp;#039;email&amp;#039;) , function(data) {
                        var tbodyEl = $(&amp;#039;#members tbody&amp;#039;);
                        tbodyEl.html(&amp;#039;&amp;#039;);
                        data.forEach(function(member) {
                            tbodyEl.append(&amp;#039;&amp;lt;tr&amp;gt;&amp;lt;td&amp;gt;&amp;#039; + member.email_address + &amp;#039;&amp;lt;/td&amp;gt;&amp;lt;td&amp;gt;&amp;#039; + member.merge_fields.FNAME + &amp;#039;&amp;lt;/td&amp;gt;&amp;lt;td&amp;gt;&amp;#039; + member.merge_fields.LNAME + &amp;#039;&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;&amp;#039;);
                        });
                    });
                });
            });
        &amp;lt;/script&amp;gt;
</pre>
<p>So here we added a new part to the page which includes a simple html table to render our members. Then we added our <code>change</code> handler which makes an Ajax request to our backend to get the lists members. On responding, we simply clear the body of the table and add our new members.</p>
<p>Let&#8217;s take a look at our backend service for this:</p>
<pre class="brush: jscript; title: ; notranslate">
app.get(&amp;#039;/mailchimp/list/members/:id&amp;#039;, function(req, res) {
  var mailchimpConf = dataStore.getMailChimpForUser(req.query.email);
  request.get(mailchimpConf.api_endpoint + &amp;#039;/3.0/lists/&amp;#039; + req.params.id + &amp;#039;/members&amp;#039;)
                .set(&amp;#039;Accept&amp;#039;, &amp;#039;application/json&amp;#039;)
                .set(&amp;#039;Authorization&amp;#039;, &amp;#039;OAuth &amp;#039; + mailchimpConf.access_token)
                    .end((err, result) =&amp;gt; {
                        if (err) {
                            res.status(500).json(err);
                        } else {
                            res.json(result.body.members);
                        }
                    });
});
</pre>
<p>If you compare this to our earlier call to get the lists, you&#8217;ll see it&#8217;s almost identical. In fact all future API calls to MailChimp now become very simple!</p>
<p>If you restart your server and try this, then you&#8217;ll see the table will now populate once you select a mailing list:</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/bf01317e69525a1cf9945702.gif" alt="enter image description here" title="enter image title here" /></p>
<h2>3. Where to go from here?</h2>
<p>Now that you have the list of members, you can easily save them to your data store. Each member has an ID which is used to look it up in MailChimp. Therefore if you wanted to sync back changes to that user in MailChimp, you&#8217;d simply make an HTTP <code>PATCH</code> call to the members&#8217; endpoint. And in the request body, add these changes:</p>
<pre class="brush: jscript; title: ; notranslate">
request.patch(mailchimpConf.api_endpoint + &amp;#039;/3.0/lists/&amp;#039; + req.params.id + &amp;#039;/members/&amp;#039; + req.params.memberId)
                .set(&amp;#039;Accept&amp;#039;, &amp;#039;application/json&amp;#039;)
                .set(&amp;#039;Authorization&amp;#039;, &amp;#039;OAuth &amp;#039; + mailchimpConf.access_token)
                .send({&amp;quot;merge_fields&amp;quot;:{&amp;quot;FNAME&amp;quot;:&amp;quot;new&amp;quot;,&amp;quot;LNAME&amp;quot;:&amp;quot;name&amp;quot;})
                  .end(...)
</pre>
<p>The MailChimp REST API is extremely rich and supports viewing and editing all sorts of data, including:</p>
<ul>
<li>Adding notes to mailing list members.</li>
<li>Create new campaigns.</li>
<li>Create and view mail templates.</li>
<li>Display reports.</li>
<li>Even manage e-commerce stores.</li>
</ul>
<p>Checkout their API documentation for all the available endpoints you can interact with:</p>
<ul>
<li><a href="http://developer.mailchimp.com/documentation/mailchimp/reference/overview/">http://developer.mailchimp.com/documentation/mailchimp/reference/overview/</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/integrate-mailchimp-nodejs-app/">How to Integrate MailChimp with your NodeJS app</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/integrate-mailchimp-nodejs-app/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16539</post-id>	</item>
		<item>
		<title>Parse Dashboard on Heroku in 3 steps</title>
		<link>https://www.mattgoldspink.co.uk/parse-dashboard-heroku-3-steps/</link>
					<comments>https://www.mattgoldspink.co.uk/parse-dashboard-heroku-3-steps/#respond</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Wed, 20 Apr 2016 11:20:43 +0000</pubDate>
				<category><![CDATA[Parse Server]]></category>
		<category><![CDATA[heroku]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[parse]]></category>
		<guid isPermaLink="false">http://www.mattgoldspink.co.uk/?p=16534</guid>

					<description><![CDATA[<p>Parse Dashboard on Heroku in 3 steps This article was originally posted on codementor.io With the imminent shutdown of Parse, the team behind it have been hard at work open sourcing a replacement in the form of Parse Server. In addition, the team has also open-sourced the Parse Dashboard &#8211; the management dashboard that lets ...</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/parse-dashboard-heroku-3-steps/">Parse Dashboard on Heroku in 3 steps</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Parse Dashboard on Heroku in 3 steps</p>
<p>This article was originally posted on <a href="https://www.codementor.io/nodejs/tutorial/deploy-parse-dashboard-on-heroku" target="_blank">codementor.io</a></p>
<p>With the imminent shutdown of Parse, the team behind it have been hard at work open sourcing a replacement in the form of <a href="https://github.com/ParsePlatform/parse-server">Parse Server</a>. In addition, the team has also open-sourced the Parse Dashboard &#8211; the management dashboard that lets you view, query and manage all the data in your Parse instances.</p>
<p>There are plenty of articles for setting up Parse Server on different platforms but not much about setting up Parse Dashboard. In this article, we&#8217;ll go through the steps of getting Parse Dashboard deployed on Heroku free account in 15 minutes.</p>
<h2>Before we start</h2>
<p>You&#8217;ll need the following:</p>
<ul>
<li>Create an account on <a href="https://www.heroku.com">www.heroku.com</a></li>
<li>Make sure you have <a href="https://nodejs.org/">Node.js</a>, <a href="https://git-scm.com/downloads">Git</a> and the <a href="https://toolbelt.heroku.com/">Heroku Toolbelt</a> installed on your machine.</li>
</ul>
<h2>1) Get started</h2>
<p>We&#8217;re going to be doing everything in a shell/terminal.</p>
<pre class="brush: bash; title: ; notranslate">
$ mkdir my-parse-dashboard
 $ cd my-parse-dashboard
 $ git init
 $ npm init
 $ npm install --save parse-dashboard
</pre>
<p>For <code>npm init</code> you can enter anything that makes sense.</p>
<h2>2) Create 2 files</h2>
<p>Now we need to create 2 files: <code>parse-dashboard-config.json</code> and a <code>Procfile</code>:</p>
<h3>parse-dashboard-config.json</h3>
<p>{<br />
  &quot;apps&quot;: [<br />
    {<br />
      &quot;serverURL&quot;: &quot;https://api.parse.com/1&quot;, // For an app still hosted on Parse.com<br />
      &quot;appId&quot;: &quot;myAppId&quot;,<br />
      &quot;javascriptKey&quot;: &quot;myJavascriptKey&quot;,<br />
      &quot;restKey&quot;: &quot;myRestKey&quot;,<br />
      &quot;appName&quot;: &quot;My Parse.Com App&quot;,<br />
      &quot;production&quot;: true<br />
    },<br />
    {<br />
      &quot;serverURL&quot;: &quot;http://my-self-hosted.parse-server.com/parse&quot;,<br />
      &quot;appId&quot;: &quot;myAppId&quot;,<br />
      &quot;masterKey&quot;: &quot;myMasterKey&quot;,<br />
      &quot;appName&quot;: &quot;My Parse Server App&quot;<br />
    }<br />
  ],<br />
  &quot;users&quot;: [<br />
    {<br />
      &quot;user&quot;:&quot;user1&quot;,<br />
      &quot;pass&quot;:&quot;pass&quot; // change this to something secure<br />
    }<br />
  ]<br />
}</p>
<p>The <code>serverUrl</code> property can be either:<br />
&#8211; your own hosted version of parse-server on Heroku, AWS, Digital Ocean or wherever you have it setup<br />
&#8211; An app still hosted on Parse.com &#8211; in this case you&#8217;ll need to get the keys, from the existing dashboard on Parse.com</p>
<p>There are more examples and documentation here for the config file format: <a href="https://github.com/ParsePlatform/parse-dashboard">https://github.com/ParsePlatform/parse-dashboard</a></p>
<h3>Procfile</h3>
<p>The contents of this should be one line:</p>
<pre class="brush: bash; title: ; notranslate">
web: ./node_modules/.bin/parse-dashboard --config ./parse-dashboard-config.json --allowInsecureHTTP
</pre>
<p>This file tells Heroku how to launch your app.</p>
<p><strong>Important Note:</strong> In general the <code>--allowInsecureHTTP</code> flag should not be set as it means the data will be sent over HTTP and could susceptible to MITM attacks. However on Heroku this is needed because all apps are sat behind a proxy which terminates secure HTTPS requests for you. There is a ticket open on the dashboard project to improve this support for this https://github.com/ParsePlatform/parse-dashboard/issues/288. You should always access your app using the <em>https</em> protocol when.</p>
<h2>3) Commit it and let&#8217;s go live!</h2>
<p>Now it’s time to commit all of this to git:</p>
<pre class="brush: bash; title: ; notranslate">
$ git add package.json Procfile parse-dashboard-config.json 
$ git commit -m &amp;quot;My First Commit&amp;quot;
</pre>
<p>Then run:</p>
<pre class="brush: bash; title: ; notranslate">
$ heroku login 
 $ heroku create 
$ git push heroku master
 $ heroku ps:scale web=1
 $ heroku open
</pre>
<p>This will create a new app, a URL for you, push all the code to Heroku, kick off the web server and open your web browser to your new Parse Dashboard!</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/e6e027140bd7e9c6a3f14653.png" alt="Your Heroku Hosted Parse Dashboard" title="enter image title here" /></p>
<p>That’s it ☺ Not too bad, was it?</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/parse-dashboard-heroku-3-steps/">Parse Dashboard on Heroku in 3 steps</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/parse-dashboard-heroku-3-steps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16534</post-id>	</item>
		<item>
		<title>Is There Life After Parse? Parse Alternatives</title>
		<link>https://www.mattgoldspink.co.uk/parse-projects-next-steps/</link>
					<comments>https://www.mattgoldspink.co.uk/parse-projects-next-steps/#respond</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Tue, 23 Feb 2016 11:10:49 +0000</pubDate>
				<category><![CDATA[Parse Server]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[development process]]></category>
		<category><![CDATA[firebase]]></category>
		<category><![CDATA[parse]]></category>
		<guid isPermaLink="false">http://www.mattgoldspink.co.uk/?p=16531</guid>

					<description><![CDATA[<p>Parse Alternatives This post was originally posted on Codementor.io January 28th, 2015 was a whole new kind of Developer’s Black Thursday. Not too long after their Facebook acquisition, Parse made this announcement: We have a difficult announcement to make. Beginning today we&#8217;re winding down the Parse service, and Parse will be fully retired after a ...</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/parse-projects-next-steps/">Is There Life After Parse? Parse Alternatives</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Parse Alternatives</p>
<p>This post was originally posted on <a href="https://www.codementor.io/development-process/tutorial/what-to-do-after-parse-shuts-down" target="_blank">Codementor.io</a></p>
<p>January 28th, 2015 was a whole new kind of Developer’s Black Thursday. Not too long after their Facebook acquisition, Parse made this announcement:</p>
<blockquote><p>
  We have a difficult announcement to make. Beginning today we&#8217;re winding down the Parse service, and Parse will be fully retired after a year-long period ending on January 28, 2017. We&#8217;re proud that we&#8217;ve been able to help so many of you build great mobile apps, but we need to focus our resources elsewhere.
</p></blockquote>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/aad4de6878242fbcefbc00f5.png" alt="" title="" /></p>
<p>While it’s didn’t exactly hurt like the hundreds years old “it’s not you, it’s me” it caused a different kind of pain. One that started from a disbelief given their recent new features:</p>
<ul>
<li><a href="http://blog.parse.com/announcements/introducing-heroku-parse/">Oct 22nd 2015 &#8211; Parse on Heroku</a></li>
<li><a href="http://blog.parse.com/announcements/the-new-parse-developer-experience/">Dec 9th 2015 &#8211; New Awesome dashboard launched</a></li>
<li><a href="http://blog.parse.com/announcements/apple-tv-and-apple-watch-sdks-are-here/">Dec 14th 2015 &#8211; Apple TV and Watch Parse SDK&#8217;s launched</a></li>
<li><a href="http://blog.parse.com/learn/introducing-the-open-source-hub/">Dec 16th 2015 &#8211; Open Source hub of all their SDK&#8217;s</a></li>
<li><a href="http://blog.parse.com/announcements/moving-on/">Jan 28th 2015 &#8211; SHUT DOWN 🙁</a></li>
</ul>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/427ccb9f3dcbd1e5330b9b3a.jpg" alt="" title="" /></p>
<p>Like in any relationship, that feeling quickly turned into anger <strong>“what are they thinking? Don’t they know that like every other company’s existence depends on them?”</strong>, that turned into depression <strong>“my app/startup/life is over”</strong> and <strong>“FMLs”</strong> of all sorts, that then left room for the feeling that is here to stay:</p>
<h3>&#8220;What are we going to do next?&#8221;</h3>
<p>Parse provided everybody with some great tools to start with to help manage the anxiety, but let’s be honest- <strong>who wants to be one of the first ones to try the new solutions out?</strong> One of first ones to find out all the problems that a migration will cause, with no reference on how other people dealt with it?</p>
<p><strong>Exactly. Nobody does!</strong></p>
<p>If you are also affected by the <strong>Black Thursday of the Tech world</strong>, I hope I can help you get inspired by introducing you to a couple options that have already begun to emerge, thanks to brave developers who weren’t afraid of the unknown and who set on a mission to save the world- one Parse migration at a time.</p>
<p>Let’s start by taking a look at the general timeline. Parse recommends the following schedule:</p>
<ul>
<li>April 28, 2016: Data migrated to a self-hosted MongoDB</li>
<li>July 28, 2016: Finish setting up your self-hosted Parse Server and release a new app pointing to it </li>
</ul>
<p>Easier said than done. Here&#8217;s a link to Parse’s official migration guide, which I am not going to focus on since it&#8217;s been out for several weeks and re-iterating it wouldn’t be the best use of your time:</p>
<p><a href="https://github.com/ParsePlatform/parse-server/wiki/Parse-Server-Guide#migrating">https://github.com/ParsePlatform/parse-server/wiki/Parse-Server-Guide#migrating </a></p>
<p>As much as I wish I could offer a <strong>pain-free</strong>, <strong>quick</strong> and <strong>easy solution</strong>,  unfortunately, none exist that offer all the cool Parse features at a reasonable price&#8230; <strong>yet!</strong></p>
<h2>3 Great Parse Alternatives</h2>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/ac34e0164db641cbed88698e.jpg" alt="enter image description here" title="enter image title here" /></p>
<p>Instead of crying over spilled milk (or Parse code), let’s look at some alternatives!</p>
<h3>ParseGround</h3>
<p><a href="http://www.parseground.com/?ref=FIR416"> www.parseground.com</a></p>
<p>Let’s start with one of the solutions I&#8217;m personally very excited about. ParseGround is from the team at and while as of today it is still in the Early Access waitlist phase, it looks quite promising.</p>
<p>Some key features?</p>
<ul>
<li><strong>Free migration</strong></li>
<li><strong>24/7 support</strong> (As programmers we know, use &amp; support NodeJS &amp; MongoDB. And we&#8217;ll help you with optimization).</li>
<li><strong>Global Hosting</strong></li>
<li><strong>Automated Scaling</strong></li>
</ul>
<p>And with that, they claim that you will still get to have full control of the Parse Server code and instances in case you decide to customize it. All of this starting at <strong>$4.95 a month</strong> (1M monthly requests) and there is no limit of monthly requests &amp; req. per second, storage, database and file transfer. Doesn’t sound too bad, does it? For the Cons of this alternative, we will have to wait and see what comes out as it is still in its early stages, but it does make me feel hopeful.</p>
<h3>AWS</h3>
<p><a href="https://aws.amazon.com/">https://aws.amazon.com/</a></p>
<p>This option is definitely at the other end of a spectrum compared to ParseGround. AWS can replace almost all the Parse features, from the cloud code to push notifications, and it provides analytics functionalities. It’s an incredibly robust, scalable solution that is well battled-tested by a lot of huge companies.</p>
<p>One of the biggest disadvantages is that it can get complicated, quickly! However there are good solutions to scaling like using <strong>Elastic Beanstalk</strong> for the Parse Server, file storage using <strong>S3</strong>, notifications using <strong>Amazon SNS</strong> and more. Plus there is a huge amount of blog posts, stack overflow questions and general knowledge about the pitfalls of and recommendations for AWS.</p>
<p>It is very fairly priced and it does have generous limits. Just be prepared to get your hands dirty!</p>
<h3>Firebase</h3>
<p> <a href="https://www.firebase.com/">https://www.firebase.com/</a></p>
<p>Firebase is argued by many to be the number one alternative to Parse. It’s biggest fans claim that you won’t even notice the lack of features such as Parse’s built-in push notifications, as you can use similar services to make up for that. In the light of the Parse announcement, it might be worth mentioning that Google said that it will support Firebase indefinitely, but you never know with those guys these days ☺</p>
<p>Firebase does not provide a an easy way to add Cloud Code, but it is a multi-platform solution that works offline, and it offers hosting as well as a real-time database.</p>
<p>They also offer a <strong>free plan</strong> if you’re platform is modest, but can go up all the way to $1499 for the robust ones.</p>
<h2>Conclusion</h2>
<p>All in all, there are definitely options out there. But at the end of the day, we all know what is going to happen as the transition deadline approaches, and it can be summed up in this one picture:</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/3131bada4573e18ad4a0103d.jpg" alt="" title="" /></p>
<p>Let us know if you found an exciting solution to the Parse transition problem in the comments&#8211;myself (and the entire Code Mentor community) would be delighted to learn as much as possible before those deadlines approach!</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/parse-projects-next-steps/">Is There Life After Parse? Parse Alternatives</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/parse-projects-next-steps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16531</post-id>	</item>
		<item>
		<title>20 iOS Developer Interview Questions</title>
		<link>https://www.mattgoldspink.co.uk/20-ios-developer-interview-questions/</link>
					<comments>https://www.mattgoldspink.co.uk/20-ios-developer-interview-questions/#respond</comments>
		
		<dc:creator><![CDATA[Matt Goldspink]]></dc:creator>
		<pubDate>Wed, 02 Dec 2015 10:30:16 +0000</pubDate>
				<category><![CDATA[iOS]]></category>
		<category><![CDATA[interview questions]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[objective-c]]></category>
		<guid isPermaLink="false">http://www.mattgoldspink.co.uk/?p=16520</guid>

					<description><![CDATA[<p>20 iOS Developer Interview Questions This article was originally posted on Codementor.io Getting ready for your iOS interview The big day is coming up. Whether it’s a phone, online or in person interview it is always a little bit stressful. So, to ease the stress you did some prep work- completed the homework on the ...</p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/20-ios-developer-interview-questions/">20 iOS Developer Interview Questions</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>20 iOS Developer Interview Questions</p>
<p>This article was originally posted on <a href="https://www.codementor.io/ios/tutorial/ios-interview-tips-questions-answers-objective-c" target="_blank">Codementor.io</a></p>
<h2>Getting ready for your iOS interview</h2>
<p>The big day is coming up. Whether it’s a phone, online or in person interview it is always a little bit stressful.  So, to ease the stress you did some prep work- completed the homework on the company you are interviewing with, stalked the hiring manager and half of the engineering team at the company of your choice on linkedin &amp; github, you brushed up on some of the skills and knowledge you haven’t used in a while- you are ready to go.</p>
<p>But following US Navy Seals motto <strong>“Two is one and one is none”</strong> let’s go through another quick refresher to help you ace that iOS interview. So let’s get right into it!</p>
<p>Let’s start with some of the basic questions that I hope you are already ready for. They might seem obvious, but you would be shocked how many engineers failed miserably at them during the 12 years I have been doing technical interviews.</p>
<h1>Technical Questions</h1>
<p>Ok, now that we’ve got that covered, let’s jump into the technical questions.</p>
<h2>Question 1</h2>
<p><strong>On a UITableViewCell constructor:</strong></p>
<p>&#8211; (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier</p>
<p><strong>What is the <code>reuseIdentifier</code> used for?</strong></p>
<p>The <code>reuseIdentifier</code> is used to indicate that a cell can be re-used in a <code>UITableView</code>. For example when the cell looks the same, but has different content. The <code>UITableView</code> will maintain an internal cache of <code>UITableViewCell</code>’s with the <code>reuseIdentifier</code> and allow them to be re-used when <code>dequeueReusableCellWithIdentifier:</code> is called. By re-using table cell’s the scroll performance of the tableview is better because new views do not need to be created.</p>
<h2>Question 2</h2>
<p><strong>Explain the difference between atomic and nonatomic synthesized properties?</strong></p>
<p>Atomic and non-atomic refers to whether the setters/getters for a property will atomically read and write values to the property. When the atomic keyword is used on a property, any access to it will be “synchronized”. Therefore a call to the getter will be guaranteed to return a valid value, however this does come with a small performance penalty. Hence in some situations nonatomic is used to provide faster access to a property, but there is a chance of a race condition causing the property to be nil under rare circumstances (when a value is being set from another thread and the old value was released from memory but the new value hasn’t yet been fully assigned to the location in memory for the property).</p>
<h2>Question 3</h2>
<p><strong>Explain the difference between copy and retain?</strong></p>
<p>Retaining an object means the retain count increases by one. This means the instance of the object will be kept in memory until it’s retain count drops to zero. The property will store a reference to this instance and will share the same instance with anyone else who retained it too. Copy means the object will be cloned with duplicate values. It is not shared with any one else.</p>
<h2>Question 4</h2>
<p><strong>What is method swizzling in Objective C and why would you use it?</strong></p>
<p>Method swizzling allows the implementation of an existing selector to be switched at runtime for a different implementation in a classes dispatch table. Swizzling allows you to write code that can be executed before and/or after the original method. For example perhaps to track the time method execution took, or to insert log statements</p>
<p>#import &quot;UIViewController+Log.h&quot;<br />
@implementation UIViewController (Log)<br />
    + (void)load {<br />
        static dispatch_once_t once_token;<br />
        dispatch_once(&amp;once_token,  ^{<br />
            SEL viewWillAppearSelector = @selector(viewDidAppear:);<br />
            SEL viewWillAppearLoggerSelector = @selector(log_viewDidAppear:);<br />
            Method originalMethod = class_getInstanceMethod(self, viewWillAppearSelector);<br />
            Method extendedMethod = class_getInstanceMethod(self, viewWillAppearLoggerSelector);<br />
            method_exchangeImplementations(originalMethod, extendedMethod);<br />
        });<br />
    }<br />
    &#8211; (void) log_viewDidAppear:(BOOL)animated {<br />
        [self log_viewDidAppear:animated];<br />
        NSLog(@&quot;viewDidAppear executed for %@&quot;, [self class]);<br />
    }<br />
@end</p>
<h2>Question 5</h2>
<p>What’s the difference between not-running, inactive, active, background and suspended execution states?</p>
<ul>
<li><strong>Not running:</strong> The app has not been launched or was running but was terminated by the system.</li>
<li><strong>Inactive:</strong> The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state.</li>
<li><strong>Active:</strong> The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.</li>
<li><strong>Background:</strong> The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state.</li>
<li><strong>Suspended:</strong> The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.</li>
</ul>
<h2>Question 6</h2>
<p><strong>What is a category and when is it used?</strong></p>
<p>A category is a way of adding additional methods to a class without extending it. It is often used to add a collection of related methods. A common use case is to add additional methods to built in classes in the Cocoa frameworks. For example adding async download methods to the <code>UIImage</code> class.</p>
<h2>Question 7</h2>
<p><strong>Can you spot the bug in the following code and suggest how to fix it:</strong></p>
<p>@interface MyCustomController : UIViewController  </p>
<p>@property (strong, nonatomic) UILabel *alert;  </p>
<p>@end  </p>
<p>@implementation MyCustomController  </p>
<p>&#8211; (void)viewDidLoad {<br />
     CGRect frame = CGRectMake(100, 100, 100, 50);<br />
     self.alert = [[UILabel alloc] initWithFrame:frame];<br />
     self.alert.text = @&quot;Please wait&#8230;&quot;;<br />
     [self.view addSubview:self.alert];<br />
      dispatch_async(<br />
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),<br />
        ^{<br />
           sleep(10);<br />
           self.alert.text = @&quot;Waiting over&quot;;<br />
        }<br />
    );<br />
}  </p>
<p>@end  </p>
<p>All UI updates must be done on the main thread. In the code above the update to the alert text may or may not happen on the main thread, since the global dispatch queue makes no guarantees . Therefore the code should be modified to always run the UI update on the main thread</p>
<p>dispatch_async(<br />
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),<br />
    ^{<br />
      sleep(10);<br />
      dispatch_async(dispatch_get_main_queue(), ^{<br />
         self.alert.text = @&quot;Waiting over&quot;;<br />
      });<br />
}); </p>
<h2>Question 8</h2>
<p><strong>What is the difference between <code>viewDidLoad</code> and <code>viewDidAppear</code>? Which should you use to load data from a remote server to display in the view?</strong></p>
<p><code>viewDidLoad</code> is called when the view is loaded, whether from a Xib file, storyboard or programmatically created in <code>loadView</code>. <code>viewDidAppear</code> is called every time the view is presented on the device. Which to use depends on the use case for your data. If the data is fairly static and not likely to change then it can be loaded in <code>viewDidLoad</code> and cached. However if the data changes regularly then using <code>viewDidAppear</code> to load it is better. In both situations, the data should be loaded asynchronously on a background thread to avoid blocking the UI.</p>
<h2>Question 9</h2>
<p><strong>What considerations do you need when writing a <code>UITableViewController</code> which shows images downloaded from a remote server?</strong></p>
<p>This is a very common task in iOS and a good answer here can cover a whole host of knowledge. The important piece of information in the question is that the images are hosted remotely and they may take time to download, therefore when it asks for “considerations”, you should be talking about:</p>
<ul>
<li>Only download the image when the cell is scrolled into view, i.e. when <code>cellForRowAtIndexPath</code> is called.</li>
<li>Downloading the image asynchronously on a background thread so as not to block the UI so the user can keep scrolling.</li>
<li>When the image has downloaded for a cell we need to check if that cell is still in the view or whether it has been re-used by another piece of data. If it’s been re-used then we should discard the image, otherwise we need to switch back to the main thread to change the image on the cell.</li>
</ul>
<p>Other good answers will go on to talk about offline caching of the images, using placeholder images while the images are being downloaded.</p>
<h2>Question 10</h2>
<p><strong>What is a protocol, how do you define your own and when is it used?</strong></p>
<p>A protocol is similar to an interface from Java. It defines a list of required and optional methods that a class must/can implement if it adopts the protocol. Any class can implement a protocol and other classes can then send messages to that class based on the protocol methods without it knowing the type of the class.</p>
<p>@protocol MyCustomDataSource<br />
&#8211; (NSUInteger)numberOfRecords;<br />
&#8211; (NSDictionary *)recordAtIndex:(NSUInteger)index;<br />
@optional<br />
&#8211; (NSString *)titleForRecordAtIndex:(NSUInteger)index;<br />
@end</p>
<p>A common use case is providing a DataSource for <code>UITableView</code> or <code>UICollectionView</code>.</p>
<h2>Question 11</h2>
<p><strong>What is KVC and KVO? Give an example of using KVC to set a value.</strong></p>
<p><em>KVC</em> stands for <em>Key-Value Coding</em>. It&#8217;s a mechanism by which an object&#8217;s properties can be accessed using string&#8217;s at runtime rather than having to statically know the property names at development time. <em>KVO</em> stands for <em>Key-Value Observing</em> and allows a controller or class to observe changes to a property value.</p>
<p>Let&#8217;s say there is a property <code>name</code> on a class:</p>
<p>@property (nonatomic, copy) NSString *name;</p>
<p>We can access it using KVC:</p>
<p>NSString *n = [object valueForKey:@&quot;name&quot;]</p>
<p>And we can modify it&#8217;s value by sending it the message:</p>
<p>[object setValue:@&quot;Mary&quot; forKey:@&quot;name&quot;]</p>
<h2>Question 12</h2>
<p><strong>What are blocks and how are they used?</strong></p>
<p>Blocks are a way of defining a single task or unit of behavior without having to write an entire Objective-C class. Under the covers Blocks are still Objective C objects. They are a language level feature that allow programming techniques like lambdas and closures to be supported in Objective-C. Creating a block is done using the <code>^ { }</code> syntax:</p>
<p> myBlock = ^{<br />
    NSLog(@&quot;This is a block&quot;);<br />
 }</p>
<p>It can be invoked like so:</p>
<p>myBlock();</p>
<p>It is essentially a function pointer which also has a signature that can be used to enforce type safety at compile and runtime. For example you can pass a block with a specific signature to a method like so:</p>
<p>&#8211; (void)callMyBlock:(void (^)(void))callbackBlock;</p>
<p>If you wanted the block to be given some data you can change the signature to include them:</p>
<p>&#8211; (void)callMyBlock:(void (^)(double, double))block {<br />
    &#8230;<br />
    block(3.0, 2.0);<br />
}</p>
<h2>Question 13</h2>
<p><strong>What mechanisms does iOS provide to support multi-threading?</strong></p>
<ul>
<li><code>NSThread</code> creates a new low-level thread which can be started by calling the <code>start</code> method.</li>
</ul>
<p>NSThread* myThread = [[NSThread alloc] initWithTarget:self<br />
                                        selector:@selector(myThreadMainMethod:)<br />
                                        object:nil];<br />
[myThread start]; </p>
<ul>
<li><code>NSOperationQueue</code> allows a pool of threads to be created and used to execute <code>NSOperation</code>s in parallel. <code>NSOperation</code>s can also be run on the main thread by asking <code>NSOperationQueue</code> for the <code>mainQueue</code>.</li>
</ul>
<p>NSOperationQueue* myQueue = [[NSOperationQueue alloc] init];<br />
[myQueue addOperation:anOperation];<br />
[myQueue addOperationWithBlock:^{<br />
   /* Do something. */<br />
}];</p>
<ul>
<li><em>GCD</em> or <em>Grand Central Dispatch</em> is a modern feature of Objective-C that provides a rich set of methods and API&#8217;s to use in order to support common multi-threading tasks. <em>GCD</em> provides a way to queue tasks for dispatch on either the main thread, a concurrent queue (tasks are run in parallel) or a serial queue (tasks are run in FIFO order).</li>
</ul>
<p>dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);<br />
dispatch_async(myQueue, ^{<br />
    printf(&quot;Do some work here.\n&quot;);<br />
});</p>
<h2>Question 14</h2>
<p><strong>What is the Responder Chain?</strong></p>
<p>When an event happens in a view, for example a touch event, the view will fire the event to a chain of <code>UIResponder</code> objects associated with the <code>UIView</code>. The first <code>UIResponder</code> is the <code>UIView</code> itself, if it does not handle the event then it continues up the chain to until <code>UIResponder</code> handles the event. The chain will include <code>UIViewController</code>s, parent <code>UIView</code>s and their associated <code>UIViewController</code>s, if none of those handle the event then the <code>UIWindow</code> is asked if it can handle it and finally if that doesn&#8217;t handle the event then the <code>UIApplicationDelegate</code> is asked.</p>
<p>If you get the opportunity to draw this one out, it&#8217;s worth doing to impress the interviewer:</p>
<p><img src="https://www.mattgoldspink.co.uk/static/article-images/b8d6bbbfdac61aa7611efc49.png" alt="enter image description here" title="enter image title here" /></p>
<h2>Question 15</h2>
<p><strong>What&#8217;s the difference between using a <em>delegate</em> and <em>notification</em>?</strong></p>
<p>Both are used for sending values and messages to interested parties. A <em>delegate</em> is for one-to-one communication and is a pattern promoted by Apple. In <em>delegation</em> the class raising events will have a property for the <em>delegate</em> and will typically expect it to implement some <code>protocol</code>. The <em>delegating</em> class can then call the _delegate_s protocol methods.</p>
<p><em>Notification</em> allows a class to broadcast events across the entire application to any interested parties. The broadcasting class doesn&#8217;t need to know anything about the listeners for this event, therefore <em>notification</em> is very useful in helping to decouple components in an application.</p>
<p>[NSNotificationCenter defaultCenter]<br />
        postNotificationName:@&quot;TestNotification&quot;<br />
        object:self];</p>
<h2>Question 16</h2>
<p><strong>What&#8217;s your preference when writing UI&#8217;s? Xib files, Storyboards or programmatic <code>UIView</code>?</strong></p>
<p>There&#8217;s no right or wrong answer to this, but it&#8217;s great way of seeing if you understand the benefits and challenges with each approach. Here&#8217;s the common answers I hear:</p>
<ul>
<li>Storyboard&#8217;s and Xib&#8217;s are great for quickly producing UI&#8217;s that match a design spec. They are also really easy for product managers to visually see how far along a screen is.</li>
<li>Storyboard&#8217;s are also great at representing a flow through an application and allowing a high-level visualization of an entire application.</li>
<li>Storyboard&#8217;s drawbacks are that in a team environment they are difficult to work on collaboratively because they&#8217;re a single file and merge&#8217;s become difficult to manage.</li>
<li>Storyboards and Xib files can also suffer from duplication and become difficult to update. For example if all button&#8217;s need to look identical and suddenly need a color change, then it can be a long/difficult process to do this across storyboards and xibs.</li>
<li>Programmatically constructing <code>UIView</code>&#8216;s can be verbose and tedious, but it can allow for greater control and also easier separation and sharing of code. They can also be more easily unit tested.</li>
</ul>
<p>Most developers will propose a combination of all 3 where it makes sense to share code, then re-usable <code>UIView</code>s or <code>Xib</code> files.</p>
<h2>Question 17</h2>
<p><strong>How would you securely store private user data offline on a device? What other security best practices should be taken?</strong></p>
<p>Again there is no right answer to this, but it&#8217;s a great way to see how much a person has dug into iOS security. If you&#8217;re interviewing with a bank I&#8217;d almost definitely expect someone to know something about it, but all companies need to take security seriously, so here&#8217;s the ideal list of topics I&#8217;d expect to hear in an answer:</p>
<ul>
<li>If the data is extremely sensitive then it should never be stored offline on the device because all devices are crackable.</li>
<li>The keychain is one option for storing data securely. However it&#8217;s encryption is based on the pin code of the device. User&#8217;s are not forced to set a pin, so in some situations the data may not even be encrypted. In addition the users pin code may be easily hacked.</li>
<li>A better solution is to use something like <a href="https://www.zetetic.net/sqlcipher/">SQLCipher</a> which is a fully encrypted SQLite database. The encryption key can be enforced by the application and separate from the user&#8217;s pin code.</li>
</ul>
<p>Other security best practices are:</p>
<ul>
<li>Only communicate with remote servers over SSL/HTTPS.</li>
<li>If possible implement certificate pinning in the application to prevent man-in-the-middle attacks on public WiFi.</li>
<li>Clear sensitive data out of memory by overwriting it.</li>
<li>Ensure all validation of data being submitted is also run on the server side.</li>
</ul>
<h2>Question 18</h2>
<p><strong>What is MVC? How is it implemented in iOS? What are some pitfalls you&#8217;ve experienced with it? Are there any alternatives to MVC?</strong></p>
<p><em>MVC</em> stands for <em>Model, View, Controller</em>. It is a design pattern that defines how to separate out logic when implementing user interfaces. In iOS, Apple provides <code>UIView</code> as a base class for all <em>View_s, <code>UIViewController</code> is provided to support the _Controller</em> which can listen to events in a <em>View</em> and update the <em>View</em> when data changes. The <em>Model</em> represents data in an application and can be implemented using any <code>NSObject</code>, including data collections like <code>NSArray</code> and <code>NSDictionary</code>.</p>
<p>Some of the pitfalls that people hit are bloated <code>UIViewController</code> and not separating out code into classes beyond the MVC format. I&#8217;d highly recommend reading up on some solutions to this:</p>
<ul>
<li><a href="https://www.objc.io/issues/1-view-controllers/lighter-view-controllers/">https://www.objc.io/issues/1-view-controllers/lighter-view-controllers/</a></li>
<li><a href="https://speakerdeck.com/trianglecocoa/unburdened-viewcontrollers-by-jay-thrash">https://speakerdeck.com/trianglecocoa/unburdened-viewcontrollers-by-jay-thrash</a></li>
<li><a href="https://programmers.stackexchange.com/questions/177668/how-to-avoid-big-and-clumsy-uitableviewcontroller-on-ios">https://programmers.stackexchange.com/questions/177668/how-to-avoid-big-and-clumsy-uitableviewcontroller-on-ios</a></li>
</ul>
<p>In terms of alternatives, this is pretty open ended. The most common alternative is MVVM using ReactiveCocoa, but others include VIPER and using Functional Reactive code.</p>
<h2>Question 19</h2>
<p><strong>A product manager in your company reports that the application is crashing. What do you do?</strong></p>
<p>This is a great question in any programming language and is really designed to see how you problem solve. You&#8217;re not given much information, but some interviews will slip you more details of the issue as you go along. Start simple:</p>
<ul>
<li>get the exact steps to reproduce it. </li>
<li>find out the device, iOS version.</li>
<li>do they have the latest version?</li>
<li>get device logs if possible.</li>
</ul>
<p>Once you can reproduce it or have more information then start using tooling. Let&#8217;s say it crashes because of a memory leak, I&#8217;d expect to see someone suggest using <em>Instruments</em> leak tool. A really impressive candidate would start talking about writing a unit test that reproduces the issue and debugging through it.</p>
<p>Other variations of this question include slow UI or the application freezing. Again the idea is to see how you problem solve, what tools do you know about that would help and do you know how to use them correctly.</p>
<h2>Question 20</h2>
<p><strong>What is AutoLayout? What does it mean when a constraint is &#8220;broken&#8221; by iOS?</strong></p>
<p><em>AutoLayout</em> is way of laying out <code>UIView</code>s using a set of constraints that specify the location and size based relative to other views or based on explicit values. <em>AutoLayout</em> makes it easier to design screens that resize and layout out their components better based on the size and orientation of a screen. _Constraint_s include:</p>
<ul>
<li>setting the horizontal/vertical distance between 2 views</li>
<li>setting the height/width to be a ratio relative to a different view</li>
<li>a width/height/spacing can be an explicit static value</li>
</ul>
<p>Sometimes constraints conflict with each other. For example imagine a <code>UIView</code> which has 2 height constraints: one says make the <code>UIView</code> 200px high, and the second says make the height twice the height of a button. If the iOS runtime can not satisfy both of these constraints then it has to pick only one. The other is then reported as being &#8220;broken&#8221; by iOS.</p>
<h2>Standard Questions</h2>
<h3>“Tell me about yourself”.</h3>
<p>This is a REALLY tricky one! So many people read their resume out loud (forgetting I am looking right at it!), listing every class they took in college, every position they have ever held (and that really adds up for the Senior Level Engineers) and every responsibility (which often times happen to be the same across 2 or 3 companies that particular person has worked at. So, 20 minutes later, I still don’t know anything new/outside of the resume about the candidate, we are 20 minutes in, and by then I believe that they might as well be robots (and robots tend to not fit very well with dynamic teams).</p>
<p>So do yourself (and the hiring manager) a favor by preparing a 2min long elevator pitch of your background- keep it simple, concise and brief, and then add something personal at the end. Do you love running? Are you coaching your daughter’s soccer team?  Die hard Star Wars fan? Adding a little bit of personality in is a great ice breaker, and will make for an amazing transition into the deeper part of the interview.</p>
<h3>&#8220;Describe an interesting problem and how you solved it.&#8221;</h3>
<p>Your chance of hearing this one is basically 99%, so you better have a great answer ready for them! Here are a few tips: think of a particularly amazing project that you are proud of. Got it? Great! Now, grab a piece of paper and summarize it in 5 bullet points.<br />
1st bullet point- very brief backstory of the circumstances behind the project<br />
2nd bullet- the nature of the project itself<br />
3rd bullet- the problems you have came across while solving it/them<br />
4thbullet- how did you solve the difficulties above<br />
5th bullet point- what have you learned from it.</p>
<p>Now, find somebody who will listen (a friend, partner, colleague) and ask them if the story makes sense (minus any technical aspects of it if the person you are talking with isn’t your peer).  It’s a great way to validate if the story holds itself together.</p>
<p>You would be shocked how many times I have heard things like “and then I went to John, and he used the tool he has created to remove the critical bug which then……”. Who is Tom? Your manager? Intern? Peer? Why did you go to him of everybody in your company? What is that magical tool that he has put together? Which critical bug exactly did it remove and how? What was the outcome?</p>
<p>You get the idea 🙂</p>
<p>Additional bonus? You now have 5 bullet points you can use as a cheat sheet during your interview without looking like THAT guy who is reading his resume out loud.</p>
<p><strong>Now let’s jump into the WEIRD questions that some hiring managers like to throw in to tip you off your game.</strong></p>
<ul>
<li>How would you test a toaster?</li>
<li>How many pens can you fit into an airplane?</li>
<li>How many windows are in San Francisco?</li>
<li>How many golf balls can fit in a school bus?</li>
<li>How many Big Macs does McDonald&#8217;s sell each year in the U.S.?</li>
</ul>
<p>The list goes on and on. While it has nothing to do with your technical skills, it does a good job of checking how you deal with curve balls, and to see if you are capable of logical step-by step problem solving. In most cases, there aren’t perfect answers to those type of questions (though you can google them for your peace of mind). It is all about how you explain your logic to your interviewer.</p>
<p>Here is the answer to the golf balls question by Michael Beauchamp, so you get the idea of what I am talking about:</p>
<blockquote><p>
  I figure a standard school bus is about 8ft wide by 6ft high by 20 feet long &#8211; this is just a guess based on the thousands of hours I have been trapped behind school buses while traffic in all directions is stopped.</p>
<p>  That means 960 cubic feet and since there are 1728 cubic inches in a cubit foot, that means about 1.6 million cubic inches.</p>
<p>  I calculate the volume of a golf ball to be about 2.5 cubic inches (4/3 * pi * .85) as .85 inches is the radius of a golf ball.</p>
<p>  Divide that 2.5 cubic inches into 1.6 million and you come up with 660,000 golf balls. However, since there are seats and crap in there taking up space and also since the spherical shape of a golf ball means there will be considerable empty space between them when stacked, I&#8217;ll round down to 500,000 golf balls.
</p></blockquote>
<p>See? Step by step. And suddenly it’s a relatively simple, logical question. Just stay calm, and instead of trying to come up with an instant number in your head, walk the interviewer through your train of thoughts with you.</p>
<hr />
<p><em>Need real life practice? Feel free to <a href="https://www.codementor.io/mattgoldspink">schedule a mock interview</a> with Matt, who has been doing technical interviews for 12 years, and ask for his feedback!</em></p>
<p>The post <a rel="nofollow" href="https://www.mattgoldspink.co.uk/20-ios-developer-interview-questions/">20 iOS Developer Interview Questions</a> appeared first on <a rel="nofollow" href="https://www.mattgoldspink.co.uk">Matt Goldspink</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mattgoldspink.co.uk/20-ios-developer-interview-questions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">16520</post-id>	</item>
	</channel>
</rss>
