emGee Software Solutions Custom Database Applications

Share this

Web Design

Inspiring Desktop Wallpapers To Make November Even More Colorful (2017 Edition)

Smashing Magazine - Tue, 10/31/2017 - 08:27
November is a rather gray month in many parts of the world, so what could be better as some colorful inspiration to start it off with the right foot? To tickle your creativity, artists and designers from across the globe once again challenged their artistic abilities and designed desktop wallpapers for you to indulge in. Wallpapers that are a bit more distinctive as the usual crowd, bound to breathe some fresh life into your routine.
Categories: Web Design

Stateful vs. Stateless Functional Components in React

Tuts+ Code - Web Development - Tue, 10/31/2017 - 07:00

React is a popular JavaScript front-end library for building interactive user interfaces. React has a comparatively shallow learning curve, which is one of the reasons why it's getting all the attention lately. 

Although there many important concepts to be covered, components are undeniably the heart and soul of React. Having a good understanding of components should make your life easy as a React developer. 

Prerequisites

This tutorial is intended for beginners who have started learning React and need a better overview of components. We will start with component basics and then move on to more challenging concepts such as component patterns and when to use those patterns. Different component classifications have been covered such as class vs. functional components, stateful vs. stateless components, and container vs. presentational components. 

Before getting started, I want to introduce you to the code snippet that we will be using in this tutorial. It is a simple counter built with React. I will be referring back to some parts of this example throughout the tutorial. 

So let's get started. 

What Are Components?

Components are self-sustaining, independent micro-entities that describe a part of your UI. An application's UI can be split up into smaller components where each component has its own code, structure, and API. 

Facebook, for instance, has thousands of pieces of functionality interfaced together when you view their web application. Here is an interesting fact: Facebook comprises 30,000 components, and the number is growing. The component architecture allows you to think of each piece in isolation. Each component can update everything in its scope without being concerned about how it affects other components. 

If we take Facebook's UI as an example, the search bar would be a good candidate for a component. Facebook's Newsfeed would make another component (or a component that hosts many sub-components). All the methods and AJAX calls concerned with the search bar would be within that component.

Components are also reusable. If you need the same component in multiple places, that's easy. With the help of JSX syntax, you can declare your components wherever you want them to appear, and that's it. 

<div> Current count: {this.state.count} <hr /> {/* Component reusability in action. */ } <Button sign = "+" count={this.state.count} updateCount = {this.handleCount.bind(this) }/> <Button sign = "-" count={this.state.count} updateCount = {this.handleCount.bind(this) }/> </div>Props and State

Components need data to work with. There are two different ways that you can combine components and data: either as props or state. props and state determine what a component renders and how it behaves. Let's start with props.

props

If components were plain JavaScript functions, then props would be the function input. Going by that analogy, a component accepts an input (what we call props), processes it, and then renders some JSX code.

Although the data in props is accessible to a component, React philosophy is that props should be immutable and top-down. What this means is that a parent component can pass on whatever data it wants to its children as props, but the child component cannot modify its props. So, if you try to edit the props as I did below, you will get the "Cannot assign to read-only" TypeError.

