Blog

Categories: Life

Latest Updates – June 2018

Here are some of the latest updates:

  1. Passed the CAPM Certified Associate in Project Management exam, which means that yes I can manage projects and lead your team.
  2. Produced a (short) video on using Local Storage for caching with AngularJS (this is a supplement to the article I wrote about the subject).
  3. Updated the article on evaluating projects with an infographic
  4. My presentation at PyCon Canada 2017 on Python as a Philosophy has been viewed thousands of times! (Update: the re-posted video at 8,000+ views was removed, the official PyCon Canada link is still up)
  5. Wrote an article on reactive programming with Ruby, Python and JavaScript

More blog posts on Angular, Ruby on Rails, and Reactive Programming are on the way along with articles on coaching and tech leadership!

Categories: Web Dev Training

Reactive Programming with JavaScript, Ruby and Python – Part 1

Reactive programming is a concept that is finally gaining some popularity among programmers. It makes it easier to think in data flows and to manage and work with them. Instead of imperative programming, you’re thinking about code as a series of processes that take place on streams.

This is similar to the conceptual shift to map/reduce thinking. But it takes those ideas further. You’re doing a map/reduce and then connecting the data to other filters and maps and creating multiple pipelines so that the right data gets to the right place.

For example, when a user clicks a button in a web app (or desktop app), that click event can be propagated through the system to all the subscribers that are listening and waiting for that event.

When working with the Angular frontend web framework, that latest versions are now using RxJS, the reactive programming library for JavaScript. It is the underlying framework for working with events. Previously in AngularJS 1.x you would use the broadcast and emit system to act on events. With Reactive, you have a generalized library for working with observables and subscribers which can work well with other libraries and other JavaScript code.

In Ruby and Python, other concepts have held sway for a long time, so here are some examples on how to do reactive programming Ruby and how to do reactive programming in Python.

These are basic examples of filtering and creating observables, think of them as the equivalent of “Hello World”, in part 2 we will explore more advanced usages.

You can find a list of other languages that are supported with a reactive library on the ReactiveX website.

Reactive Programming: JavaScript Example

Let’s begin by creating an observable:

var numbers = [1,2,3,4,5];
var all = Rx.Observable.from(numbers);

This observable is being created from a list of numbers. It’s possible to convert other types of lists into Observables.

Next we want to print out all of the numbers. We do this by subscribing to the observable with a function:

all.subscribe(function(number) {
 console.log("The number is " + number);
});

Right now this looks like a for loop, but remember that observables are meant for events in time. There could be milliseconds or seconds or minutes between each event that the observable is emitting to the subscriber.

Next, let’s create a new flow of data by filtering all of the numbers so we only receive even numbers in our subscriber:

var only_evens = all.filter(function(number) {
  return number % 2 === 0;
});

Again we print out the numbers and you will notice that we only print out even numbers:

only_evens.subscribe(function(number) {
   console.log("This number is even: " + number);
});

That was a simple example of creating two flows; one with all values, and a filtered flow of values.

Now imagine in your next web app, a user does any action. That action is sent through an observable and we can have a subscriber that waits for a specific button click action or subscribes to any button click.

Then imagine a 3rd party API or REST API whose response you’re waiting on, you are subscribing to the observable and filtering for certain responses straight for display in your user interface.

There is a lot of power in reactive programming and it makes diagramming the process of UI event flow much easier. Each new user interaction or display is just another flow of events to be filtered and subscribed to.

Reactive Programming: Ruby Example

Now let’s do the same thing but this time in Ruby with RxRuby.

First we create the observable and print out all the numbers:

require 'rx_ruby'
numbers = [1, 2, 3, 4, 5]
all = RxRuby::Observable.from_array numbers
all.subscribe do |number|
  puts "The number is #{number}"
end

Then we filter the observable and print out the filtered values:

only_evens = all.select(&:even?)
only_evens.subscribe do |number|
  puts "This number is even: #{number}"
end

One interesting note when creating your observable, you should use from_array because simply using from will only emit the flow of values once. I’m not sure why RxRuby has this particular behaviour.

Reactive Programming: Python Example

And now let’s do it all over again but with Python and RxPy.

We create the observable with all values and print them out:

import rx
numbers = [1, 2, 3, 4, 5]
all = rx.Observable.from_(numbers)
all.subscribe(lambda number: print('The number is {}'.format(number)))

And again we filter the observable’s values to a subset and print those out as well:

