34,79 €
This book starts with the basic installation and overview of the main components in Meteor. You’ll get hands-on multiple versatile applications covering a wide range of topics from adding a front-end views with the hottest rendering technology React to implementing a microservices oriented architecture.All the code is written with ES6/7 which is the latest significantly improved JavaScript language. We’ll also look at real-time data streaming, server to server data exchange, responsive styles on the front-end, full-text search functionality, and integration of many third-party libraries and APIs using npm.
By the end of the book, you’ll have the skills to quickly prototype and even launch your next app idea in a matter of days.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 342
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2017
Production reference: 1260517
ISBN 978-1-78712-988-7
www.packtpub.com
Author
Dobrin Ganev
Copy Editor
Shaila Kusanale
Reviewer
Olivier Pons
Project Coordinator
Devanshi Doshi
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Shweta Pant
Indexer
Rekha Nair
Content Development Editor
Roshan Kumar
Graphics
Jason Monteiro
Technical Editor
Murtaza Tinwala
Production Coordinator
Shraddha Falebhai
Dobrin Ganev is a Calgary-based software developer with years of experience in various domains, from large-scale distributed applications to frontend web development with the latest JavaScript frameworks. In recent years, he has been focusing on architecting and prototyping solutions in various subjects, such as enterprise search, GIS, predictive analytics, and real-time distributed systems.
Olivier Pons is a highly-skilled developer who's been building websites for many years. He's a teacher in France at the IUT (University of Sciences) in Aix-en-Provence, CESI (Centre d'Études Supérieures en Informatique), ISEN (Institut Supérieur de l’Électronique et du Numérique), G4 Marseille, and École d’Ingénieurs des Mines de Gardanne, where he teaches state-of-the-art web techniques: Django/Python, Node.js, Big Data / NoSQL, MVC fundamentals, PHP for experts, WordPress for experts, Symfony, jQuery, Apache, nginx and Apache advanced configuration, Linux basics, and advanced VIM techniques. He has already done some technical reviews, including the PacktLib books Learning ExtJS, Building Modern JavaScript Applications, jQuery hotshots, jQuery Mobile Web Development Essentials, and Wordpress Complete, among others. In 2011, he left a full-time job as a Delphi developer and PHP expert to concentrate on his own company, HQF Development (http://hqf.fr). He currently runs a number of websites, including http://www.cogofly.com, http://www.krystallopolis.com, http://www.papdevis.fr, and http://olivierpons.fr, his own web development blog. He’s currently making a Unity mcq mobile application, which works along with a Django website.
He works as teacher, highly-skilled developer and project manager, and also helps big companies' CTOs make the best choices for their web projects.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787129888/.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Foundation of Meteor
Setting up the development environment
Building a Meteor app
The frontend with React
The React's state
Adding state to a stateless function component
Inheritance versus composition
Adding a state to a component
Meteor with React
Adding and removing atmosphere packages in Meteor
Integrating React with Meteor's reactive data system
Explore MongoDB in the Meteor shell
Publishing and Subscribing
Improvements in the current code
Summary
Building a Shopping Cart
Creating the project structure
On the server
Building the application components
The ProductsContainer
PropTypes
The CartContainer
Adding router to the application
App.js
ProductComponent.js
The data containers
BooksContainer.js
MusicContainer.js
Meteor methods
Removing item from the cart
Updating the quantity of an item in the cart
Let's create another method that will calculate the cart's total price
Considerations for scalability
Basic validations on the server
Defining a schema
Defaults
Summary
Style Your React Components with Bootstrap and Material Design
Mobile first
Making it mobile friendly!
Modular CSS with LESS
Test it out!
Modular CSS with Syntactically Awesome StyleSheets
Bootstrap and Meteor
Using CSS modules with Meteor
Meteor and webpack styling the shopping cart
Test it out!
Test it out!
Styling the shopping cart with Material Design Lite
The grid
Summary
Real-Time Twitter Streaming
Twitter streaming
The application structure
Meteor with Redux
Redux and pure functions
The Redux parts
Why do we need Redux when we have Minimongo on the client?
Building the App
Folder structure client
Getting the data from the collection
Async actions in Redux
Creating the App components
Connecting the Redux store with the React components
The containers and the components of the App
The Filter components
Tweets component
The Sentiment component
On the Server
Test it out and improve it!
Summary
Developing Kanban Project Management Tool
Drag and drop in React
Test it out!
Building the App
The reducer function
Building the Modal
Test it out!
Higher-Order Components
Test it out!
Summary
Building a Real-Time Search Application
Importing the data
Index a text field
Try it out!
Building the app
Test it Out!
Summary
Real-Time Maps
Building the App
The server side
Test it out!
Summary
Build a Chatbot with Facebook’s Messenger Platform
Building the app
Training the bot
Moving the chatbot to the Meteor app
Test it out and improve it!
Adding Cassandra to our stack
Adding GraphQL to the stack
Summary
Build Internet of Things Platform
What is gRPC?
Test it out!
Building the apps
Test it out!
Test it out!
Test it and improve it!
Summary
This book will help you explore the basics of Meteor, right from its core components to understanding how the platform works for building a variety of applications. This book will also help in familiarizing you with a variety of modern-day applications. It will also give an introduction to various systems, such as Redux and React, and explore how to launch an app idea in a very short period of time.
Chapter 1, Foundation of Meteor, walks you through the installation of Meteor and getting to grips with the core concepts of the framework.
Chapter 2, Building a Shopping Cart, teaches you to build a CRUD shopping cart application using React as a view layer. Also, we will cover client-side routing and Meteor methods.
Chapter 3, Style Your React Components with Bootstrap and Material Design, provides an overview of the responsive web design by building a mobile first CSS grid from scratch using SASS and LESS; then we will move on to exploring the two most popular CSS frameworks: Bootstrap and Material Design. By styling the shopping cart application from the last chapter, we will go over the challenges of building scalable CSS and concepts such as CSS modules and React inline styles.
Chapter 4, Real-Time Twitter Streaming, introduces a frontend state management container, called Redux. We will also become familiar with Twitter’s Streaming API by building an application that will parse tweets by user and location, perform a simple sentiment analysis, and ingest them into MongoDB.
Chapter 5, Developing Kanban Project Management Tool, outlines the steps for building a Kanban app by implementing the React DnD library; we will also learn how we can enhance our React components using a pattern called Higher-Order Components.
Chapter 6, Building a Real-Time Search Application, explores adding a full-text search on MongoDB collection to our Meteor application. Calling the async functions in Meteor Methods with Fibers and Promises, and adding the native Node.js MongoDB, driver will also be covered.
Chapter 7, Real-Time Maps, covers adding user accounts into our Meteor app, client-side routing, and real-time geo functionality with React-Leaflet components.
Chapter 8, Build a Chatbot with Facebook’s Messenger Platform, gets you started with using Angular 2 for your view layer. We will also add a distributed database, Cassandra, and with GraphQL we will be able to query both the MongoDB and Cassandra databases in a single trip to the server. Using the Wit.ai API, we will build a chatbot prototype that will mock up an online flower store.
Chapter 9, Build Internet of Things Platform, explores another data transport layer, gRPC from Google, by implementing a server-to-server data transport without human intervention.
For this book, you will need a text editor and OS X, Windows, or a Linux box.
If you are a developer who is looking forward to taking your application development skills with Meteor to the next level by getting your hands on different projects, this book is for you.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "All native npm packages' metadata is in thepackage.jsonfile."
A block of code is set as follows:
function Greeting({ hello }) { return <div>{hello}</div>;}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
server
.
addProtoService
(
messages_proto
.
Messages
.
service
, {
sendMessage:
sendMessage
,
clientStream: clientStream
});
Any command-line input or output is written as follows:
>> sudo apt-get update
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Here, we added an inner grid with two full-size columns; one for thePriceof an item and the other will wrap up theQuantitycomponent."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Build-Applications-with-Meteor. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/BuildApplicationswithMeteor_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Meteor is an open source web and mobile development platform, simplifying the process of building applications using only one programming language--JavaScript.
What is included in Meteor?
Server
: As a full-stack platform needs a web server, Meteor runs on top of Node.js, and we get all the benefits of using the Node, such as non-blocking I/O event driven architecture, an enormous amount of open source packages via NPM, plus we don't need to switch the language from the backend to the frontend.
Database(s)
: Meteor comes with MongoDB in a universal way. We get a light copy of MongoDB on the browser called Minimongo. Both the databases are in sync in real-time out of the box, which means that the UI can be updated even before the data reaches the server, and that is one of the most compelling features of the platform.
Communication
: How do the client and server talk to each other? The communication is done via
DDP
(
Distributed Data Protocol
), which is an RPC (
Remote Procedure Call
) protocol built on top of WebSockets instead of HTTP. Due to the bidirectional communication nature of the web sockets, Meteor is a real-time platform by default.
Frontend UI frameworks
: Meteor was using Blaze as its primary template engine, which is Meteor's implementation of Handlebars; however, it also ships with support for Angular and React currently.
Now you must be wondering how all these technologies are glued together. On a very high level, the way Meteor works is that the server publishes channels and the client subscribes to those channels, then all updates from the client can update the server in real time and the other way around--updates on the server can update the client.
Now, let's look at what else is included in Meteor:
There is also a native for Meteor package management, called
Atmosphere
, where you can find tons of useful packages. Note that all Atmosphere packages will be moved to NPM in the future.
ECMAScript 6 or ES6 is the major upgrade of JavaScript language, and you
can code in ES6 in any of your
js
files. There is no need for configuring anything like babel, webpack plugins, dev servers, and task runners.
Any changes on the server or the client create a build automatically for you, and there is no need for browser refresh or manual server restarts.
Throughout the book, we will be using React expect for
Chapter 8
,
Build a Chatbot with Facebook's Messenger Platform
, where we will use Angular 2. With Meteor, there is zero effort to start writing React apps. There is no need for any babel presets or anything else. The support for JSX extension comes with the default
ecmascript
package.
In this chapter, we'll be looking at the following topics:
Downloading and installing Meteor
Installing packages with NPM and Meteor
Overview of React's API
Creating an example application with React and Meteor
Installing and running Meteor is extremely easy.
For Linux and iOS, all you need is the terminal and cURL. cURL is basically a command-line tool that we can use to move data with URL syntax, such as a GET, POST, and more, all directly from the terminal.
For Windows users, Meteor comes with an installer. You can download it from https://www.meteor.com/install">https://www.meteor.com/install. All the commands in the book are executed in a Linux terminal; just skip the sudo command and execute the commands as administrator if you are on Windows.
If you don't have cURL installed, open your terminal and install it with the following commands:
Run
update
as a superuser:
>> sudo apt-get update
Install cURL:
>> sudo apt-get install curl
Verify the installation:
>> curl --version
Once you have cURL installed, installing Meteor is easy as it's a one line command:
>> curl https://install.meteor.com/ | sh
This will download the latest version of Meteor, and it will install it globally on your machine. Node.js, NPM, MongoDB, and all other default packages will be inside the .meteor directory.
The final installation looks like this:
Meteor 1.4.4.2 has been installed in your home directory (~/.meteor).
Writing a launcher script to /usr/local/bin/meteor for your convenience.
This may prompt for your password.
In Chapter 9, Build Internet of Things Platform, we will build Node.js apps connecting to a Meteor app. If you don't have Node.js and MongoDB and you want to run them outside Meteor, here's a list of commands and installing scripts that you might find useful:
Install Node.js with cURL
curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
sudo apt-get install -y nodejs
Uninstall Node.js
sudo rm /usr/local/bin/{node,npm}
Update node with NPM
sudo npm cache clean -f sudo npm install -g n sudo n stable
Update to specific version with NPM
sudo n 4.4.4
Check the version of Node.js
node -v or node --version
Check the version of NPM
npm -v or npm --version
Install cURL and check its version
sudo apt-get update
sudo apt-get install curl
curl --versionc
Uninstall cURL
sudo apt-get remove --auto-remove curl
Purging cURL config data
sudo apt-get purge --auto-remove curl
MongoDB install(Ubuntu)
sudo apt-get update
sudo apt-get install -y mongodb-org
MongoDB version
mongod --version
Stop MongoDB
sudo service mongod stop
Restart MongoDB
sudo service mongod restart
Remove MongoDB
sudo apt-get purge mongodb-org*
Remove Data Directories
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb
The following are the Meteor scripts:
Install Meteor
curl https://install.meteor.com/ | sh
Check the Meteor version
meteor --version
Update Meteor to the latest version
meteor update
Check the Node.js version in Meteor
meteor node -v
Create a Meteor App
meteor create app_name
Add an Atmosphere package to a Meteor app
meteor add package_name
Remove Atmosphere package
meteor remove package_name
List all the Atmosphere packages
meteor list
Install an npm package
meteor npm install package_name --save
List all the npm packages
npm list
Run a Meteor app on a specific port;
the default is 3000
meteor --port 2000
Launch the MongoDB shell in a meteor app
in the app directory execute
meteor mongo
Show all databases from the MongoDB shell
show dbs
Switch to a database
use database_name
Show all collections in a database
show collections
Reset Meteor app
meteor reset
The steps for creating a meteor app are as simple as the installation:
Open your terminal and change your directory to where you want to have your app installed. With the meteor
command line interface
(
CLI
), we can create an app with just one command:
>> meteor create <appname>
You can name it as anything you want; I am naming mine timerapp. We'll go through the steps of creating a basic timer, updating the time from the server side to the client in real time:
>> meteor create timerapp
The meteor create appname command installed all packages and libraries specified in the .meteor folder in the app directory. In Meteor, the packages can be installed from Atmosphere and NPM, and there are two places where you can see what is installed by default.
Atmosphere packages are specified in ./meteor/packages. All native npm packages' metadata is in the package.json file.
Folders: If you go into your app directory, you will note that Meteor created three folders and two files: client, server, .meteor, package.json, and .gitignore:
cd
to that app directory:
>> cd timerapp
To start the server, run the following command:
>> meteor
After some installation logs in the terminal, you'll see something like this:
=> Started proxy.
=> Started MongoDB.
=> Started your app.
=> App running at:
http://localhost:3000/
Open the project in any text editor of your choice.
In my setup, I am using Atom https://atom.io/ with the Facebook package Nuclide https://nuclide.io/. There are other very good editors, such as Sublime Text, Visual Studio Code, WebStorm, Brackets, and many more.
The app skeleton, created by default, is nice and minimal. In the client and server folders, there is a startup JS main.js file. All this comes by default, and you do not need to create additional configs, specify entry points of the application in different environments, dev servers, plugins, and so on.
Besides the flexibility of decoupling your development with reusable components, another powerful feature of React is in its component state. Every React component comes with an internal state.
If the state of a component changes, the render method will fire and re-render the component. One thing that's very different from other frameworks is that React will re-render only the changes and nothing else.
Also, it does so in a very efficient way, and it doesn't have to touch the DOM for searching before making any changes. What is happening in the back is that JSX actually represents the DOM in JavaScript, and all the updates are happening on the script site in memory first; then it will do some checks, then batch the changes and, finally, it will commit them to the DOM.
Facebook and the React community encourage the use of composition over classical inheritance. It can be said that any other pattern to reuse code is considered anti-pattern in React. A lot more can be said about that, but React has been heavily used in production at Facebook without using inheritance for sure. In such a large-scale application, the advantage of building independent pieces and combining them to form a complex functionally is what made React so popular. Components can be moved around, organized by common functionality; they can be well tested and refactored without much of a risk of breaking other parts of the system.
Extending from the React.Component:
class
Greeting
extends
React.Component
{ constructor(props){ // ES6 class constructor super(props) // ES6 } render() { return <h1>Hello, {this.props.name}</h1>; //local }}
Instead of creating a new Greeting instance, we are adding it as a <Greeting/> tag:
ReactDOM.render(<
Greeting
name="Johny"
/>
,document.getElementById('root'))
Some components can be strictly presentational; others may not know who can be their children components in advance. Many namings later came from the community, Smart and Dumb components, Containers and Components, functional and classical.
How React is used it's all up to the developers, the team, and the organization. It's a very powerful and unopinionated library and can be used along with other frameworks.
Starting from the client, let's create our simple app:
Delete all the content of the client folder.
Create the
index.html
file with the following content:
<head> <title>Timer</title></head><body> <div id="root"></div></body>
Meteor will take care of the missing HTML tags. It will compile it as a template rather than serve it as an HTML document.
It will throw an error if you try to add the
<!DOCTYPE html>
and
html>
tags:
While processing files with <cdpcomment data-comment-id="2521" data-comment-text="Sounds incomplete. ">">templating-compiler (for target web.browser): client/index.html:1: Expected one of: <body>, <head>, <template>.
Since we are using only React, we don't need to have the blaze-html-templates package installed.
