How to Build and Structure a Node.js MVC Application

In a non-trivial application, the architecture is as important as the quality of the code itself. We can have well-written pieces of code, but if we don’t have a good organization, we’ll have a hard time as the complexity increases. There’s no need to wait until the project is half-way done to start thinking about the architecture. The best time is before starting, using our goals as beacons for our choices.

Node.js doesn’t have a de facto framework with strong opinions on architecture and code organization in the same way that Ruby has the Rails framework, for example. As such, it can be difficult to get started with building full web applications with Node.

In this article, we are going to build the basic functionality of a note-taking app using the MVC architecture. To accomplish this we are going to employ the Hapi.js framework for Node.js and SQLite as a database, using Sequelize.js, plus other small utilities to speed up our development. We are going to build the views using Pug, the templating language.

What is MVC?

Model-View-Controller (or MVC) is probably one of the most popular architectures for applications. As with a lot of other cool things in computer history, the MVC model was conceived at PARC for the Smalltalk language as a solution to the problem of organizing applications with graphical user interfaces. It was created for desktop applications, but since then, the idea has been adapted to other mediums including the web.

We can describe the MVC architecture in simple words:

Model: The part of our application that will deal with the database or any data-related functionality.

View: Everything the user will see. Basically the pages that we are going to send to the client.

Controller: The logic of our site, and the glue between models and views. Here we call our models to get the data, then we put that data on our views to be sent to the users.

Our application will allow us to publish, see, edit and delete plain-text notes. It won’t have other functionality, but because we will have a solid architecture already defined we won’t have big trouble adding things later.

You can check out the final application in the accompanying GitHub repository, so you get a general overview of the application structure.

Laying out the Foundation

The first step when building any Node.js application is to create a package.json file, which is going to contain all of our dependencies and scripts. Instead of creating this file manually, NPM can do the job for us using the init command:

npm init -y

After the process is complete will get a package.json file ready to use.

Note: If you’re not familiar with these commands, checkout our Beginner’s Guide to npm.

We are going to proceed to install Hapi.js—the framework of choice for this tutorial. It provides a good balance between simplicity, stability and feature availability that will work well for our use case (although there are other options that would also work just fine).

npm install --save hapi hoek

This command will download the latest version of Hapi.js and add it to our package.json file as a dependency. It will also download the Hoek utility library that will help us write shorter error handlers, among other things.

Now we can create our entry file; the web server that will start everything. Go ahead and create a server.js file in your application directory and all the following code to it:

'use strict';

const Hapi = require('hapi');
const Hoek = require('hoek');
const Settings = require('./settings');

const server = new Hapi.Server();
server.connection({ port: Settings.port });

server.route({
  method: 'GET',
  path: '/',
  handler: (request, reply) => {
    reply('Hello, world!');
  }
});

server.start((err) => {
  Hoek.assert(!err, err);

  console.log(`Server running at: ${server.info.uri}`);
});

This is going to be the foundation of our application.

First, we indicate that we are going to use strict mode, which is a common practice when using the Hapi.js framework.

Next, we include our dependencies and instantiate a new server object where we set the connection port to 3000 (the port can be any number above 1023 and below 65535.)

Our first route for our server will work as a test to see if everything is working, so a ‘Hello, world!’ message is enough for us. In each route, we have to define the HTTP method and path (URL) that it will respond to, and a handler, which is a function that will process the HTTP request. The handler function can take two arguments: request and reply. The first one contains information about the HTTP call, and the second will provide us with methods to handle our response to that call.

Finally, we start our server with the server.start method. As you can see, we can use Hoek to improve our error handling, making it shorter. This is completely optional, so feel free to omit it in your code, just be sure to handle any errors.

Storing Our Settings

It is good practice to store our configuration variables in a dedicated file. This file exports a JSON object containing our data, where each key is assigned from an environment variable—but without forgetting a fallback value.

In this file, we can also have different settings depending on our environment (e.g. development or production). For example, we can have an in-memory instance of SQLite for development purposes, but a real SQLite database file on production.

Selecting the settings depending on the current environment is quite simple. Since we also have an env variable in our file which will contain either development or production, we can do something like the following to get the database settings (for example):