only_evens = all.filter(lambda number: number % 2 == 0)
only_evens.subscribe(lambda number: print('This number is even: {}'.format(number)))

Please note that in the JavaScript example we used the operator “filter” and in the Python example. But in the Ruby example we used “select”. If you try and use “select” in the Python example you will get a list of boolean values instead of properly filtering the list. There are a few differences like this between each library.

Conclusion

This was a short introduction into reactive programming. There’s a lot more you can do and here I wanted to demonstrate that it’s possible to use Rx with more than just JavaScript. I’ve only seen it used in Java and JavaScript and thought it was time to write more examples of Ruby and Python so others can see that those languages can also benefit from Rx and Reactive programming.

Categories: AngularJS

Top 15 Awesome Tutorials To Learn AngularJS

AngularJS 1.x is more stable and mature and while Angular 2+ has taken off, there are many projects still using AngularJS. It still makes sense for web developers to learn AngularJS. In a few years that may change, but for now, AngularJS 1.x is still a viable alternative to React, Angular 2+, Vue.js and Ember and other frontend web frameworks.

If you’re interested in other Angular and AngularJS resources, check out the Learning AngularJS page.

Here are the top 25 awesome tutorials to learn AngularJS:

1. The Official AngularJS Tutorial

In this tutorial provided by the team that developed AngularJS, you will learn how to create templates, components, and how to work with two-way data binding. Dependency injection is also introduced in the tutorial.

Read the official AngularJS tutorial.

2. Year of Moo: AngularJS Guide

In this guide from Year of Moo (which I’ve linked to before for their unit testing guide for AngularJS), you will learn how to create components and services and how models and directives work. It goes in depth on how modules are created within AngularJS for organization of projects.

Read the Year of Moo AngularJS Guide.

3. Beginning AngularJS in 7 days

While the website has a lot of ads, the information on it is very good and is a good beginner tutorial for AngularJS. It goes into specifics on how to use REST resources with the $resource module and how to make HTTP requests with $http. What I like are the sections on filtering and sorting tables and form validation, two common tasks in web frontends.

Learn AngularJS in 7 days.

4. Todd Motto’s AngularJS Guide

Todd Motto is one of the top AngularJS writers and developers. His complete guide to AngularJS is also a good reference when working on a project. It begins with an overview of engineering concepts in JavaScript frameworks, moves on to services and controllers and goes in-depth on routes and the $http and $resource modules.

Read Todd Motto’s Comprehensive Guide to AngularJS.

5. AngularJS: Getting Started (PluralSight)

The courses on PluralSight are all very high quality and easy to learn from. They even offer an AngularJS quiz so you can gauge what your own skill level. In this course they show you how to build controllers and directives. In particular it shows how to use the ng-click, ng-repeat, and ng-model directives.

Watch the AngularJS Getting Started video course on PluralSight.

6. Building a Mobile App with AngularJS 1.6 and Ionic

In the video course, they cover how to build a mobile web app that can be deployed for iOS and Android using the Ionic framework.

Watch the Building A Mobile App With AngularJS 1 and Ionic video course.

7. Creating a Quiz with AngularJS

Test yourself by building a quiz web app with AngularJS! Or just build the quiz app and learn how AngularJS works. What’s nice about this course is that it not only shows you how to build the components and controllers for the app, it also shows you how to style the app and how to move from one screen to another and to carry over data.

Watch the Creating a Quiz with AngularJS 1 course on Lynda.com.

8. Build a GMail clone with AngularJS

This is always fun, instead of a contrived project to build in order to learn AngularJS, you build a clone of an existing product. This was one of the best ways to teach game programming, making clones of popular games like Tetris or Super Mario World or Final Fantasy.

In the web development world, making a clone of Instagram (as I’ve done for Elm) or GMail with AngularJS as this course shows you, is an excellent way to learn a frontend web framework.

Read the tutorial to build a GMail clone with AngularJS.

9. Creating an app with AngularJS and Rails 4

In this tutorial, you learn how to create a Rails API that can be used with AngularJS. It shows you how to use the $http HTTP module to make requests to a backend server.

Read the beginners guide to a web app with AngularJS and Rails 4.

10. Hands-on AngularJS Tutorial

This tutorial shows you how to build an online movie booking app with AngularJS. There is a really good section on creating services.

Read the Hands-on AngularJS Tutorial.

11. Animate your site with AngularJS

Animations are important for a smooth user experience, and this tutorial explains how CSS3 animations can be used to enhance your AngularJS app. Specifically, it shows you which directives have built-in animation support. Then it ends with walking you through how to create custom animations with JavaScript.

