Keep Calm - Keep Coding with Cosmos and Node.js

Keep Calm - Keep Coding with Cosmos and Node.js

Keep Calm - Keep Coding with Cosmos and Node.js -Coding with the Cosmos DB SDK feels good. Yes, I said feels good. Yeah, yeah … it is fast to install, fast to learn and fast to execute. But most of all it feels good.

Keep Calm - Keep Coding with Cosmos and Node.js -Coding with the Cosmos DB SDK feels good. Yes, I said feels good. Yeah, yeah … it is fast to install, fast to learn and fast to execute. But most of all it feels good.

Think about when you are coding and everything is just flowing for you. It feels great to be in a rhythm and get everything out of your head and into the code and working fluidly! A key ingredient to this is when the APIs we are coding are intuitive and easy to follow. This is where the Cosmos DB SDK shines brightest. Let’s see why.

I Want to Have Fun with the Code Now

Cosmos DB SDK is awesome, feels great, and if you want to feel great too without reading this and try this all yourself - here are the links to get you started. I may cry if you skip reading this, but I’ll get over it.

Calm, Cool, Collected Coding

When all is well with the coding universe, coding can be therapeutic for many of us. Other times it can be like a dozen screaming children running through our house with paint guns at a birthday party! (hey, don’t judge me)

When we write code we know what we want it to do. For example, recently I wanted a list of heroes from my database - just give them to me without making me work so hard! The line of code that gives them to me with Cosmos DB SDK is simply this:

container.items.readAll().toArray()


There is a container for my heroes, and it has items in it (my heroes). So read them and return them as an array, please. Now that wasn’t so hard!

Cosmos DB with Express Routes

OK, so how does this work in context with a Node and Express route for an HTTP request? Let’s think this through.

We’ll first need to set up the database. We’ll do that in another module, so we can stub that out quickly and import it.

Then we get the heroes. OK, we already have that line of code from above. This code is asynchronous, so we’ll consider using promises or async/await. It’s your call, so choose wisely. Using async/await is what brings me joy, so that’s what we’ll do here. Here is how it will look as I pull the result out and rename it heroes.

const { result: heroes } = await  container
      .items
      .readAll()
      .toArray();


Finally, if it works we need to stuff the heroes in the response with a status code. If it fails, we return a failure status code and message.

Here is the code I wrote for this. Feel free to borrow it (just return it when you’re done, please, so others can borrow it too).

//hero.service.js
const { heroes: container } = require('./config').containers;
async function getHeroes(req, res) {
  try {
    const { result: heroes } = await  container
      .items
      .readAll()
      .toArray();
    res.status(200).json(heroes);
  } catch (error) {
    res.status(500).send(error);
  }
}


That was easy. Like crazy easy! We just wrote database access code and connected it to an express route in a few lines.

OK, there was that one line we stubbed in for the configuration. We’ll need to write that, but the good news here is that the configuration only needs to be done once. The fixed cost is a one-time thing that as many functions as you need can re-use. In other words, we can write functions to get, put, post, delete heroes, villains, and whatever we want and only need that single line up top to configure it!

Isolating the Configuration

Here is a module you can use to help get started. I like to isolate the functionality that sets up my coding environment to connect to the database in one Node module. Here we have one that we could call config.js or giraffe.js. I think the former makes more sense, but you do you.

The comments explain what is happening in here, but let’s review anyway. First, we reference the Cosmos module from the @azure/cosmos npm package. Then we set up the keys, URL, and database name. This consolidates all of our configurations in one place. Finally, we instantiate the Cosmos client object and expose the container objects. These container objects are what we’ll import in other modules, so we can just ask for the container and it just works. Yes, it’s that simple.

// config.js
// Get the npm module for Azure's Cosmos
const cosmos = require('@azure/cosmos');
// Identify your database keys and name
const endpoint = process.env.CORE_API_URL;
const masterKey = process.env.CORE_API_KEY;
const dbDefName = 'vikings-db';
// Instantiate the Cosmos client object,
// which is the focal point of interacting with Cosmos
const { CosmosClient } = cosmos;
const client = new CosmosClient({ endpoint, auth: { masterKey } });
// Make it easy to acces the containers
const containers = {
  heroes: client.database(dbDefName).container('heroes'),
  villains: client.database(ddDefName).container('villains')
};
module.exports = { containers };


Try It

You can try this out yourself in your own app, or by cloning my repository here, or by running through a quick start in the documentation.

Originally published by John Papa at https://dev.to

=======================================

Follow me on Facebook | Twitter

Learn More

☞ The Complete Node.js Developer Course (3rd Edition)

☞ Angular & NodeJS - The MEAN Stack Guide

☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

☞ Docker for Node.js Projects From a Docker Captain

☞ Intro To MySQL With Node.js - Learn To Use MySQL with Node!

☞ Node.js Absolute Beginners Guide - Learn Node From Scratch

☞ React Node FullStack - Social Network from Scratch to Deploy

☞ Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

☞ Complete Next.js with React & Node - Beautiful Portfolio App

☞ Build a Blockchain & Cryptocurrency | Full-Stack Edition

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Difference between AngularJS, React, Ember, Backbone, and Node.js.

The most common thing between all of them is that they are Single Page Apps. The SPA is a single page where much of the information remains the same and only some piece of data gets modified when you click on other categories/option.

Node.js Tutorial for Beginners | Node.js Crash Course | Node.js Certification Training

This courseis designed for professionals who aspire to be application developers and gain expertise in building real-time, highly-scalable applications in Node.js. The following professionals can go for this course :

Why learn Node.js?

Node.js uses JavaScript - a language known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Using Node.js you can build simple Command Line programs or complex enterprise level web applications with equal ease. Node.js is an event-driven, server-side, asynchronous development platform with lightning speed execution. Node.js helps you to code the most complex functionalities in just a few lines of code...

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Docker for Node.js Projects From a Docker Captain

Intro To MySQL With Node.js - Learn To Use MySQL with Node!

Node.js Absolute Beginners Guide - Learn Node From Scratch

React Node FullStack - Social Network from Scratch to Deploy

Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

Complete Next.js with React & Node - Beautiful Portfolio App

Build a Blockchain & Cryptocurrency | Full-Stack Edition