const dbSettings = Settings[Settings.env].db;

So dbSettings will contain the setting of an in-memory database when the env variable is development, or will contain the path of a database file when the env variable is production.

Also, we can add support for a .env file, where we can store our environment variables locally for development purposes; this is accomplished using a package like dotenv for Node.js, which will read a .env file from the root of our project and automatically add the found values to the environment. You can find an example in the dotenv repository.

Note: If you decide to also use a .env file, make sure you install the package with npm install -s dotenv and add it to .gitignore so you don’t publish any sensitive information.

Our settings.js file will look like this:

// This will load our .env file and add the values to process.env,
// IMPORTANT: Omit this line if you don't want to use this functionality
require('dotenv').config({silent: true});

module.exports = {
  port: process.env.PORT || 3000,
  env: process.env.ENV || 'development',

  // Environment-dependent settings
  development: {
    db: {
      dialect: 'sqlite',
      storage: ':memory:'
    }
  },
  production: {
    db: {
      dialect: 'sqlite',
      storage: 'db/database.sqlite'
    }
  }
};

Now we can start our application by executing the following command and navigating to localhost:3000 in our web browser.

node server.js

Note: This project was tested on Node v6. If you get any errors, ensure you have an updated installation.

Defining the Routes

The definition of routes gives us an overview of the functionality supported by our application. To create our additional routes, we just have to replicate the structure of the route that we already have in our server.js file, changing the content of each one.

Let’s start by creating a new directory called lib in our project. Here we are going to include all the JS components. Inside lib, let’s create a routes.js file and add the following content:

'use strict';

module.exports = [
  // We are going to define our routes here
];

In this file, we will export an array of objects that contain each route of our application. To define the first route, add the following object to the array:

{
  method: 'GET',
  path: '/',
  handler: (request, reply) => {
    reply('All the notes will appear here');
  },
  config: {
    description: 'Gets all the notes available'
  }
},

Our first route is for the home page (/) and since it will only return information we assign it a GET method. For now, it will only give us the message All the notes will appear here, which we are going to change later for a controller function. The description field in the config section is only for documentation purposes.

Then, we create the four routes for our notes under the /note/ path. Since we are building a CRUD application, we will need one route for each action with the corresponding HTTP method.

Add the following definitions next to the previous route:

{
  method: 'POST',
  path: '/note',
  handler: (request, reply) => {
    reply('New note');
  },
  config: {
    description: 'Adds a new note'
  }
},
{
  method: 'GET',
  path: '/note/{slug}',
  handler: (request, reply) => {
    reply('This is a note');
  },
  config: {
    description: 'Gets the content of a note'
  }
},
{
  method: 'PUT',
  path: '/note/{slug}',
  handler: (request, reply) => {
    reply('Edit a note');
  },
  config: {
    description: 'Updates the selected note'
  }
},
{
  method: 'GET',
  path: '/note/{slug}/delete',
  handler: (request, reply) => {
    reply('This note no longer exists');
  },
  config: {
    description: 'Deletes the selected note'
  }
},

We have done the same as in the previous route definition, but this time we have changed the method to match the action we want to execute.

The only exception is the delete route. In this case, we are going to define it with the GET method rather than DELETE and add an extra /delete in the path. This way, we can call the delete action just by visiting the corresponding URL.

Continue reading %How to Build and Structure a Node.js MVC Application%


Source: Sitepoint

Monthly Web Development Update 1/2018: Browser Diversity, Ethical Design, And CSS Alignment

I hope you had a great start into the new year. And while it’s quite an arbitrary date, many of us take the start of the year as an opportunity to try to change something in their lives. I think it’s well worth doing so, and I wish you the best of luck for accomplishing your realistic goals. I for my part want to start working on my mindfulness, on being able to focus, and on pursuing my dream of building an ethically correct, human company with Colloq that provides real value to users and is profitable by its users.
Source: Smashing Magazine

How To Internationalize Your WordPress Website

On September 30th, 2017, the international WordPress community united for 24 hours to translate the WordPress ecosystem. For the third time, #WPTranslationDay fused an all-day translating marathon with digital and contributor day events designed to promote the value of creating accessible experiences for global users, better known as “localization”.
As an open-source community, we should all strive to localize our open-source contributions. Before you can transcribe your digital assets though, you have to internationalize your codebase.
Source: Smashing Magazine