Watch the Animate Your SIte With AngularJS video course.

12. How to create animations with ngAnimate [article]

This article embeds code snippets of AngularJS so you can see the code in action and modify it and learn from it. It shows you how to animate a list of items, and how to show and hide validation messages for form validation.

Read the How To Create Animations With ngAnimate article.

13. AngularJS Routing Using UI-Router

Routing in an SPA (single page application) is how a URL is translated into the right controller and view to display in the app. For example, a router determines how to route /hello to the HelloController and /world to the WorldController.

The UI Router is more advanced than the router included with AngularJS which makes it powerful enough to be the default for many AngularJS projects.

Read the AngularJS Routing Using UI-Router article.

14. Learn AngularJS 1.x Interactively

CodeAcademy has an interactive way to learn AngularJS where you are given the code for the tutorials, it is explained and you’re free to edit it. The course is nice because it has both free form projects and quizzes to test your knowledge of AngularJS.

Learn AngularJS interactively.

15. AngularJS Data Modeling

This is an intermediate video course that shows you how to use caching in your models, how to add validation and manage validation through sub-classes. It is a thorough course at 104 minutes and 13 lessons.

Watch the AngularJS Data Modeling video course.

Heilmeier’s Catechism

Heilmeier Catechism

When George Heilmeier was the director of ARPA in the mid 1970s, he had a standard set of questions he expected every proposal for a new research program to answer. These have been called the Heilmeier Catechism. It’s a good exercise to answer these questions for an individual research project, too, both for yourself and as a way to convey to others what you hope to accomplish.

A nice set of questions to ask yourself when doing research. They are part of Heilmeier Catechism, who was the director of research at ARPA.

They’re also questions you can ask when you’re working on something that could be turned into a research paper (which is a lot of things in the computer world unsurprisingly).

Or when you want to execute a marketing or sales project that relies on a new technology.

Update 2018:

heilmeier catechism research project steps

Below we will explore each question that is part of the Heilmeier Catechism in the context of a software development team TeamSaas working on a SaaS product adopting GraphQL for the API.

The questions to ask: Heilmeier Catechism in an example context

1. What is the problem? Why is it hard?

In our example, TeamSaas needs to cater to multiple clients and consumers of their API and maintain a maximum payload size of some amount. This is difficult because different clients/consumers have different needs (some may need a lot of data, others may need less data). TeamSaas is aiming to minimize the payload size and give clients/consumers of their API only the data they need.

2. How is it solved today?

Today, TeamSaas would use a REST API.

3. What is the new technical idea; why can we succeed now?

GraphQL is the new technical idea, it allows a client/consumer of an API to select and filter data before it is passed back. The reason it can succeed now is that GraphQL has an integration with the database and framework and language that TeamSaas is using; there are also client libraries that can consume a GraphQL API and they are (relatively) stable. The main reason though is that there is enough adoption and resources aimed at making GraphQL implementable and stable.

4. What is the impact if successful?

In our example, the impact for TeamSaas is that they will be able to send the exact data that each client/consumer of their API needs; additional impacts include a cleaner codebase on their server-side and on the client-side since the data is handled through a GraphQL layer and the API response doesn’t have to be transformed in an awkward/hacky way.

5. How will the program be organized?

TeamSaas could organize their project with a client developer and backend developer prototyping and developing one or two API calls using GraphQL and then further expanding from there.

6. How will intermediate results be generated?

In our example, TeamSaas can use their prototype to generate API responses and operate the new GraphQL APi in parallel with the old REST API.

7. How will you measure progress?

Progress for TeamSaas’s switch from a REST API to a GraphQL-based API can be measured by the number of clients/consumers using the new GraphQL API and by the number of complaints there are. If there are more clients switching and there are few complaints/feedback, then things are going smoothly. Additionally, the payload sizes for each request can be measured and averaged and compared in the 90th to 99th percentile range to the old REST API to ensure payload sizes overall are smaller. The total payload sizes delivered over a week or a month could be measured, aiming for a decreased payload size total in comparison to the REST API.

8. What will it cost?

This is an exercise for the reader; the cost of the project depends on the tasks and time estimates and the team.

Categories: Life

Notes on “Transforming Team Communication” event from Slack

Taking place at restaurant in Toronto distillery district, cocktails and drinks, RSVP free event, first speaker is Slack VP of Eng, Michael Lopp. After that is showcase of Slack features, and then a customer panel. More networking afterwards.