const Button = (props) => { // props are read only props.count =21; . . }State

State, on the other hand, is an object that is owned by the component where it is declared. Its scope is limited to the current component. A component can initialize its state and update it whenever necessary. The state of the parent component usually ends up being props of the child component. When the state is passed out of the current scope, we refer to it as a prop.


Now that we know the component basics, let's have a look at the basic classification of components.

Class Components vs. Functional Components

A React component can be of two types: either a class component or a functional component. The difference between the two is evident from their names. 

Functional Components

Functional components are just JavaScript functions. They take in an optional input which, as I've mentioned earlier, is what we call props.


Some developers prefer to use the new ES6 arrow functions for defining components. Arrow functions are more compact and offer a concise syntax for writing function expressions. By using an arrow function, we can skip the use of two keywords, function and return, and a pair of curly brackets. With the new syntax, you can define a component in a single line like this. 

const Hello = ({ name }) => (<div>Hello, {name}!</div>);Class Components

Class components offer more features, and with more features comes more baggage. The primary reason to choose class components over functional components is that they can have state.

The state = {count: 1} syntax is part of the public class fields feature. More on this below. 

There are two ways that you can create a class component. The traditional way is to use React.createClass(). ES6 introduced a syntax sugar that allows you to write classes that extend React.Component. However, both the methods are meant to do the same thing. 

Class components can exist without state too. Here is an example of a class component that accepts an input props and renders JSX.

class Hello extends React.Component { constructor(props) { super(props); } render() { return( <div> Hello {props} </div> ) } }

We define a constructor method that accepts props as input. Inside the constructor, we call super() to pass down whatever is being inherited from the parent class. Here are a few details that you might have missed.

First, the constructor is optional while defining a component. In the above case, the component doesn't have a state, and the constructor doesn't appear to do anything useful. this.props used inside the render() will work regardless of whether the constructor is defined or not. However, here's something from the official docs:

Class components should always call the base constructor with props.

As a best practice, I will recommend using the constructor for all class components.

Secondly, if you're using a constructor, you need to call super(). This is not optional, and you will get the syntax error "Missing super() call in constructor" otherwise. 

And my last point is about the use of super() vs. super(props). super(props) should be used if you're going to call this.props inside the constructor. Otherwise, using super() alone is sufficient.

Stateful Components vs. Stateless Components

This is another popular way of classifying components. And the criteria for the classification is simple: the components that have state and the components that don't. 

Stateful Components

Stateful components are always class components. As previously mentioned, stateful components have a state that gets initialized in the constructor. 

// Here is an excerpt from the counter example constructor(props) { super(props); this.state = { count: 0 }; }

We've created a state object and initialized it with a count of 0. There is an alternative syntax proposed to make this easier called class fields. It's not a part of the ECMAScript specification yet, but If you're using a Babel transpiler, this syntax should work out of the box.

class App extends Component { /* // Not required anymore constructor() { super(); this.state = { count: 1 } } */ state = { count: 1 }; handleCount(value) { this.setState((prevState) => ({count: prevState.count+value})); } render() { // omitted for brevity } }

You can avoid using the constructor altogether with this new syntax.

We can now access the state within the class methods including render(). If you're going to use them inside render() to display the value of the current count, you need to place it inside curly brackets as follows:

render() { return ( Current count: {this.state.count} ) }

The this keyword here refers to the instance of the current component. 

Initializing the state is not enough—we need to be able to update the state in order to create an interactive application. If you thought this would work, no, it won't.

//Wrong way handleCount(value) { this.state.count = this.state.count +value; }

 React components are equipped with a method called setState for updating the state. setState accepts an object that contains the new state of the count.

// This works handleCount(value) { this.setState({count: this.state.count+ value}); }

The setState() accepts an object as an input, and we increment the previous value of count by 1, which works as expected. However, there is a catch. When there are multiple setState calls that read a previous value of the state and write a new value into it, we might end up with a race condition. What that means is that the final results won't match up with the expected values.

Here is an example that should make it clear for you. Try this in the codesandbox snippet above.

// What is the expected output? Try it in the code sandbox. handleCount(value) { this.setState({count: this.state.count+100}); this.setState({count: this.state.count+value}); this.setState({count: this.state.count-100}); }

We want the setState to increment the count by 100, then update it by 1, and then remove that 100 that was added earlier. If setState performs the state transition in the actual order, we will get the expected behavior. However, setState is asynchronous, and multiple setState calls might be batched together for better UI experience and performance. So the above code yields a behavior which is different from what we expect.

Therefore, instead of directly passing an object, you can pass in an updater function that has the signature:

(prevState, props) => stateChange

prevState is a reference to the previous state and is guaranteed to be up to date. props refers to the component's props, and we don't need props to update the state here, so we can ignore that. Hence, we can use it for updating state and avoid the race condition.

// The right way handleCount(value) { this.setState((prevState) => { count: prevState.count +1 }); }

The setState() rerenders the component, and you have a working stateful component.

Stateless Components

You can use either a function or a class for creating stateless components. But unless you need to use a lifecycle hook in your components, you should go for stateless functional components. There are a lot of benefits if you decide to use stateless functional components here; they are easy to write, understand, and test, and you can avoid the this keyword altogether. However, as of React v16, there are no performance benefits from using stateless functional components over class components. 

The downside is that you can't have lifecycle hooks. The lifecycle method ShouldComponentUpdate() is often used to optimize performance and to manually control what gets rerendered. You can't use that with functional components yet. Refs are also not supported.

Container Components vs. Presentational Components

This is another pattern that is very useful while writing components. The benefit of this approach is that the behavior logic is separated from the presentational logic.

Presentational Components

Presentational components are coupled with the view or how things look. These components accept props from their container counterpart and render them. Everything that has to do with describing the UI should go here. 

Presentational components are reusable and should stay decoupled from the behavioral layer. A presentational component receives the data and callbacks exclusively via props and when an event occurs, like a button being pressed, it performs a callback to the container component via props to invoke an event handling method. 

Functional components should be your first choice for writing presentational components unless a state is required. If a presentational component requires a state, it should be concerned with the UI state and not actual data. The presentational component doesn't interact with the Redux store or make API calls. 

Container Components

Container components will deal with the behavioral part. A container component tells the presentational component what should be rendered using props. It shouldn't contain limited DOM markups and styles. If you're using Redux, a container component contains the code that dispatches an action to a store. Alternatively, this is the place where you should place your API calls and store the result into the component's state. 

The usual structure is that there is a container component at the top that passes down the data to its child presentational components as props. This works for smaller projects; however, when the project gets bigger and you have a lot of intermediate components that just accept props and pass them on to child components, this will get nasty and hard to maintain. When this happens, it's better to create a container component unique to the leaf component, and this will ease the burden on the intermediate components.

So What Is a PureComponent?

You will get to hear the term pure component very often in React circles, and then there is React.PureComponent. When you're new to React, all this might sound a bit confusing. A component is said to be pure if it is guaranteed to return the same result given the same props and state. A functional component is a good example of a pure component because, given an input, you know what will be rendered. 

const HelloWorld = ({name}) => ( <div>{`Hi ${name}`}</div> );

Class components can be pure too as long as their props and state are immutable. If you have a component with a 'deep' immutable set of props and state, React API has something called PureComponent. React.PureComponent is similar to React.Component, but it implements the ShouldComponentUpdate() method a bit differently. ShouldComponentUpdate() is invoked before something is rerendered. The default behaviour is that it returns true so that any change to the state or the props rerenders the component.

shouldComponentUpdate(nextProps, nextState) { return true; }

However, with PureComponent, it performs a shallow comparison of objects. Shallow comparison means that you compare the immediate contents of the objects instead of recursively comparing all the key/value pairs of the object. So only the object references are compared, and if the state/props are mutated, this might not work as intended. 

React.PureComponent is used for optimizing performance, and there is no reason why you should consider using it unless you encounter some sort of performance issue. 

Final Thoughts

Stateless functional components are more elegant and usually are a good choice for building the presentational components. Because they are just functions, you won't have a hard time writing and understanding them, and moreover, they are dead easy to test. 

It should be noted that stateless functional components don't have the upper hand in terms of optimization and performance because they don't have a ShouldComponentUpdate() hook. This might change in future versions of React, where functional components might be optimized for better performance. However, if you're not critical of the performance, you should stick to functional components for the view/presentation and stateful class components for the container.

Hopefully, this tutorial has given you a high-level overview of the component-based architecture and different component patterns in React. What are your thoughts on this? Share them through the comments.

Over the last couple of years, React has grown in popularity. In fact, we have a number of items in Envato Market that are available for purchase, review, implementation, and so on. If you’re looking for additional resources around React, don’t hesitate to check them out.

Categories: Web Design

TypeScript for Beginners, Part 5: Generics

Tuts+ Code - Web Development - Tue, 10/31/2017 - 05:00

The second tutorial in our TypeScript for Beginners series focused on basic data types available in TypeScript. The type checking in TypeScript allows us to make sure that the variables in our code can only have specific types of values assigned to them. This way we can avoid a lot of mistakes while writing code because the IDE will be able to tell us when we are performing an operation on a type that it does not support. This makes type checking one of the best features of TypeScript.

In this tutorial, we will focus on another important feature of this language—generics. With generics, TypeScript enables you to write code that can act on a variety of data types instead of being limited to a single one. You will learn about the need for generics in detail and how it's better than just using the any data type available in TypeScript.

The Need for Generics

If are not familiar with generics, you might be wondering why we need them at all. In this section, I will answer this question for you. Let's begin by writing a function that will return a random element from an array of numbers.

function randomIntElem(theArray: number[]): number { let randomIndex = Math.floor(Math.random()*theArray.length); return theArray[randomIndex]; } let positions: number[] = [103, 458, 472, 458]; let randomPosition: number = randomIntElem(positions);

The randomElem function we just defined takes an array of numbers as its only parameter. The return type of the function has also been specified as a number. We are using the Math.random() function to return a floating-point random number between 0 and 1. Multiplying it with the length of a given array and calling Math.floor() on the result gives us a random index. Once we have the random index, we return the element at that specific index.

Some time later, let's say you need to get a random string element from an array of strings. At this point, you may decide to create another function which specifically targets strings.

function randomStrElem(theArray: string[]): string { let randomIndex = Math.floor(Math.random()*theArray.length); return theArray[randomIndex]; } let colors: string[] = ['violet', 'indigo', 'blue', 'green']; let randomColor: string = randomStrElem(colors);

What if you need to select a random element from an array of an interface that you defined? Creating a new function every time you want to get a random element from an array of different kinds of objects is not feasible.

One solution for this problem is to set the type of array parameter being passed to the functions as any[]. This way you can just write your function only once, and it will work with an array of all types.

function randomElem(theArray: any[]): any { let randomIndex = Math.floor(Math.random()*theArray.length); return theArray[randomIndex]; } let positions = [103, 458, 472, 458]; let randomPosition = randomElem(positions); let colors = ['violet', 'indigo', 'blue', 'green']; let randomColor = randomElem(colors);

As you can see, we can use the above function to get random positions as well as random colors. One major problem with this solution is that you will lose the information about the type of value that is being returned. 

Earlier, we were sure that randomPosition would be a number and randomColor would be a string. This helped us in using these values accordingly. Now, all we know is that the returned element could be of any type. In the above code, we could specify the type of randomColor to be a number and still not get any error.

// This code will compile without an error. let colors: string[] = ['violet', 'indigo', 'blue', 'green']; let randomColor: number = randomElem(colors);

A better solution to avoid code duplication while still preserving the type information is to use generics. Here is a generic function that returns random elements from an array.

function randomElem<T>(theArray: T[]): T { let randomIndex = Math.floor(Math.random()*theArray.length); return theArray[randomIndex]; } let colors: string[] = ['violet', 'indigo', 'blue', 'green']; let randomColor: string = randomElem(colors);

Now, I will get an error if I try to change the type of randomColor from string to number. This proves that using generics is a lot safer than using the any type in such situations.

Using Generics May Seem Very Limiting

The previous section discussed how you can use generics instead of the any type in order to write a single function and avoid sacrificing the benefits of type checking. One problem with the generic function that we have written in the previous section is that TypeScript won't let us perform a lot of operations on the variables passed to it. 

This is because TypeScript can't make any assumptions about the type of variable that will be passed to our generic function beforehand. As a result, our generic function can only use those operations which are applicable on all data types. The following example should make this concept clearer.

function removeChar(theString: string, theChar: string): string { let theRegex = new RegExp(theChar, "gi"); return theString.replace(theRegex, ''); }

The above function will remove all occurrences of the specified character from the given string. You might want to create a generic version of this function so that you can also remove specific digits from a given number as well as characters from a string. Here is the corresponding generic function.

function removeIt<T>(theInput: T, theIt: string): T { let theRegex = new RegExp(theIt, "gi"); return theInput.replace(theRegex, ''); }

The removeChar function did not show you an error. However, if you use replace inside removeIt,TypeScript will tell you that replace doesn't exist for type 'T'. This is because TypeScript can no longer assume that theInput is going to be a string.

This restriction on using different methods in a generic function might lead you to think that the concept of generics is not going to be of much use after all. There is not really much that you can do with a handful of methods that must be applicable on all data types for you to use them inside a generic function.

One important thing that you should remember at this point is that you don't generally need to create functions that will be used with all kinds of data types. It is more common to create a function that will be used with a specific set or range of data types. This constraint on data types makes generic functions much more useful.

Create Generic Functions Using Constraints

The generic removeIt function from the previous section showed an error because the replace method inside it is meant to be used with strings, while the parameters passed to it could have any data type. 

You can use the extends keyword to constrain the data types that are passed to a generic function in TypeScript. However, extends is limited to just interfaces and classes. This means that most generic functions that you create will have parameters that extend a base interface or class. 

Here is a generic function that prints the name of people, family members or celebrities passed to it.

interface People { name: string } interface Family { name: string, age: number, relation: string } interface Celebrity extends People { profession: string } function printName<T extends People>(theInput: T): void { console.log(`My name is ${theInput.name}`); } let serena: Celebrity = { name: 'Serena Williams', profession: 'Tennis Player' } printName(serena);

In the above example, we have defined three interfaces, and each of them has a name property. The generic printName function that we created will accept any object that extends People. In other words, you can pass either a family or a celebrity object to this function, and it will print its name without any complaints. You can define many more interfaces, and as long as they have a name property, you will be able to use the printName function without any issue.

This was a very basic example, but you can create more useful generic functions once you are more comfortable with the whole process. For instance, you can create a generic function that calculates the total value of different items sold in a given month as long as each item has a price property to store the price and a sold property that stores the number of items sold. Using generics, you will be able to use the same function as long as the items extend the same interface or class.

Final Thoughts

In this tutorial, I have tried to cover the basics of generics in TypeScript in a beginner-friendly manner. We began the article by discussing the need for generics. After that, we learned about the right way to use generics in order to avoid code duplication without sacrificing the type checking ability. Once you understand the basics discussed here, you can read more about generics in the official documentation.

If you have any questions related to this tutorial, I will be happy to answer them in the comments.

Categories: Web Design

Launching a Website: Your Complete Content Checklist

Most developers have multiple processes in place when it comes to launching a website. It starts with the technical considerations, like where the website will be hosted and what...

The post Launching a Website: Your Complete Content Checklist appeared first on Onextrapixel.

Categories: Web Design

Inspiring Desktop Wallpapers To Make November Even More Colorful (2017 Edition)

Smashing Magazine - Tue, 10/31/2017 - 00:27

   

November is a rather gray month in many parts of the world, so what could be better as some colorful inspiration to start it off with the right foot? To tickle your creativity, artists and designers from across the globe once again challenged their artistic abilities and designed desktop wallpapers for you to indulge in. Wallpapers that are a bit more distinctive as the usual crowd, bound to breathe some fresh life into your routine.

All artworks in this collection come in versions with and without a calendar for November 2017, so it’s up to you to decide if you want to have the month always in sight or just some distraction-free inspiration. A big thank-you to everyone who shared their wallpapers this time around! Enjoy!

The post Inspiring Desktop Wallpapers To Make November Even More Colorful (2017 Edition) appeared first on Smashing Magazine.

Categories: Web Design

A Swift Transition From iOS To macOS Development

Smashing Magazine - Mon, 10/30/2017 - 09:15
Today started just like any other day. You sat down at your desk, took a sip of coffee and opened up Xcode to start a new project. But wait! The similarities stop there. Today, we will try to build for a different platform! Don’t be afraid. I know you are comfortable there on your iOS island, knocking out iOS applications, but today begins a brand new adventure. Today is the day we head on over to macOS development, a dark and scary place that you know nothing about.
Categories: Web Design

How to Deploy With Deployer

Tuts+ Code - Web Development - Mon, 10/30/2017 - 06:00

Automated workflow for deployment is a great tool that every software development team must have. The release process, when it is fast, secure and fault tolerant, can save time for developing more great things. And the good news that there are many great tools for creating an automated release cycle.

In this article, I'm going to introduce you a deployment tool called Deployer. I like to use it because it is written in PHP, is easy to set up, and has many handy features to integrate the deployment process into your team's workflow.

The Deployment Process With Deployer

First of all, let's see the structure of the deployment process with Deployer. It consists of three main parts: a deploy server to init deployment, a production or staging server to host your application, and a git repository to store the code of your application.

When you init a deploy process, you run a deployment script on the deploy server. After this, the deploy server connects to the production server with SSH and does the maintenance things from the production server like cloning the code from a git repository, updating Composer's dependencies, and other stuff you need in order to have a successful release. 

For everyone to be trusted in this chain, we will create and install SSH certificates to the servers and repository.

Install SSH Certificates

We need to create an SSH authentication key on a production server and share it to a git repository. If you don't have any SSH authentication keys on your deploy server, run ssh-keygen and follow the instructions. Keygen will create a public key in a file ~/.ssh/id_rsa.pub.

Now you can install it to the account of your repository. If you don't know how to do it, look at the example of GitHub from the related links at the bottom of the article, or ask your repository hosting service for help.

Also, it is better to create an SSH key on your deploy server to get trusted on the production machine. Use these commands to make a passwordless SSH connection between the deploy and production servers.

vagrant@localserver:~$ ssh-keygen vagrant@localserver:~$ ssh-copy-id -i ~/.ssh/id_rsa.pub www-data@my_project.com

With all certificates installed, we are ready to install Deployer.

Install Deployer

The installation of Deployer is as easy as the installation of Composer. You need to download PHP Archive and make it a global command:

curl -LO https://deployer.org/deployer.phar mv deployer.phar /usr/local/bin/dep chmod +x /usr/local/bin/dep

Let's check the version of Deployer to see if everything is installed correctly:

vagrant@localserver:~$ dep --version Deployer 6.0.3

Everything looks great, and we are ready to create our first deployment script.

Make the First Deployment Script

To initialize Deployer for your project, run dep init. This will execute a utility to generate a deployment script, which will ask you for a project type and repository link and will create the deploy.php file in the current directory. Let's have a look at this file and the main functions that are used in a recipe. 

The functions set and get work with the configuration values, and a shortcut of a getter can be used with a run command:

set('current_path', '~/my_application'); run('rm {{current_path}}/runtime/*');

Each configuration value can be overridden for each host. We can set up a deploy path and SSH user for our application in our deploy script:

host('my_project.com') ->user('www-data') ->set('deploy_path', '~/{{application}}');

To define your own tasks, use the task function and run to run a command on the production server:

task('disk_free', function() { $df = run('df -h /'); writeln($df); });

And then run it with dep and the function name as a param:

vagrant@localserver:/vagrant/deployer$ dep disk_free ➤ Executing task disk_free Filesystem Size Used Avail Use% Mounted on /dev/md0 7.4G 4.7G 2.4G 67% / ✔ Ok

Now you can look through the deploy file and change all the needed params to the configuration of your application.

Deploy to Production

We have already installed Deployer, installed SSL certificates to the deploy and production servers, and made the deployment script, so finally it is time to pull it all together and make the first deployment to production.

To deploy your application, just call dep deploy:

If something has gone wrong, you can roll back to the previously deployed version in just one step:

vagrant@localserver:~$ dep rollback ✔ Executing task rollback

Looks easy, doesn't it?

Now let's check what was created on our production server. Thanks to Deployer, we can do this easily with shortcut commands. Try dep ssh to connect to a server directly using the configuration from the deployment script, or remotely execute a command via SSH tunnel with dep run. Also, this command supports variables that we have set in the script.

So let's have a look at the deploy path:

vagrant@localserver:~$ dep run "tree {{deploy_path}}" . ├── current -> /home/user/my_project/releases/3 ├── releases │   ├── 1 │   │   ├── composer.json │   │   ├── config.php -> /home/user/my_project/shared/config.php │   │   ├── README.md │   │   ├── runtime -> /home/user/data/my_project/shared/runtime │   │   ├── vendor │   │   └── ... │   │   └── web │   │   └── index.php │   ├── 2 │   │   ... │   └── 3 │   ... └── shared ├── config.php └── runtime

The main thing is the releases directory, where Deployer stores the last versions of our application. After each successful deploy or rollback, it links current to the enabled release. Finally, we have a shared directory, which stores files and folders from the shared_dirs and shared_files that we have set in the script file.

On the first deployment, Deployer will copy those files to a shared dir and create a link from the releases dir to the shared dir. The next time, it will just add a link from the release files to the files and folders in the shared directory. Also, you can change any file in a shared directory and Deployer will keep it without changes on each deploy—for example, this is useful for configuration files.

In addition, if you have a composer.json file in the root of your repository, Deployer will call Composer to create a vendor directory and update all needed dependencies. If you don't store the Composer file in the root directory, you can create a custom task to update it.

And now it is time to integrate the application deploy to our processes.

Add a Custom Task

Every team has its own deploy configurations and process to automate, so Deployer has easy tools to extend the standard configuration and add custom tasks. For example, your hosting may have the rule to store applications and webroot in different places, with no rights to change the configuration of Apache or Nginx. 

But there is a way to get over this rule—use symbolic links. So we will add a task for this:

task('deploy:public_html', function() { run('ln -sf {{deploy_path}}/current/web /var/www/my_application.com'); });

And then add it to the main deploy task as part of a release cycle:

task('deploy', [ // ... 'deploy:public_html', // ... ]);

Now run the deploy script again and check if everything is correct with dep ssh.

Third-Party Recipes

Deployer has many recipes to integrate with third parties that can extend the basic functionality. We can use Composer to install them:

composer require deployer/recipes --dev

I like to use the Slack notification recipe. To enable it, we should go to the Slack recipe page, click the Add to Slack button, and select the channel to send notifications. Then we will get the Slack webhook and add this code to deployment.

// require slack recipe require 'recipe/slack.php'; // set slack webhook set('slack_webhook', /* your slack webhook*/); // notify slack after successful deploy after('success', 'slack:notify:success');

After these changes, Deployer will send a message like this to the deploy channel:


Now you can add your team to the channel so everyone who's involved can be notified.

Conclusion

In this tutorial we have installed Deployer and created a deploy script that can be used to deploy our application from a git repository to a production or staging server in just one click.

Also, it can be integrated into team processes—for example, an application can be deployed automatically after changes in the master branch and notification can be made on a Slack channel about successful deployment.

If you have any questions, don't hesitate to ask questions in the comments to the article. 

Further Reading and Related Links
Categories: Web Design

TypeScript for Beginners, Part 4: Classes

Tuts+ Code - Web Development - Mon, 10/30/2017 - 05:00

We have come a long way in learning TypeScript since starting this series. The first tutorial gave you a brief introduction of TypeScript and suggested some IDEs that you can use for writing TypeScript. The second tutorial focused on data types, and the third tutorial discussed the basics of interfaces in TypeScript.

As you might already know, JavaScript has only recently added native support for classes and object-oriented programming. However, TypeScript has allowed developers to use classes in their code for a long time. This code is then compiled to JavaScript that will work across all major browsers. In this tutorial, you will learn about classes in TypeScript. They are similar to their ES6 counterparts but are stricter.

Creating Your First Class

Let's start with the basics. Classes are a fundamental part of object-oriented programming. You use classes to represent any entity which has some properties and functions that may act on given properties. TypeScript gives you full control over the properties and functions that are accessible inside and outside their own containing class. Here is a very basic example of creating a Person class.

class Person { name: string; constructor(theName: string) { this.name = theName; } introduceSelf() { console.log("Hi, I am " + this.name + "!"); } } let personA = new Person("Sally"); personA.introduceSelf();

The above code creates a very simple class called Person. This class has a property called name and a function called introduceSelf. The class also has a constructor, which is also basically a function. However, constructors are special because they are called every time we create a new instance of our class. 

You can also pass parameters to constructors in order to initialize different properties. In our case, we are using the constructor to initialize the name of the person that we are creating using the Person class. The introduceSelf function is a method of the Person class, and we are using it here to print the name of the person to the console. All these properties, methods, and the constructor of a class are collectively called class members.

You should keep in mind that the Person class does not automatically create a person by itself. It acts more like a blueprint with all the information about the attributes a person should have once created. With that in mind, we created a new person and named her Sally. Calling the method introduceSelf on this person will print the line "Hi, I am Sally!" to the console.

Private and Public Modifiers

In the previous section, we created a person named Sally. Right now, it is possible to change the name of the person from Sally to Mindy anywhere in our code, as shown in the following example.

class Person { name: string; constructor(theName: string) { this.name = theName; } introduceSelf() { console.log("Hi, I am " + this.name + "!"); } } let personA = new Person("Sally"); // Prints "Hi, I am Sally!" personA.introduceSelf(); personA.name = "Mindy"; // Prints "Hi, I am Mindy!" personA.introduceSelf();

You might have noticed that we were able to use both the name property and the introduceSelf method outside the containing class. This is because all the members of a class in TypeScript are public by default. You can also explicitly specify that a property or method is public by adding the keyword public before it.

Sometimes, you don't want a property or method to be accessible outside its containing class. This can be achieved by making those members private using the private keyword. In the above code, we could make the name property private and prevent it from being changed outside the containing class. After this change, TypeScript will show you an error saying that the name property is private and you can only access it inside the Person class. The screenshot below shows the error in Visual Studio Code.

Inheritance in TypeScript

Inheritance allows you to create more complex classes starting from a base class. For example, we can use the Person class from the previous section as a base to create a Friend class that will have all the members of the Person and add some members of its own. Similarly, you could also add a Family or Teacher class. 

They will all inherit the methods and properties of the Person while adding some methods and properties of their own to set them apart. The following example should make it clearer. I have also added the code for the Person class here so that you can easily compare the code of both the base class and the derived class.

class Person { private name: string; constructor(theName: string) { this.name = theName; } introduceSelf() { console.log("Hi, I am " + this.name + "!"); } } class Friend extends Person { yearsKnown: number; constructor(name: string, yearsKnown: number) { super(name); this.yearsKnown = yearsKnown; } timeKnown() { console.log("We have been friends for " + this.yearsKnown + " years.") } } let friendA = new Friend("Jacob", 6); // Prints: Hi, I am Jacob! friendA.introduceSelf(); // Prints: We have been friends for 6 years. friendA.timeKnown();

As you can see, you have to use the extend keyword for the Friend class to inherit all the members of the Person class. It is important to remember that the constructor of a derived class must always invoke the constructor of the base class with a call to super().

You might have noticed that the constructor of Friend did not need to have the same number of parameters as the base class. However, the first name parameter was passed to super() in order to invoke the constructor of the parent, which also accepted one parameter. We did not have to redefine the introduceSelf function inside the Friend class because it was inherited from the Person class.

Using the Protected Modifier

Up to this point, we have only made the members of a class either private or public. While making them public allows us to access them from anywhere, making the members private limits them to their own containing class. Sometimes you might want the members of a base class to be accessible inside all the derived classes. 

You can use the protected modifier in such cases to limit the access of a member only to derived classes. You can also use the protected keyword with the constructor of a base class. This will prevent anyone from creating an instance of that class. However, you will still be able to extend classes based on this base class.

class Person { private name: string; protected age: number; protected constructor(theName: string, theAge: number) { this.name = theName; this.age = theAge; } introduceSelf() { console.log("Hi, I am " + this.name + "!"); } } class Friend extends Person { yearsKnown: number; constructor(name: string, age: number, yearsKnown: number) { super(name, age); this.yearsKnown = yearsKnown; } timeKnown() { console.log("We have been friends for " + this.yearsKnown + " years.") } friendSince() { let firstAge = this.age - this.yearsKnown; console.log(`We have been friends since I was ${firstAge} years old.`) } } let friendA = new Friend("William", 19, 8); // Prints: We have been friends since I was 11 years old. friendA.friendSince();

In the above code, you can see that we made the age property protected. This prevents the use of age outside any classes derived from Person. We have also used the protected keyword for the constructor of the Person class. Declaring the constructor as protected means that we will no longer be able to directly instantiate the Person class. The following screenshot shows an error that pops up while trying to instantiate a class with the protected constructor.

Final Thoughts

In this tutorial, I have tried to cover the basics of classes in TypeScript. We began the tutorial by creating a very basic Person class that printed the name of the person to the console. After that, you learned about the private keyword, which can be used to prevent the members of a class from being accessed at any arbitrary point in the program. 

Finally, you learned how to extend different classes in your code using a base class with inheritance. There is a lot more that you can learn about classes in the official documentation.

If you have any questions related to this tutorial, let me know in the comments.

Categories: Web Design

A Swift Transition From iOS To macOS Development

Smashing Magazine - Mon, 10/30/2017 - 01:15

   

Today started just like any other day. You sat down at your desk, took a sip of coffee and opened up Xcode to start a new project. But wait! The similarities stop there. Today, we will try to build for a different platform! Don’t be afraid. I know you are comfortable there on your iOS island, knocking out iOS applications, but today begins a brand new adventure. Today is the day we head on over to macOS development, a dark and scary place that you know nothing about.

The good news is that developing for macOS using Swift has a lot more in common with iOS development than you realize. To prove this, I will walk you through building a simple screen-annotation application. Once we complete it, you will realize how easy it is to build applications for macOS.

The post A Swift Transition From iOS To macOS Development appeared first on Smashing Magazine.

Categories: Web Design

Facebook Messenger Marketing: How it Works and Why it Helps

Webitect - Sat, 10/28/2017 - 14:32

If you’re like most people, you probably waste at least some of the workday browsing Facebook. That’s alright – I do, too. But Facebook doesn’t have to be a time-waster. In fact, Facebook can be a serious benefit for your business. Beyond traditional marketing, Facebook ads can also help you reach likely potential customers. Of course, you’ll also need to make sure you’re on the right track by measuring your Facebook marketing success. Today I want to go a bit more in-depth. Let’s look at a Facebook marketing strategy which isn’t very common – but which can really generate leads.

The post Facebook Messenger Marketing: How it Works and Why it Helps appeared first on Webitect.

Categories: Web Design

Quick Wins For Improving Performance And Security Of Your Website

Smashing Magazine - Thu, 10/26/2017 - 13:31
When it comes to building and maintaining a website, one has to take a ton of things into consideration. However, in an era when people want to see results fast, while at the same time knowing that their information online is secure, all webmasters should strive for a couple of things: Improving the performance of their website, Increasing their website’s security. Both of these goals are vital in order to run a successful website.
Categories: Web Design

Building With Vue.js 2 and Firebase

Tuts+ Code - Web Development - Thu, 10/26/2017 - 06:00
Introduction

Firebase is Google's mobile platform that helps you develop high-quality apps and grow your business. In this tutorial, you will make good use of one of Firebase's awesome features: the Realtime Database. 

You will build a single page application to create books. This book will be saved to your Firebase database, and you will be able to retrieve and delete books you have created.

Let's get started.

Set Up Firebase

Go to Google's Firebase page to create a new account. When done with that, log in to your console. Click on the option to add a project. Enter your project details and click on the button CREATE PROJECT.

This will lead you to your console. The Firebase console helps you manage your Firebase configuration settings.

For this tutorial, you'll need to make access to your database public. From the panel on the left, select Database. Select Realtime Database from the options that show next by clicking GET STARTED. Making your database public involves editing the rules. So click RULES on the page that loads next.

Make your rules look like this.

{ "rules": { ".read": true, ".write": true } }

Click the option to PUBLISH when done.

With this rule, authentication is not required to perform read and write actions on your database. This is needful for the application you will be building in this tutorial.

Set Up a Project Using Vue CLI

Vue CLI allows you to scaffold Vue.js projects. If you do not have it on your machine, you can get it by running:

npm install -g vue-cli

This will install it globally on your machine. Here is how Vue-CLI is used.

vue init <template-name> <project-name>

To learn more about Vue-CLI, check the GitHub page.

For this project you will use webpack templates, so run the command below from your terminal.

vue init webpack vue-book

These are the installation options I used.

? Project name vue-book ? Project description A Vue.js project ? Author izuchukwu1 <chineduizuchukwu1@gmail.com> ? Vue build standalone ? Install vue-router? No ? Use ESLint to lint your code? Yes ? Pick an ESLint preset Standard ? Setup unit tests with Karma + Mocha? No ? Setup e2e tests with Nightwatch? No vue-cli · Generated "vue-book". To get started: cd vue-book npm install npm run dev Documentation can be found at https://vuejs-templates.github.io/webpack

Navigate to your project folder. The files and folders generated by Vue-CLI have a tree like this.

├── build │ ├── build.js │ ├── check-versions.js │ ├── dev-client.js │ ├── dev-server.js │ ├── utils.js │ ├── vue-loader.conf.js │ ├── webpack.base.conf.js │ ├── webpack.dev.conf.js │ └── webpack.prod.conf.js ├── config │ ├── dev.env.js │ ├── index.js │ └── prod.env.js ├── index.html ├── package.json ├── README.md ├── src │ ├── App.vue │ ├── assets │ │ └── logo.png │ ├── components │ │ └── HelloWorld.vue │ └── main.js └── static 6 directories, 19 files

Now run the command to install your dependencies.

npm install

When done, you can start your dev server by running:

npm run devAdd Firebase to the Project

To bind Firebase data to Vue.js data properties, we will make use of the VueFire library. You can check more about it on GitHub.

Run the command below:

npm install firebase vuefire --save

Open up main.js to add VueFire. Make your main.js file look like what I have below.

#src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import VueFire from 'vuefire' Vue.use(VueFire) Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', components: { App } })Set Up the Firebase Connection

Go to your Firebase console, and click on the Overview link on the left panel. Select the option to add Firebase to your web app. Copy the snippet that pops up in the window to a text file. The snippet contains your apiKey, authDomain, databaseURL, projectId, storageBucket, and messagingSenderId. You need these details to be able to access your Firebase database.

You start by importing Firebase from the core Firebase library. A Firebase instance is created using the initializeApp method. The snippet you copied has to be passed to this method as an object. This has to be done in the script section of your App.vue, like this.

#src/App.vue import Firebase from 'firebase' let config = { apiKey: "...", authDomain: "...", databaseURL: "...", storageBucket: "...", messagingSenderId: "..." }; let app = Firebase.initializeApp(config) let db = app.database() let booksRef = db.ref('books')

After creating the Firebase instance, the database reference is obtained by using app.database().

Book Listing

Since VueFire makes it easy to bind Vue.js data properties to Firebase, implementing the books listing feature requires you to add this.

firebase: { books: booksRef },

You add that below:

name: 'app',

Now you have access to the book items from your database. The template will look like this.

<div class="panel-body"> <table class="table table-striped"> <thead> <tr> <th>Title</th> <th>Author</th> </tr> </thead> <tbody> <tr v-for="book in books"> <td><a v-bind:href="book.url">{{book.title}}</a></td> <td>{{book.author}}</td> </tr> </tbody> </table> </div>

The v-for directive is used to iterate through the available books. Each book will be outputted in a new table row.

Adding a New Book

To put in place the addition of new books, you need to first define the data model that will be used.

data () { return { newBook: { title: '', author: '', url: 'http://', isbn: '' } } }

Next, set up the template to look like this.

<div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Add New Books</h3> </div> <div class="panel-body"> <form id="form" class="form-inline" v-on:submit.prevent="addBook"> <div class="form-group"> <label for="bookTitle">Title:</label> <input type="text" id="bookTitle" class="form-control" v-model="newBook.title"> </div> <div class="form-group"> <label for="bookAuthor">Author:</label> <input type="text" id="bookAuthor" class="form-control" v-model="newBook.author"> </div> <div class="form-group"> <label for="bookUrl">Url:</label> <input type="text" id="bookUrl" class="form-control" v-model="newBook.url"> </div> <input type="submit" class="btn btn-primary" value="Add Book"> </form> </div> </div>

The v-model directive is used to bind the newBook properties to the corresponding input.

The v-on directive will lead us to create an event handler method that gets called whenever a new book is to be created. Here is what the event handler should look like.

methods: { addBook: function() { booksRef.push(this.newBook) this.newBook.title = '', this.newBook.author = '', this.newBook.url = 'http://', this.newBook.isbn = '' }, },

The addBook method helps insert new book objects into the Firebase database. The data is also synced across all clients. 

Deleting Books

Let's add the ability to delete books. Add another column to the book listing.

<td> <span class="glyphicon glyphicon-trash" aria-hidden="true" v-on:click="removeBook(book)"></span> </td>

Let's put in place a method that gets called each time the button is clicked. The method is passed the book you intend to delete, which is actually the key to the book, as you will see soon. The remove() is called on the returned book to delete it from the database.

Here is what the method looks like.

removeBook: function (book) { booksRef.child(book['.key']).remove() }

With that, you are done with App.vue. Putting everything together, here is how your App.vue file should look.

<template> <div id="app" class="container"> <div class="page-header"> <h1>Vue Book</h1> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3>Add Book</h3> </div> <div class="panel-body"> <form id="form" class="form-inline" v-on:submit.prevent="addBook"> <div class="form-group"> <label for="bookTitle">Title:</label> <input type="text" id="bookTitle" class="form-control" v-model="newBook.title"> </div> <div class="form-group"> <label for="bookAuthor">Author:</label> <input type="text" id="bookAuthor" class="form-control" v-model="newBook.author"> </div> <div class="form-group"> <label for="bookUrl">URL:</label> <input type="text" id="bookUrl" class="form-control" v-model="newBook.url"> </div> <div class="form-group"> <label for="bookIsbn">ISBN:</label> <input type="text" id="bookIsbn" class="form-control" v-model="newBook.isbn"> </div> <input type="submit" class="btn btn-primary" value="Add Book"> </form> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3>Books Lists</h3> </div> <div class="panel-body"> <table class="table table-stripped"> <thead> <tr> <th>Title</th> <th>Author</th> <th></th> </tr> </thead> <tbody> <tr v-for="book in books"> <td> <a v-bind:href="book.url">{{book.title}}</a> </td> <td> {{book.author}} </td> <td> <span class="glyphicon glyphicon-trash" aria-hidden="true" v-on:click="removeBook(book)"></span> </td> </tr> </tbody> </table> </div> </div> </div> </template> <script> import Firebase from 'firebase' let config = { apiKey: "...", authDomain: "...", databaseURL: "...", storageBucket: "...", messagingSenderId: "..." } let app = Firebase.initializeApp(config) let db = app.database() let booksRef = db.ref('books') export default { name: 'app', firebase: { books: booksRef }, data () { return { newBook: { title: '', author: '', url: 'http://', isbn: '' } } }, methods: { addBook: function() { booksRef.push(this.newBook) this.newBook.title = '', this.newBook.author = '', this.newBook.url = 'http://', this.newBook.isbn = '' }, removeBook: function(book) { booksRef.child(book['.key']).remove() } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; margin-top: 60px; } </style>

In the template, I added some Bootstrap classes. For these to work, open your index.html file and make it look like this.

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>vue-book</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" /> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </body> </html>Conclusion

JavaScript has become extremely popular and is now capable of building mature applications (as we've seen above). If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato Market.

In this tutorial, you learned about Firebase. You were able to connect Vue.js and Firebase using VueFire. Your application can make read and write requests to your Firebase database.

You can go further by adding more features like categories and description.

Categories: Web Design

Quick Wins For Improving Performance And Security Of Your Website

Smashing Magazine - Thu, 10/26/2017 - 05:31

   

When it comes to building and maintaining a website, one has to take a ton of things into consideration. However, in an era when people want to see results fast, while at the same time knowing that their information online is secure, all webmasters should strive for a) improving the performance of their website, and b) increasing their website's security.

Both of these goals are vital in order to run a successful website. So, we've put together a list of five technologies you should consider implementing to improve both the performance and security of your website.

The post Quick Wins For Improving Performance And Security Of Your Website appeared first on Smashing Magazine.

Categories: Web Design

The Role Of Storyboarding In UX Design

Smashing Magazine - Wed, 10/25/2017 - 13:37
To come up with a proper design, UX designers use a lot of different research techniques, such as contextual inquires, interviews and workshops. They summarize research findings into user stories and user flows and communicate their thinking and solutions to the teams with artifacts such as personas and wireframes. But somewhere in all of this, there are real people for whom the products are being designed for. In order to create better products, designers must understand what’s going on in the user’s world and understand how their products can make the user’s life better.
Categories: Web Design

How to Measure Your SEO Campaign Results

Webitect - Wed, 10/25/2017 - 07:44

It can feel impossible to run a successful SEO campaign. SEO has become a $65 billion industry. But that doesn’t mean you need to spend a billion dollars hiring people to handle it for you. A lot of people feel like they don’t know what they’re doing when it comes to drinking wine. And telling the difference between different SEO strategies can be just as hard for the uninitiated as telling the difference between a cabernet and a pinot noir.   The worst thing that you can do for your campaign is measuring the wrong metrics. Instead of misinforming yourself

The post How to Measure Your SEO Campaign Results appeared first on Webitect.

Categories: Web Design

Testing a Node.js API

Tuts+ Code - Web Development - Wed, 10/25/2017 - 06:00
Introduction

Tests are important; they provide a safeguard for your applications or APIs. As beginners, it is possible to be oblivious of the need to write tests that cover the important parts of what you are building. Yet you will meet with it as you make progress as a developer.

In a previous tutorial, you learned how to build an API with Node.js. If you have not gone through it, I suggest you do so before continuing with this. In this tutorial, you will be writing tests for an API built using Node.js and Express. At the end of this tutorial, you will know how testing works in Node.js, and you will be able to build functional and tested APIs.

Testing Tools

You will be making use of Mocha, Expect, and Supertest.

Mocha is a JavaScript test framework which makes asynchronous testing simple and fun. Mocha comes with tons of great features which can be found on the website. You will be making use of a handful of them.

Expect is an assertion library that makes it easy for you to make better assertions. You will see how that works. Supertest provides a high-level abstraction for testing HTTP. This is needful as you will be testing an API.

Enough talk, time to write some code.

Project Setup

I have a to-do list project already set up for you. The model, config file, and part of the app.js are already done for you. Go over to GitHub and clone the repository. Or you can simply do:

git clone https://github.com/izuchukwu1/node-todo-api.git

Your package.json should look like this.

#package.json { "name": "node-todo-api", "version": "1.0.0", "description": "", "main": "server.js", "scripts": { "start": "node server/server.js", "test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha server/**/*.test.js", "test-watch": "nodemon --exec 'npm test'" }, "engines": { "node": "8.0.0" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.17.2", "express": "^4.15.3", "lodash": "^4.17.4", "mongodb": "^2.2.29", "mongoose": "^4.11.1" }, "devDependencies": { "expect": "^1.20.2", "mocha": "^3.4.2", "nodemon": "^1.11.0", "supertest": "^3.0.0" } }

Now run the command to install the dependencies.

npm installPOST Request Test

For your test, create a new folder called test; this folder should be in your server directory. Now create a new file where you will write your test. Name the file server.test.js.

In this file, start by requiring the modules you installed. You also need to require your server file and your model.

#server/test/server.test.js const expect = require('expect') const request = require('supertest') const {ObjectId} = require('mongodb') const {app} = require('./../server') const {Todo} = require('./../models/todo')

You need to have a few to-dos that will be used during tests. But these to-dos will be deleted from the test database each time you run your test suite. To handle that, create two tests like so.

#server/test/server.test.js const todos = [{ _id: new ObjectId(), text: "First test todo" }, { _id: new ObjectId(), text: "Second test todo", completed: true, completedAt: 333 }] beforeEach((done) => { Todo.remove({}).then(() => { return Todo.insertMany(todos) }).then(() => done()) })

The before block cleans your Todo database, then inserts the to-dos set above. This ensures that you have a stable amount of entries in your database so your tests do not run into issues.

With that done, you can write the test for the POST request. For your POST request, you will write two tests. The first will make a request for a valid to-do and be successful. The second will make a request with an invalid body, and this should not create a new to-do.

Here is what the test should look like.

#server/test/server.test.js describe('POST /todos', () => { // 1 it('should create a new todo', (done) => { let text = 'Test todo text' // 2 request(app) // 3 .post('/todos') .send({text}) .expect(200) .expect((res) => { expect(res.body.text).toBe(text) }) .end((err, res) => { // 4 if (err) { return done(err) } Todo.find({text}).then((todos) => { // 5 expect(todos.length).toBe(1) expect(todos[0].text).toBe(text) done() }).catch((e) => done(e)) }) }) it('should not create todo with invalid body data', (done) => { // 6 request(app) // 7 .post('/todos') .send({}) .expect(400) .end((err, res) => { if (err) { return done(err) } Todo.find().then((todos) => { // 8 expect(todos.length).toBe(2) done() }).catch((e) => done(e)) }) }) })

Run the test using the command:

npm run test

It should fail. Here is what is happening:

  1. Describes the test.
  2. Creates a new to-do and saves it as a value to text.
  3. You make a POST request to the /todos path of your API, sending the to-do you created as the body of the request. You expect the status code for the request to be 200 and the body of the to-do to equal the value of text.
  4. An error is returned if there is any, and this will cause the request to end. Thus the next block of code will not run. If no error is encountered, the flow continues.
  5. A request is made to the database to find the created to-do. You expect the length of the to-dos in the database to be 1, and the text of the to-do to be equal to the value of text.
  6. This is the test made with invalid body data.
  7. A POST request is made to the /todos path. This time, you are sending a request with no body. You expect to get a 400 request. No need to check the body as you are not sending any. If an error is encountered, it gets returned and the code stops running.
  8. If no error is encountered, a request is made to the database to check the length of the to-dos. We expect that the database will contain only 2, which are the to-dos created at the beginning.

To get this test passing, go to your server.js file and drop in the code needed for the POST request.

#server/server.js app.post('/todos', (req, res) => { let todo = new Todo({ text: req.body.text }) todo.save().then((doc) => { res.send(doc) }, (e) => { res.status(400).send(e) }) })GET Request Test

This is simple—the test should return the length of to-dos available in the database. As you already know, the length of the todos should be 2. Why? You guessed right. At the beginning of the test suite, you created a beforeEach block that cleans your database and inserts new to-dos each time the test suite is run.

To test that the request to get all to-dos works, here is the code for that.

#server/test/server.test.js describe('GET /todos', () => { it('should get all todos', (done) => { request(app) .get('/todos') .expect(200) .expect((res) => { expect(res.body.todos.length).toBe(2) }) .end(done) }) })

In the above, you are making a GET request to the /todos path. This time, you are not passing anything as the body of the request because it is a GET request. You expect to get a response with the status code of 200. Then you expect that the length of the to-dos will be 2.

When you run the test, you should get an error. Try getting the error to pass on your own.

I bet you got that to work. Here is the code to get the test to pass; compare it with your solution.

#server/server.js app.get('/todos', (req, res) => { Todo.find().then((todos) => { res.send({todos}) }, (e) => { res.status(400).send(e) }) })

When a GET request is made to the /todos path, you want to find every to-do in the Todo collection and return them as to-dos. Adding this to server.js causes the test to pass.

Next, you'll write three tests for the GET request made to retrieve individual to-dos. The first should retrieve and return the to-do. The second and third should return 404 error in cases where the to-do is not found.

Open up your server.test.js and create a new describe block with the first test case.

#server/server.test.js describe('GET /todos/:id', () => { it('should return todo doc', (done) => { request(app) .get(`/todos/${todos[0]._id.toHexString()}`) .expect(200) .expect((res) => { expect(res.body.todo.text).toBe(todos[0].text) }) .end(done) })

This test makes a GET request to retrieve the first to-do available in your database. You expect to get a 200 status code, and then check that the text value of the to-do is the same as the one created.

The next test looks like this.

it('should return 404 if todo is not found', (done) => { let _id = new ObjectId('5967989ee978311656e93a59') request(app) .get(`/todos/${todos/_id.toHexString()}`) .expect(404) .end(done) })

Here you are looking for a to-do using an ID that does not correspond to the ID of any to-do saved in your database. The test expects this request to return a 404 error.

The last test is like the first but a little different; here is how it looks.

it('should return 404 for non-object ids', (done) => { let hexId = '5967989ee978311656e93a5312' request(app) .get(`/todos/${todos/hexId}`) .expect(404) .end(done) }) })

Here, you create an invalid ObjectId and try to query the database to get a to-do matching the ObjectId created. The test expects the request to return a 404 error. 

When you run the test, they should all fail. To get them to pass, add the code below to your server.js file.

#server/server.js app.get('/todos/:id', (req, res) => { let id = req.params.id // 1 if (!ObjectId.isValid(id)) { // 2 return res.status(404).send('ID is not valid') } Todo.findById(id).then((todo) => { if (!todo) { // 3 return res.status(404).send() } res.send({todo}) //4 }).catch((e) => { res.status(400).send() }) })
  1. Get the ID of the to-do requested from the params.
  2. Check to see if the ID is valid. If the ID is not valid, an error stating this is sent.
  3. If the ID is valid, try to find a to-do that matches that ID using the findById method. If no to-do is found with that ID, a 404 error is sent.
  4. If a to-do is found, the to-do is sent. Then you catch any error that occurs and sends it.

Run the test command once more, and it should pass.

DELETE Request Test

The test for your DELETE request will be a little like what you have for your GET request.

First, you want to test that a to-do is deleted.

#server/test/server.test.js describe('DELETE /todos/:id', () => { it('should delete a todo', (done) => { let hexId = todos[0]._id.toHexString() // 1 request(app) .delete(`/todos/${hexId}`) .expect(200) .expect((res) => { expect(res.body.todo._id).toBe(hexId) }) .end((err, res) => { // 2 if (err) { return done(err) } }) Todo.findById(hexId).then((todo) => { // 3 expect(todo.hexId).toNotExist() done() }).catch((e) => done(e)) })

Here is what is happening above:

  1. You set the id of the to-do to a variable called hexId. Next, a DELETE request is made to the path of the to-do, using the ID. You expect to get a 200 response, and the to-do obtained to match the value of hexId.
  2. If any error is encountered, it is returned.
  3. If no error, the test goes further to query your database using the ID saved as the value of hexId. Since a DELETE request has been previously sent, the test expects that the to-do matching that ID does not exist.

Next, you want to test that when a request is made to delete a to-do that does not exist, the response contains a 404 error. It is important to have this, as it is not possible to delete a to-do twice. Here is how the test for this should look.

#server/test/server.test.js it('should return 404 if todo is not found', (done) => { let hexId = new ObjectId().toHexString() request(app) .delete(`/todos/${todos/hexId}`) .expect(404) .end(done) })

This creates an ID for a to-do that does not exist in the database. Then a DELETE request is made to delete the to-do. The test is expected to return a 404 error as the to-do does not exist.

You want to test that a DELETE using an invalid ID returns a 404 error, like so.

#server/test/server.test.js it('should return 404 for non-object ids', (done) => { request(app) .delete('/todos/123abc') .expect(404) .end(done) }) })

To get the test to pass, open your server.js and drop this.

#server/server.js app.delete('/todos/:id', (req, res) => { let id = req.params.id if (!ObjectId.isValid(id)) { return res.status(404).send() } Todo.findByIdAndRemove(id).then((todo) => { if (!todo) { return res.status(404).send() } res.send({todo}) }).catch((e) => { res.status(400).send() }) })

Run the command to test:

npm run test

And your tests should be passing.

Conclusion

At this point, you now know how to set up a test suite when building an API using Node.js. You have used Mocha, Expect, and Supertest to test an API. One advantage of doing this is that you do not need to always fire up Postman when building your API. With your test, you can get to know what is broken.

Before we wrap up, note that JavaScript has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available on Envato Market.

Using what you now know, you are good to explore the world of testing.

Categories: Web Design

The Role Of Storyboarding In UX Design

Smashing Magazine - Wed, 10/25/2017 - 05:37

   

To come up with a proper design, UX designers use a lot of different research techniques, such as contextual inquires, interviews and workshops. They summarize research findings into user stories and user flows and communicate their thinking and solutions to the teams with artifacts such as personas and wireframes. But somewhere in all of this, there are real people for whom the products are being designed for.

In order to create better products, designers must understand what’s going on in the user’s world and understand how their products can make the user's life better. And that’s where storyboards come in.

The post The Role Of Storyboarding In UX Design appeared first on Smashing Magazine.

Categories: Web Design

The Front-End Performance Challenge: Make Your Site Blazingly Fast And Win Some Smashing Prizes

Smashing Magazine - Tue, 10/24/2017 - 14:24
Not too long ago, front-end performance was a mere afterthought. Something that was postponed to the end of a project and that didn’t go much beyond minification, asset optimization, and maybe a few adjustments on the server’s config file. But things have changed. We have become more conscious of the impact performance has on the user experience, and the tools and techniques that help us cater for snappy experiences have improved and are widely supported now as well.
Categories: Web Design

We’ve Got A Lil’ Announcement To Make: Rachel Andrew Is SmashingMag’s New Editor-In-Chief

Smashing Magazine - Tue, 10/24/2017 - 10:47
Sometimes things evolve faster than you think. Something that started as a simple WordPress blog back in September 2006, has evolved into a little Smashing universe — with books, eBooks, conferences, workshops, consultancy, job board and, most recently, 56 fancy cats (upcoming, also known as Smashing Membership). We have a wonderful team making it all happen, but every project requires attention and focus and every project desperately needs time to evolve and flourish and improve.
Categories: Web Design

The Front-End Performance Challenge: Make Your Site Blazingly Fast And Win Some Smashing Prizes

Smashing Magazine - Tue, 10/24/2017 - 06:24

   

Not too long ago, front-end performance was a mere afterthought. Something that was postponed to the end of a project and that didn’t go much beyond minification, asset optimization, and maybe a few adjustments on the server’s config file. But things have changed.

We have become more conscious of the impact performance has on the user experience, and the tools and techniques that help us cater for snappy experiences have improved and are widely supported now as well.

The post The Front-End Performance Challenge: Make Your Site Blazingly Fast And Win Some Smashing Prizes appeared first on Smashing Magazine.

Categories: Web Design

Pages