What Is Wix Code?

This article was sponsored by Wix. Thank you for supporting the partners who make SitePoint possible.

You probably already know that Wix is a cloud-based web design platform that lets users create stunning HTML5 websites using its online drag and drop editor.

Wix Code takes Wix to the next level, turning it into an open platform for building robust, content-rich sites and web apps. With Wix Code, Wix becomes a powerful and extensible tool for web developers.

Wix Code adds a bunch of new features and functionality to Wix:

  • Databases
  • Dynamic pages
  • Repeating layouts
  • Custom forms
  • Built-in online IDE
  • Custom interactions using our APIs and JavaScript
  • Access to 3rd party APIs
  • Call backend code from the front-end with Web Modules
  • HTTP functions: Exposing your site’s functionality as a service with your own API

And, don’t forget, this is still Wix, so everything is hassle-free:

  • It’s serverless: All this added functionality comes in a serverless environment that lets you get your work done without any of the normal full-stack development headaches.
  • Just code and go: Wix Code has a built-in, online IDE and backend so you can just add the code you need to your page or your site, publish, and you’re live.

All these new features mean that you can think about the kind of site you want to build on Wix in whole new ways. Let’s consider an example.

Do you want to build a full-fledged real estate site, where users can browse your offerings and search by location or other property features? You probably don’t want to build a separate page for each listing, right? You might also want to let your clients sign up for your newsletter.

How about if, on the same site, you want to give your agents access to special pages with admin permissions so they can add or update listings in a database? Maybe they also need to maintain a database of all their clients?

Maybe you need to connect your site to an existing database? What if you have a dedicated mobile app and you want your site to integrate with it? Of course you want any changes you or your agents make to go live in real-time.

Wix Code makes all this possible. Using a combination of Wix Code features, our APIs, and JavaScript that you add, you can make your Wix site behave exactly the way you need it to. You can even expose your site as a service or use your site exclusively as a backend for an external application.

And it’s all within the Wix ecosystem so it’s hosted, secure, and SEO-compatible, and you never have to worry about scalability.

With Wix Code you can use all the stunning templates and styling options from Wix and add extra functionality and code to make your site even more awesome. This way you can focus on the fun part of making your site work exactly the way you want.

Databases

Database Collections

Imagine our real estate site. You probably want one database for your available properties, one for your agents, and another for your clients. But you’ll need to associate your agents with the properties they’re handling and also to associate potential clients with each property.

Now with Wix Code you can add a database with multiple collections to your site. The Wix Code database is automatically integrated into your Wix site so there’s no need to set anything up—we do all the magic for you. As soon as you create a collection, it’s available for you to use with the elements in your site, to either display or store data, all without writing a line of code.

You can also create complex data structures with reference fields so that one collection can refer to the records, or what we call items, in another collection. The Wix Code database also includes a permissions model that gives you control over which visitors are allowed to interact with your data and what they are allowed to do.

Once your collections are set up, you can use our wix-data API to manage your data. It lets you query your collection with a long list of functions to control your query results. It even has hook functions so you can add custom code that runs before or after different actions on your data.

One of the most powerful things you can do with a collection is use its content in dynamic pages, so let’s talk about that next.

Dynamic Pages

Dynamic Pages

Back to real estate. As your users browse your site, you want them to be able to view a dedicated page for each property. Each listing should be displayed using the same layout with the same basic elements. You just need the content of those elements to change and for each page to have a unique URL. That’s what dynamic pages do.

When you create a dynamic page, you design one page layout that’s used each time your site calls that page. And each time it’s called, it displays the content of a different item in your collection with its own URL.

Now you no longer need to create a unique page when you have a lot of data that you want to display in the same way. Just create a dynamic page, connect it to your collection, and you automatically get a unique page with its own URL for each item in your collection. And whenever your collection’s data changes, your page contents change automatically.

Dynamic Pages and SEO

The content in dynamic pages can change each time the page is displayed, and you’re going to want search engines and social networks to index that page for any of the content it could display. The SEO settings for dynamic pages let you control how your pages are indexed, and they let you reference the data in your collections for indexing.