Michael Lopp – Showing off Slack and how it’s managed day to day

Evolution of collaboration starting with email and it’s drawbacks. Slack in contrast has searchable history, “amazing from an onboarding perspective”. Moving on to intranets for documentation. Then evolving to wiki which allows people to update anything out of date. But the drawback is people leave, which means wiki pages don’t have champions for it. People were constantly maintaining and not realizing the value.

Social came along, micro transactions of thumbs up and thumbs down. In the business world we still are stuck on email.

Slack has learned from history of email, intranet, social. Slack gained broad product adoption from the builders (low level employees). Chart showing how slack adoption has completely outpaced competitors like hipchat, Yammer “most popular collaboration apps – messaging”, NPS.

Slacktualization: messaging is where it starts. The next inflection point is moving messaging into channels; giving context to the conversation. Record keeping and productivity is going on within the channel. The channel starts to organize all your people and projects. Integrations into slack to do quick approval of expenses. Then managing workflows within slack. At the top is “AI”.  All the conversations within slack have signals such as reactions and search. Using data to surface more value.

Measure engagement, not accounts. Stickiness, communication, workflow, power users.

Users recognize the benefits: 72% say slack reduced length of projects; 76% say slack is easier.

Adoption is amazing even during Christmas.

Slack described as operating system of business. You are able to use slack with as many existing systems as possible. They’re a platform company trying to be neutral even integrates with competitors.

Slide showing a lot of clients and brands using Slack.

Demo time / Slack Showcase

Slack is a set of communication primitives. Your configuration will be different, different users and companies will configure differently.

One workspace is easy then you later want to segment into others. Social channels, executive channels, project channels.

Starred messages are used as todos, starred channels are used for regular checks.

Easy to mark as read for everything, changing focus instead of worrying about information, you can use search instead.

2 weeks after he got to Slack, he emailed Stewart Butterfield CEO of Slack. Stepping back from learned behaviours with email, so many different ways to use slack.

Quick switcher feature is one of the coolest: command K, searches through contacts and channels.

Emojis are also a cool future, the sentiment analysis from the reactions, alternative to asking each person of the team what they think. Emoji for eyes used as reaction for unread messages to say “I’m looking at it”.

Slash command helpdesk opens a dialog for creating an IT ticket.

Go into the channel details, Slack has started to show highlights of the channel based on emoji reactions and other signals.

Customer Panel

Shopify

Communication density, email would not be effective. The alternative chat app was not effective. New employees and emails used to email realize how important slack is.

What drives adoption vs organic usage. Smaller company led to quick change. Larger company has to look at trajectory of the tool, how does it look at scale, chart out how the tool will grow with us.

Explored data decoding to figure out which integrations are useful what questions are being asked.

We could not have done the automation of information without Slack. Having information delivered to us rather than opening multiple tabs.

RBC

How are people adapting to Slack? Traditionalists have to be moved over to new concepts. Forward thinking people like new application development are using Slack. Predominantly IT departments using Slack.

How have you seen people react to open transparent communication? The tool markets itself, training is built into the tool, great for adoption.

How do you think about machine learning as a component of Slack? Starting with search and highlights and the usability is much better.

Bell

Any team can be spread across many different sites and offices. Using Slack to make up for lacking face to face communication. Slack wasn’t a mandate, it was a movement. The workers at Bell asked some startups what they’re using and wanted to try it out. 16 month trial period to try Slack. Organic adoption within the company. Lots of workflows depend on slack.

Examples of integrations: Built up a lookup bot to look up corporate directory for phone numbers. Tracking status with bots for JIRA. Single point to interact with multiple systems.

Weather information affects wireless systems.

We could not have done true community building across multiple site. If you search the word community, you will see many channels come up.

Takeaways

Good event to learn more about Slack and their plans for the future and mainly to see the advice that Michael Lopp / Rands In Repose gave on how he uses Slack, and to see how a good networking and promotional event is run.

Categories: Web Dev Training

One Easy Way To Speed up your Rails Tests and RSpec

There comes a time in the life of every Ruby on Rails project where you and your team will end up with long running tests. Rails tests can contain factories, fixtures and lots of setup procedures before tests are executed, and all of these can contribute to major slowness in the test runs.

I’ve seen four ways of dealing with slow running tests in Rails:

  1. start deleting tests (or mark them as skip-able): the drawback is your test coverage drops and you may end up with more bugs
  2. use more integration tests rather than unit tests: this exercises a lot of code paths so test coverage won’t drop too much but in the end most developers will write integration tests that exercise the “happy path”
  3. Run your tests in parallel
  4. Run only the tests that were most likely to be affected by recent code changes

The latter two methods are much better than the first two.

My favourite so far is #3 because it still runs all of the integration and unit tests that you have but makes use of the fact that you can offload the work of running tests to multiple machines. Everyone now has access to multiple machines through AWS (Amazon Web Services) or Microsoft Azure or RedHat’s cloud. You can even run tests in parallel on your local development machine.

Run Your Ruby on Rails Tests In Parallel

The idea is that each test file will be run in separate processes.

If you have 5 tests that have a duration 2 minutes, in sequential runs it will take 10 minutes to run the whole test suite. If you have 5 processes available for parallel runs, it will only take 2 minutes to run the whole test suite.

That’s a huge difference and means you can make 30 test runs in an hour rather than 6 test runs.

Splitting RSpec test files into multiple files

However, some of your Rails tests may take longer; within the spec you could have multiple test cases and contexts that are taking too long. For example, one test context with a few tests could be taking 1 minute while the rest of the test cases in that file only take 10 seconds. At that point, you can split the long-running test context into multiple files.

Here’s an example of how that might look like:

# spec/my_controller_spec.rb
describe MyController do
  context 'Slow tests' do
    it 'runs slowly #1' do
      # ...
    end
    it 'runs slowly #2' do
      # ...
    end
  end

  context 'Faster part of the test suite' do
    it 'runs in 10 seconds or less' do
      # ...
    end
  end
end

And now here’s how we could split that controller rspec test file into multiple files.

# spec/my_controller_spec.rb
describe MyController do
  context 'Faster part of the test suite' do
    it 'runs in 10 seconds or less' do
      # ...
    end
  end
end

# spec/my_controller_slow_1_spec.rb
describe :MyControllerSlow1 do
  def self.described_class
    MyController
  end

  include_context 'my controller helpers'

  it 'runs slowly #1' do
    # ...
  end
end

# spec/my_controller_slow_2_spec.rb
describe :MyControllerSlow2 do
  def self.described_class
    MyController
  end

  include_context 'my controller helpers'

  it 'runs slowly #2' do
    # ...
  end
end

The reason this works is because we override the class method described_class. This method is used by the rspec-rails extensions that make it easier to test Rails classes with RSpec.

By using shared contexts and helpers and by splitting files, you can optimize your Rails tests even further.

(If you liked this article, I have written about using mocks with Django and Python unit and integration tests and using Protractor with AngularJS and how you can take screenshots with Selenium during test runs.)

Categories: Web Dev Training

3 Great Videos about GraphQL

Since GraphQL is a hot topic and a new way of creating APIs for client devices and applications, it helps to learn what it is, how it’s used and why it’s becoming quickly adopted for new projects. So here are 3 great videos on YouTube that explain why your team should explore GraphQL and consider it as a viable technology for your next project.

Lessons From 4 Years Of GraphQL

A reflection on GraphQL’s successes and its evolution within Facebook, the company at which it originated.

Connect Your Angular App To Any GraphQL Backend

At Facebook they use React (it was created there too!) but a lot of companies use AngularJS and now are adopting Angular 2/4/5+. This video shows you how to use it with an Angular app. Angular offers a more complete framework in contrast to React; so if you’re already using it, it’s definitely possible to use it with APIs such as GitHub.

Implementing & Using GraphQL at GitHub

GitHub started to use it for their API in 2016 and revealed it at their yearly event GitHub Universe. They show how they implemented part of the API and then show the client-facing portion through the query explorer. The query explorer is a powerful way to construct and test different API queries.

Home » Blog
Categories: Life

How NOT to do Social Media Marketing (and 5 ways to get better at it!)

Haven’t posted about marketing in a while so here’s a good one: Someone spent thousands of dollars on buying things just to be able to post about them on Instagram.

Invest in your business, consider the ROI

Calveiro would treat herself to monthly $200 shopping sprees so she wouldn’t be seen on Instagram wearing the same outfit twice.

Imagine spending $200 a month on Facebook ads, Google ads or a LinkedIn Premium Sales Navigator ($65/month for individual account, $100/month for a team of 10+) to get more sales leads for your business.

That’s more worthwhile than spending $200 on a shopping spree just to take a few photos on Instagram.

Collectible marketing, badges, gamification