You can control the page’s title, description, keywords, and social images using the data from your collection that’s associated with your page. You can also hide the page from search results if you want.

Continue reading %What Is Wix Code?%


Source: Sitepoint

What Is Node and When Should I Use It?

So you’ve heard of Node.js, but aren’t quite sure what it is or where it fits into your development workflow. Or maybe you’ve heard people singing Node’s praises and now you’re wondering if it’s something you need to learn. Perhaps you’re familiar with another back-end technology and want to find out what’s different about Node. […]

Continue reading %What Is Node and When Should I Use It?%


Source: Sitepoint

Introduction to Forms in Angular 4: Writing Custom Form Validators

This is the third part of the series on creating forms in Angular. In the first two tutorials, we used Angular’s template-driven and model-driven approach to create forms. However, while detailing both the approaches, there was something that we didn’t cover—custom validator functions. This tutorial will cover everything you need to know about writing custom validators that meet your requirements.

Prerequisites

You don’t need to have followed part one or two of this series for part three to make sense. However, if you are entirely new to forms in Angular, you should head over to the first tutorial of this series and start from there. 

Otherwise, grab a copy of this code from our GitHub repo and use that as a starting point.  

Built-in Validators

Angular doesn’t boast a huge built-in validator library. As of Angular 4, we have the following popular validators in Angular:

  • required
  • minlength
  • maxlength
  • pattern

There are actually a few more, and you can see the full list in the Angular docs

We can use the above built-in validators in two ways:

1. As directives in template-driven forms.

2. As validators inside the FormControl constructor in model-driven forms.

If the above syntax doesn’t make sense, follow my previous tutorials on building a signup form using a template-driven approach or a model-driven approach and then drop back!

The built-in form validators hardly cover all the validation use cases that might be required in a real-world application. For instance, a signup form might need to check whether the values of the password and confirm password control fields are equal and display an error message if they don’t match. A validator that blacklists emails from a particular domain is another common example. 

Here is a fact: Template-driven forms are just model-driven forms underneath. In a template-driven form, we let the template take care of the model creation for us. The obvious question now is, how do you attach a validator to a form?

Validators are just functions. In a model-driven form, attaching validators to FormControl is straightforward. In a template-driven form, however, there is a bit more work to be done. In addition to the validator function, you will need to write a directive for the validator and create instances of the directive in the template.

Diving Into the Details

Although this has been already covered, we will go through a quick recap of the code for the signup form. First, here’s the reactive approach.

app/signup-form/signup-form.component.ts

FormBuilder is a syntax sugar that creates the FormGroup and FormControl instances. A FormControl tracks the value and the validation status of an individual form element. A FormGroup, on the other hand, comprises a group of FormControl instances, and it tracks the value and validity of the whole group.

Here’s the structure that we have been following:

Depending on the requirements, we can attach a validator to a FormControl or a FormGroup. An email blacklisting validator would require it to be attached to the FormControl instance of the email. 

However, for more complex validations where multiple control fields have to be compared and validated, it’s a better idea to add the validation logic to the parent FormGroup. As you can see, password has a FormGroup of its own, and this makes it easy for us to write validators that check the equality of pwd and confirmPwd.

For the template-driven form, all that logic goes into the HTML template, and here is an example:

app/signup-form/signup-form.component.html

ngModel creates an instance of FormControl and binds it to a form control element. Similarly, ngModelGroup creates and binds a FormGroup instance to a DOM element. They share the same model domain structure discussed above. 

It’s also interesting to note that FormControl, FormGroup, and FormArray extend the AbstractControl class. What this means is that the AbstractControl class is responsible for tracking the values of form objects, validating them, and powering other things such as pristine, dirty, and touched methods. 

Now that we are acquainted with both the form techniques, let’s write our first custom validator.

Custom Validator Function for Model-Driven Forms

Validators are functions that take a FormControl/FormGroup instance as input and return either null or an error object. null is returned when the validation is successful, and if not, the error object is thrown. Here’s a very basic version of a validation function. 

app/password-match.ts

I’ve declared a function that accepts an instance of FormGroup as an input. It returns an object with a key of type string and a true/false value. This is so that we can return an error object of the form below:

Next, we need to get the value of the pwd and confirmPwd FormControl instances. I am going to use control.get() to fetch their values. 

Now we need to make the comparison and then return either null or an error object.

app/password-match.ts

Why did I replace FormGroup with AbstractControl? As you know, AbstractControl is the mother of all Form* classes, and it gives you more control over the form control objects. It has the added benefit that it makes our validation code more consistent.

Import the passwordMatch function in the SignupForm component and declare it as a validator for the password FormGroup instance.

app/password-match.ts

Displaying the Errors

If you did everything right, password.errors?.mismatch will be true whenever the values of both the fields don’t match.

Although there are alternative ways to display errors, I am going to use the ngIf directive to determine whether an error message should be displayed or not.

First, I am going to use ngIf to see if the password is invalid. 

We use password.touched to ensure that the user is not greeted with errors even before a key has been pressed.

Next, I am going to use the ngIf =”expression; then a else b” syntax to display the right error.

app/signup-form/signup-form.component.html

There you have it, a working model of the validator that checks for password equality.

Demo for Custom Validators in Model-Driven Forms

Custom Validator Directive for Template-Driven Forms

We will be using the same validator function that we created for the model-driven form earlier. However, we don’t have direct access to instances of FormControl/FormGroup in a template-driven form. Here are the things that you will need to do to make the validator work:

  1. Create a PasswordMatchDirective that serves as a wrapper around the passwordMatch validator function. We will be registering the directive as a validator using the NG_VALIDATORS provider. More on this later.
  2. Attach the directive to the template form control. 

Let’s write the directive first. Here’s what a directive looks like in Angular:

app/password-match.ts

The @Directive decorator is used to mark the class as an Angular directive. It accepts an object as an argument that specifies the directive configuration meta-data such as selectors for which the directive should be attached, and the list of Providers to be injected, etc. Let’s fill in the directive meta-data:

app/password-match.ts

  1. The directive is now attached to all input controls that have the attributes ngModelGroup and passwordMatch
  2. We extend the built-in validators using the NG_VALIDATORS provider. As previously mentioned, NG_VALIDATORS is a provider that has an extensible collection of validators. The passwordMatch function that we created earlier is declared as a dependency. The multi: true sets this provider to be a multi-provider. What this means is that we will be adding to the existing collection of validators provided by NG_VALIDATORS.

Now, add the directive to the declarations array in ngModule.

app/app.module.ts

Displaying Error Messages

To display the validation error messages, I am going to use the same template that we created for the model-driven forms.

Demo for Custom Validators in Template-Driven Forms

Conclusion

In this tutorial, we learned about creating custom Angular validators for forms in Angular. 

Validators are functions that return null or an error object. In model-driven forms, we have to attach the validator to a FormControl/FormGroup instance, and that’s it. The procedure was a bit more complex in a template-driven form because we needed to create a directive on top of the validator function. 

If you’re interested in continuing to learn more about JavaScript, remember to check out what we have in Envato Market.

I hope that you’ve enjoyed this series on Forms in Angular. I would love to hear your thoughts. Share them through the comments. 


Source: Nettuts Web Development

Learning Elm From A Drum Sequencer (Part 2)

In part one of this two-part article, we began building a drum sequencer in Elm. We learned the syntax, how to read and write type-annotations to ensure our functions can interact with one another, and the Elm Architecture, the pattern in which all Elm programs are designed.
In this conclusion, we’ll work through large refactors by relying on the Elm compiler, and set up recurring events that interact with JavaScript to trigger drum samples.
Source: Smashing Magazine

How to Optimize CSS and JS for Faster Sites

This article was sponsored by Aussie Hosting. Thank you for supporting the partners who make SitePoint possible.

User experience is the most important factor when it comes to the success of your online venture.

It doesn’t matter if you run a niche blog, SaaS site, or an online store. If you somehow manage to botch up your audience’s experience, don’t expect to convert any of them into paying customers.

The good news is, any brand can methodically improve user experience by narrowing down on specific on-page factors.

Loading speed, for instance, is something that most website owners easily overlook.