Then there was the desire to look like a jet-setter, traveling to a new location — such as Las Vegas, the Bahamas and Los Angeles — every month for a year.

“Snapchat had these [geo-]filters [like digital passport stamps] and I wanted to collect at least 12,” Calveiro said.

It looks like the marketing around collecting badges and gamification works! If you run an ecommerce site, you could have your own set of collectibles such as t-shirts, cups, stickers, buttons or some other small bit of swag that’s part of a limited-time collection (for example: orders over $100 get a free t-shirt, each order gets you a different t-shirt, collect them all!)

Usually you’ll see this kind of gamification and collectibles marketing strategy work at lower price points where it’s easier to spend, things like branded cups that come with a fast food meal or Beanie Babies or trading cards in an exclusive, limited time set.

Accept when you’re doing things for your business versus just to have fun

Although she traveled some for work, Calveiro said, “If you break it down, a lot of the travel I was doing in 2016 was strictly for Instagram.”

This is what David Allen talks about in Getting Things Done. When you’re in the moment you want to be doing the right things and enjoying yourself and not feeling regretful later on. For example, working after hours instead of spending time with family. Plan your time and know that you’re doing the right things at the right moment.

In this case, it’s traveling with a focus on Instagram marketing instead of just traveling to have fun and see the world. Be clear about why you’re doing things and be in the moment.

Don’t have the resources for social media marketing?
Use your time instead & focus on impactful strategies.

1. Reply and converse on social networks to boost your brand’s visibility

If you’re a solopreneur or a one-person business, you may not have the resources to buy advertising on Instagram or Facebook to find leads. You may have more time than money to spend and that’s what you should do. Maximize and improve your social media skills to draw in more people to your product or services.

Simple actions such as replying to someone who asks a question related to your product on Twitter improves your brand recognition. That costs you time and a little bit of thought but it is free in terms of money and other resources. It can have a huge impact because you’ll be creating conversations with potential customers and potential business contacts.

2. Recycle your content, show your existing content to new audiences

“A lot of it was recycled content,” Calveiro said of her posts.

Another good option is to recycle your content. I mentioned it on the Rudolf Podcast; you can post content you wrote years ago on to a new platform such as Medium or Pinterest, or you can create new smaller pieces of content from a larger article or video or podcast. You can also easily automate this and have Buffer or HootSuite or MeetEdgar send out tweets, Facebook status updates, and more with your previous content. Remember, that the audience you have today may not have ever seen your back catalog of great content, they may not know you wrote an amazing article years ago that’s relevant to them today.

3. Considering rentals/subscriptions/leases instead of buying

In place of her old shopping sprees, she shells out $130 for a Rent the Runway monthly membership — so she can have a revolving door of new clothes for hire.

Instead of buying a car; rent one. Instead of buying a camera, rent one. Instead of building your own email servers, subscribe to GMail for Businesses; instead of buying Photoshop, subscribe to Canva.

There are a lot of ways for businesses to save money by going with a subscription or rental plan than outright buying something.

4. Entrepreneurs and small businesses: Watch your budget, there’s very little room for error

“I had a lot of opportunities to save,” she said. “I could’ve invested that money in something.”

Save and re-invest in your business when you’re starting out or growing your small business. Check the ROI.

5. Invest in Facebook Ads, Google Ads and LinkedIn Sales Navigator

The fifth way to get better at social media marketing is to invest in advertising on the dominant platforms. If your business is selling to consumers, use Facebook ads or Google ads. Their great tools and huge audiences make every dollar spent worthwhile, each dollar spent on Facebook or Google ads has far greater impact than the same dollar spent on TV, radio or billboards or leaflets. If your business is selling to businesses (or governments), consider LinkedIn Sales Navigator.

Here are some great guides on investing in advertising on Facebook, Google and LinkedIn:

Follow me on Twitter, Facebook, and connect on LinkedIn

If you think this advice is interesting and want to discuss it further or you would like to talk about web development training and workshops or digital marketing and ecommerce, follow me on all the social networks:

Categories: Portfolio, Web Dev Training

GraphQL with Node.js and Mongoose/MongoDB

In March 2016, as part of an exploratory project, I worked on an example implementation of GraphQL using MongoDB and Node.js: graphql-server. While at the time, the company decided not to go with GraphQL, it was only a year later that they revisited the idea and started to make it part of their core technology strategy (they had multiple mobile apps and 3rd party clients that needed a more performant interface than the REST API, which had some performance issues).

Example of a GraphQL Schema

Here’s an example of how to define a schema. The advantage for clients/consumers is that they can select only the fields they need from the API.

import {
  GraphQLObjectType,
  GraphQLNonNull,
  GraphQLSchema,
  GraphQLString,
  GraphQLInt,
  GraphQLList,
  GraphQLID,
  GraphQLBoolean
} from 'graphql/type';
import co from 'co';
import mongoose from 'mongoose';

import models from './models';

var makeGQLString = function(desc) {
  return {
    type: GraphQLString,
    description: desc
  };
};

var makeNonNullGQLString = function(desc) {
  return {
    type: new GraphQLNonNull(GraphQLString),
    description: desc
  };
};

var makeGQLBoolean = function(desc) {
  return {
    type: GraphQLBoolean,
    description: desc
  };
};

var makeGQLInt = function(desc) {
  return {
    type: GraphQLInt,
    description: desc
  };
};

var listingType = new GraphQLObjectType({
  name: 'Listing',
  description: 'An event listing',
  fields: function() {
    return {
      id: makeNonNullGQLString('The id of the listing.'),
      slug: makeNonNullGQLString('slug'),
      title: makeGQLString('The title of the listing.'),
      description: makeGQLString('description'),
      description_html: makeGQLString('description_html'),
      category_id: GraphQLID,
      category_key: makeGQLString('category_key'),
      hashtag: makeGQLString('hashtag'),
      location: makeGQLString('location'),
      website: makeGQLString('website'),
      show_count: makeGQLInt('show count'),
      show_avatars_of_bookers: makeGQLBoolean('show_avatars_of_bookers'),
      show_tickets_sold_count: makeGQLBoolean('show_tickets_sold_count'),
      hide_date: makeGQLBoolean('hide_date'),
      capacity: makeGQLString('Capacity of the listing'),
      state: makeNonNullGQLString('State of the listing')
    };
  }
});

var eventType = new GraphQLObjectType({
  name: 'Event',
  description: 'An event',
  fields: function() {
    return {
      id: makeNonNullGQLString('Event id'),
      start_stamp: makeNonNullGQLString('Start of the event, timestamp'),
      end_stamp: makeNonNullGQLString('End of the event, timestamp'),
      city_name: makeGQLString('Event that the city is in')
    };
  }
});

var rootQueryType =  new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    listings: {
      type: new GraphQLList(listingType),
      resolve: function(parent, args, ast) {
        return models.Listing.find().limit(10);
      }
    },
    listing: {
      type: listingType,
      args: {
        id: {
          name: 'id',
          type: new GraphQLNonNull(GraphQLString)
        }
      },
      resolve: function(parent, args, ast) {
        return models.Listing.findOne({ _id: args.id });
      }
    },
    events: {
      type: new GraphQLList(eventType),
      args: {
        listing_id: {
          name: 'listing_id',
          type: new GraphQLNonNull(GraphQLString)
        }
      },
      resolve: function(parent, args, ast) {
        return models.Event.find({ listing_id: args.listing_id });
      }
    }
  }
});

var schema = new GraphQLSchema({
  query: rootQueryType
});

export var getProjection;
export default schema;

We declare a root query that contains certain fields that are resolved by particular functions. The type of each field can be a list, non-null or other types. The resolve function is what fetches data from the database (or whatever caching layer(s) you have).

Within the GraphQLObjectType we can define a structured object with more fields and define the types of those fields. This is in contrast to most REST APIs which provide no schema.

It’s also possible, as you define the fields, to provide descriptions of them. These descriptions can appear in a GraphQL API explorer and since they are built-in and supported as part of the GraphQL specification, the descriptions can be supported by multiple libraries. In contrast, most REST APIs do not place descriptions near the fields within the code; they provide the descriptions (if at all) within separate documentation.

When building this prototype to provide a GraphQL interface to a MongoDB database, it was very easy to declare the schemas for the models and then to provide them as part of the interface.

Click here to see more code for a GraphQL server made with Node, Express and Mongoose.

Want to learn more about GraphQL?

Click here to see a list of 3 excellent videos explaining how GraphQL works.

Here are some questions on GraphQL at StackOverflow:

It is an exciting technology that promises to make it easier for clients to consume APIs and only receive exactly the data that they need.

Categories: AngularJS, Web Dev Training

How to use Local Storage for Caching in AngularJS 1.6

After we talk about window.localStorage and caching, I discuss the state of the Angular web framework with respect to AngularJS 1.6 and Angular 2/4/5+.

Local Storage and Caching in AngularJS 1.6