According to conversion rate data, increasing your Internet site speed from eight seconds to two seconds may lead to a 74 percent increase in conversion rate.

That means that a slow site could cost you nearly half of your potential customers.

Seeing the Full Picture with PageSpeed Insights

To determine issues on your website that affect loading speed, you can use Google PageSpeed Insights. It’s a free tool that automatically scans both the desktop and mobile versions of your site.

PageSpeed Insights

In addition to the issues detected, PageSpeed Insights will also show you a handful of actionable recommendations.

For site owners who never gave any thought to page loading speed, you may encounter the following issues:

PageSpeed Insights

These indicate that your CSS and JavaScript code is slowing your site down. And while it might sound like a job for full-fledged web developers, they’re fairly easy to optimize with the help of tools.

Without further ado, here are the steps you need to take to minify your CSS and JavaScript assets.

Determine the Code to be Minified

Code minification is the practice of deleting characters that don’t serve any function other than improving readability.

For example, inline comments may help developers comprehend what a particular section of code does. While it’s useful for reviewing or debugging, they may also bloat the size of the code.

Minification removes these excess characters — therefore reduces bandwidth usage and boosts page loading speed.

Using PageSpeed Insights, you can easily identify which code requires minification. Simply click “Show how to fix” and follow the path in your CMS (Content Management System) or FTP (File Transfer Protocol) client.

Code minification

For example, if your website runs on WordPress, then all of your code should be consolidated in the “Editor” section. This can be found by under the “Appearance” tab from the primary dashboard.

Code minification

Optimizing Your Codes

Now that you’ve found the code in question, it’s time to learn how to minify them.

Perhaps the easiest way to minify your code is to leverage automated tools. When it comes to CSS and JavaScript, some of the best tools for the job are CSS Minifier and JSCompress.

Using CSS Minifier

CSS Minifier is a free and simple tool that automatically compresses CSS assets. All you need to do is paste the code into the input field, set a compression level, and click “Minify.”

CSS Minifier

Depending on the size of your code, it may take a few seconds to a minute to minify your code. Your new code can then be copied back into your CMS or FTP client interface.

Important: As a precaution, don’t forget to create backups before making any changes in your site’s code. Creating offline or cloud-based copies is a straightforward way to do this.

CSS Minifier

To test if your minification worked, go ahead and run another analysis on PageSpeed Insights. The CSS file you recently compressed should no longer appear under the “Minify CSS” details.

CSS Minifier

Using Asynchronous Loading on JavaScript

Compared to CSS, JavaScript is slightly trickier to minify correctly. Before you run your code through JSCompress, consider implementing asynchronous code loading first.

Also referred to as “Lazy Loading” — but in the context of JavaScript, asynchronous loading works by dynamically loading functions.

To use asynchronous loading, just add the “async” tag when calling the .js file. This can be done in your website’s HTML source code.

Here’s an example on how to do this:

<script src=”yourscript.js” async> </script>

You can refer to this post for more information on how this works and its usage. If you’re completely new to HTML, read this beginner’s guide until you’re comfortable with the basics.

Combining JavaScript Files

Another point worth mentioning when it comes to optimizing JavaScript is to combine files in a single page. Doing so will reduce the number of HTTP requests that the browser makes, which would invariably speed up loading time.

For example, rather than calling multiple .js files in your source code:

Continue reading %How to Optimize CSS and JS for Faster Sites%


Source: Sitepoint

Understanding And Using REST APIs

There’s a high chance you came across the term “REST API” if you’ve thought about getting data from another source on the internet, such as Twitter or Github. But what is a REST API? What can it do for you? How do you use it?
In this article, you’ll learn everything you need to know about REST APIs to be able to read API documentations and use them effectively.
Source: Smashing Magazine

A Comprehensive Guide To UX Research

(This is a sponsored article.) Before embarking upon the design phase of any project, it’s critical to undertake some research so that the decisions you make are undertaken from an informed position. In this third article of my series for Adobe XD, I’ll be focusing on the importance of undertaking user research.
Your job title might not be “design researcher”, but that doesn’t mean you shouldn’t at the very least inform yourself of your users and their needs by undertaking at least some initial scoping research before you embark upon a project.
Source: Smashing Magazine