Let’s get to the fun stuff, Local storage in AngularJS 1.6!

Window Local Storage is an HTML5 web api that can be used to store data in the browser. The data is stored in a bucket for the current domain name (click here to view the Storage API).

An awesome developer created the angular-local-storage module for AngularJS 1.6 which gives you a nice API to work with in AngularJS for local storage.

What’s cool about is that you can listen for notifications whenever the local storage has been changed (with setItem or removeItem). It also lets you set the storage to use local storage or session storage. Session storage is great for quick caching while local storage is more long-term.

AngularJS API for Local Storage

The API for angular-local-storage is easy to use:

  • isSupported – whether the browser supports local storage
  • setPrefix – prefix used when setting keys
  • getStorageType – the type of storage used
  • set – set a value
  • get – get a value
  • keys – the list of keys that have been set in local storage (very very convenient!)
  • remove – remove a value
  • clearAll – remove all values set
  • bind – binds a value from local storage to a variable in the $scope

The most important API functions for angular local storage are: set, get, and bind.

Here’s an example of how it’s used:

var myApp = angular.module('myApp', ['angular-local-storage']);
myApp.controller('HomeCtrl', ['$scope', 'localStorageService', 'someApiService', function($scope, localStorageService, someApiService) {
  
  function $onInit() {
    console.log('the keys! ' + localStorageService.join(', '));
    console.log('storing a value from an API call');
    someApiService.fetchValues(function(values) {
      localStorageService.set('valuesFetched', values);
    });
    localStorageService.set('formSubmitted', false);
  }

  function submitForm() {
    if (localStorageService.get('formSubmitted')) {
      console.log('form already submitted!');
    } else {
      localStorageService.set('formSubmitted', true);
    }
  }
}]);

In the example you can see that angular local storage is used to fetch values when the controller HomeCtrl is initialized with $onInit. After the value is fetched, we use the localStorage service to set the initial value for formSubmitted.

When the form is submitted through the submitForm method, we check the value of formSubmitted through localStorage and then set its value. The idea is to prevent resubmission of the form. Of course this is just for the frontend and it’s a good idea to check for resubmission on the server backend.

Angular local storage is simple to use and highly valuable as a cache for AngularJS web apps.

The State of Angular 2/4/5+

After the last year of keeping up with Angular 2/4/5+ development, it seems that they’re still gearing up. In my eyes, they have taken on a lot of work and have shifted the ground underneath developers quite a bit. The full adoption and support for TypeScript is welcome news, but there are still many development shops that will use JavaScript and ES6 with Babel. The documentation and examples do not seem to support JavaScript as much as they support TypeScript. This is also true for Dart, which is used by Google for one of the larger Angular projects, but even they cannot count on full support from the Angular team.

There’s also the rapid rate of change. Angular has an upgrade path however it is not fun to upgrade dependencies and change code every few months because the API of the framework has changed.

The state of Angular 2/4/5+ at this point is similar to the state of the Django web framework before it was version 1.0. Before 1.0 of Django, every single week seemed to bring new changes in the codebase. It was fun to be on the cutting edge and the latest and greatest but Django before 1.0 was not ready for production. This cycle is happening to Angular 2/4/5+. If you want to be on the cutting edge, use Angular and be careful when deploying and maintaining a production app.

When should you consider using Angular 2/4/5+?

If you are starting a new project, you should consider Angular 2/4/5+

If you want to develop a mobile app using Angular, use NativeScript with Angular 2./4/5+

If your web development team has at least 3 developers, consider using Angular 2/4/5+

When should you consider using AngularJS 1.6?

If you have an older AngularJS 1.x project, consider upgrading it to AngularJS 1.6 (don’t attempt a rewrite in Angular 2 until you do that!)

If your web development team has 1 to 3 developers, consider AngularJS 1.6 because you will find a lot of modules that have been production-ready and are well-tested. You will be able to ship the project into production and support it for years to come. As I pointed in the last Learning AngularJS issue about Siberian CMS, they are using AngularJS 1.3 for mobile apps and it still works just fine for them.

Thanks for reading!

Thanks for reading! If you’re still using AngularJS 1.6, don’t worry you are not alone, there are thousands of projects out there also using it and the modules are well-tested and production-ready! If you ever wanted to use local storage in AngularJS, now here’s your chance with angular-local-storage.

Click here to read more Learning AngularJS.

NeverFriday Software Expertise Proudly powered by WordPress , Theme designed by FancyThemes