How to create the Node.js API with TypeScript and GraphQL

How to create the Node.js API with TypeScript and GraphQL

In this tutorial, I will teach you how to create a GraphQL API and use Node.js and TypeScript to apply authentication and real-time responses using subscriptions.

GraphQL is a strongly typed query language, and Typescript is a typed superset of JavaScript - together they are a match made in heaven!

Prerequisites
  • Basic knowledge of TypeScript and Node.js
  • You should be able to work with Git
Why GraphQL

GraphQL is a query language for our API. It makes developing complex APIs a breeze by being strongly typed, which allows us to easily generate mocks for tests, documentation and automated optimizations.

GraphQL also allows us to optimize latency and response sizes as we can selectively query data or batch requests very easily. It also allows us to validate the input in several easy ways.

Approaching types

Unfortunately, syncing the types of both GraphQL and TypeScript is not so straight forward, and here are two ways in which we can achieve this:

  • Generating GraphQL from TypeScript using annotations. type-graphql is a library that does just that, but this can pose a problem when you also want to use the types on the front-end.

  • Generating TypeScript from a GraphQL schema. There are a lot of tools for generating types out of the schema such as graphql-schema-typescript.

Before we start

In this tutorial, we will build a simple message board app, and add some basic authentication to it. There will be no database here — we will simply use lowdb to create a database out of a JSON file.

We are going to use a pretty large array of technologies here. Here are some of them:

  • Apollo - Provides us with a server implementation for GraphQL, creates a playground where we can play with our queries and gives us different tools. Apollo can be either a standalone server or combined with Express. We will use the later.

  • graphql-schema-typescript & graphql cli - These two tools will allow us to convert our GraphQL API into TypeScript. They can do more, but that's mostly what we will use them for.

  • graphql-tag - Allows us to embed chunks of GraphQL code inside our TypeScript files. It makes it easier to separate our schemas into multiple smaller chunks.

We will also use uuid to generates id's, bcrypt to hash passwords and JWT to generate tokens, but you can ignore these parts as we will not discuss them in this article.

The basics of GraphQL

I think the easiest way to explain how GraphQL schemas work will be to simply check an example.

We will use 3 root types for our schemas:

type Query {
  getPuppies: [Puppy]
}

type Mutation {
  createPuppy(input: InputPuppy!): Puppy
}

type Subscription {
  onPuppy: String
}

Let's take a look at what we have here:

  • Query - defines all of our queries. As you can see we have a query called getPuppies, and it returns an array of puppies. This is the array notation in GraphQL: [Int] [String] [Cat]...

  • Mutation - defines all of our possible mutations. You can think of it as PUT/POST in terms of REST. As you can see we have a mutation named createPuppy which accepts a Puppy by the name of input. The ! sign after the Puppy means it is required, and it returns a single puppy.

  • Subscription - defines all of the events our server can emit to the client. We can use web-sockets to subscribe to the onPuppy subscription and get a String every time a new puppy is born.

Simple GraphQL queries make use of POST request as follows:

query {
  getPuppies{
    name
    id
  }
  getKittens{
    name
    age
  }
}

This is a good example since it shows how we can batch queries. We will have data from 2 queries, returned in a single HTTP request.

To do such a thing with a REST API we would have to do two requests, one to GET /api/puppies and another to GET /api/kittens. That way the response is simpler, faster, the server needs to handle fewer requests and we have less network overhead for both the clients and the server.

Let's say a puppy also has color,eyeColor and owner - thanks to GraphQL we don't have to get those parameters, we can simply query what we need.

We will use some of the types GraphQL provides:

  • type - you can think of type values as objects. We have seen them before and we can also define custom Objects.

  • scalarType - the base scalar Types are Int, Float, Boolean, String and ID which can be either a string or a number, but it's always parsed as a string.

  • input - input are types that can be accepted as input for queries, the base scalarTypes are also accepted as input for functions.

  • enum - an enum of strings

We can define types like this:

" we can define descriptions too "
    # or comments
    input GetBookInput {
        id: ID!
    }

    " we can also define required on types using !"
    type Book {
        id: ID!
        title: String
        writerID: ID!
        country: CountryEnum
    }


    """
    multiline descriptions
    are also possible
    """
    enum CountryEnum {
      UNITED_STATES
      JAPAN
      CHINA
    }

GraphQL has a lot of other types, and you can read more about them in the official docs. You may want to learn more about GraphQL, and there's a lot to learn about it, and if that's the case you should visit the GraphQL website.

Planning our application

Through this tutorial we will make an API that will provide basic functionality for a real-time message board. You will be able to create a user, get a user, get a user's public data, post messages, get messages, and listen to new messages.

In terms of REST API it might look something like this:

  • POST /user/login (login)
  • POST /user/register (create)
  • GET /user (get publicly available user data)
  • POST /post (post a new post, a user must be logged in for this)
  • GET /post/all (get all the posts)

And a separate logic for web-sockets.

Each post has a userId which allows us to join and know which user posted it.

Other than that, when a user logs in or registers they will get a JWT token which will be used for authentication.

In GraphQL, however, there are no POST/GET/PUT methods. We will replace them with Mutation and Query which use POST for the HTTP request, and Subscription which uses web-sockets under the hood.

Setting Up

You should clone the git repository and we will go over the main parts of the code.

Unfortunately, it's beyond the scope of the tutorial to get into the Typescript/Webpack configurations in this tutorial, but they are pretty simple and straightforward.

We can also completely ignore the database implementation. You shouldn't care about it as it's only there to provide mock data.

We are going to base our app partially off of this article by the Apollo team which gives a simple method to modularize our GreaphQL schemas.

After cloning you should have this directory structure:

Other than that we have some configuration files:

.graphqlconfig This file is used by graphql-cli. It was created with the init command.

webpack.config.js, tsconfig.json, tslint.json Standard files to configure our build. I used webpack since it provides us with HMR so development is much faster than with typescript only.

db.json This file holds our database.

You can run the server like so:

# run the server in development mode
npm run dev

You should be able to see the playground at http://localhost:3000/, for now you can ignore it as we will play with the queries at the end of this tutorial.

It should look like this:

Our server

We will start from the file src/index.ts — this is where our server initialization is happening:

import { ApolloServer, Config } from 'apollo-server';
import { makeExecutableSchema } from 'graphql-tools';
import { handleGraphQLContext, handleGraphQLSubscriptionContext } from 'src/auth/index';
import { rawSchema } from './graphql';

const port = process.env.PORT || 3000;

// create our schema
const schema = makeExecutableSchema(rawSchema);

// configure the server here
const serverConfig: Config = {
  schema,
  context: handleGraphQLContext,
  subscriptions: {
    onConnect: handleGraphQLSubscriptionContext,
  },
  playground: {
    settings: {
      'editor.theme': 'dark', // change to light if you prefer
      'editor.cursorShape': 'line', // possible values: 'line', 'block', 'underline'
    },
  },
};

// create a new server
const server = new ApolloServer(serverConfig);
server.listen(port).then(({ url }) => {
  console.log(`🚀  Server ready at ${url}`);
});

You can see that we are doing 3 interesting things:

  1. We create a schema with makeExecutableSchema. We will cover the rawSchema variable later, but this executable schema is the optimized version of our GraphQL schema with the resolvers, it matches GraphQL endpoints to functions that return the responses.

  2. We create the configuration for our server, we pass the schema that matches requests to resolvers, a context which is a function that will authenticate the users, and pass the users as a variable to the resolvers.

  3. We create our server with Apollo.

And that's it. With this we have web-socket support, GraphQL support, auto-generated documentation and a playground to test queries.

Our first schema

In the file src/graphql/index.ts you can see the root schema:

import { mergeRawSchemas } from './utils/mergeRawSchemas';
import { gql } from 'apollo-server';
import schemaShards from './schemaShards';

export const rawSchema = mergeRawSchemas(
  {
    typeDefs: [
      // we create empty main types, we can later extend them in the shards
      gql`
                 type Query {
                    _empty: String
                }

                type Mutation {
                    _empty: String
                }

                type Subscription {
                    _empty: String
                }
            `,
    ],
    resolvers: {},
  },
  schemaShards,
);

We see some new things here too:

gql - a tag used for creating our schema. It should provide syntax highlighting and auto-complete in your IDE of choice.

Each type has a "_empty" field. This is used so we can later extend those types, allowing us to completely modularize our application into different files.

mergeRawSchemas is a utility function written with lodash. It merges the arrays that contain typeDefs and the objects that contain the resolvers.

Now we can look at the users schema, in src/graphql/schemaShards/user, I'm separating the code snippets to allow syntax highlight.

Our schema:

extend type Query {
    " login as a user "
    loginUser(input: InputLogin!): User
    " get a user's public data"
    getUser(id: ID!): PublicUser
}

extend type Mutation {
    " register a new user "
    registerUser(input: InputRegisterUser!): User
}

" used for logging in "
input InputLogin {
    email: String!
    password: String!
}

" used for creating a new user "
input InputRegisterUser {
    name: String!
    email: String!
    password: String!
}

" a type defining a user's public data "
type PublicUser {
    id: ID
    name: String
    email: String
}

" a type defining a user  "
type User {
    id: ID
    name: String
    email: String
    token: String
}

And our code:

import { getPublicUser, getUserByPasswordAndEmail, registerUser } from 'src/db';
import { gql } from 'apollo-server';

const typeDefs = gql`..typedefs..`;

export default {
  resolvers: {
    Query: {
      // login
      loginUser: (root, { input }: GQL.QueryToLoginUserArgs) => getUserByPasswordAndEmail(input),
      // get a user
      getUser: (root, { id }:  GQL.QueryToGetUserArgs) => getPublicUser(id),
    },
    Mutation: {
      // register
      registerUser:  (root, { input }: GQL.MutationToRegisterUserArgs) => registerUser(input),
    },
  },
  typeDefs: [typeDefs],
};

As you can see, for each root type I have created a matching resolver, and each resolver is a function that gets some parameters. It usually looks like this:

fieldName(root, args, context, info) { result }

Where root is used to do type resolution, we will talk about more about it later in this post.

args are the arguments we pass. context is an object that we will handle later when we talk about authentication.

info is a pretty advanced variable. It contains information about the execution. In most cases we don't need to use it.

And a result can be either a value or a promise that returns the value. The value must match the return value defined in the schema.

Generating types

The types you see such as GQL.QueryToLoginUserArgs are auto generated. Here is how we can generate them.

# download the schema with graphql-cli
graphql get-schema

You will have the schema downloaded and saved in** src/_typedefs/schema.graphql** (it's defined in .graphqlconfig). I only use it to generate types, but this schema could have different usages.

Now we can generate the types from the schema:

# generate types with graphql-schema-typescript

graphql-schema-typescript --namespace=GQL --global=true --typePrefix='' generate-ts --output=src/__typedefs/graphqlTypes.d.ts src/__typedefs

And with that we are done. We should have a new file named graphqlTypes.d.ts and the types will be available globally under the GQL namespace.

For simplicity it's all defined in package.json, so generating types is easy -- just call npm run generate-typedefs.

Authentication

As I mentioned before, I created a function called handleGraphQLContext. We can take a look at it in src/auth/index.ts:

import { getUserByToken } from 'src/db';
import { Request, Response } from 'express';

// our context interface
export interface IContext {
  token?: string;
}

// handle all of the context magic here
function createContext(token: string): Promise<IContext> | IContext {
  return {
    token,
  };
}

// create context for requests
export function handleGraphQLContext(ctx: {connection?: any, req?: Request, res?: Response}) {
  const { req, connection } = ctx;
  // we already connected with a subscription
  if (connection) {
    return connection.context;
  }
  // check the request for the token
  const token = req.headers && req.headers.token;
  return createContext(token as string);
}

// handle authentication for socket connections
export function handleGraphQLSubscriptionContext(
    connectionParams: {token: string},
    webSocket: WebSocket,
) {
  const token = connectionParams.token;
  return createContext(token);
}

// check if the user is logged in or whatever you want to do to authenticate the user
export async function authenticateContext(context: IContext): Promise<GQL.User> {
  if (!context.token) {
    // too bad 👎
    throw new Error('user is not logged in');
  }
  const user = await getUserByToken(context.token);
  if (!user) {
    // too bad 👎
    throw new Error('invalid token');
  }
  // yay 👍
  return user;
}

Depending on whether the request is a subscription or a query/mutation, we will have to handle it differently. Either way we want to generate the same context, so we handle it with one of the functions handleGraphQLSubscriptionContext or handleGraphQLContext. Those functions extract the token and call createContext.

Our main authentication logic should happen in either createContext or in authenticateContext.

Unfortunately, there is no easy way to do authentication with OAuth or other complicated mechanisms in Apollo, but you can create your own Express app and let apollo-server become a middleware in it. This is easier and pretty straightforward to do.

const app = express();
app.use('/auth', authRoutes);
apolloServer.applyMiddleware({app, path: '/graphql'});
app.listen(3000);
Subscriptions

Now that we can create and get a user, and we can authenticate them, let's create an API to post, get and listen to new messages.

We need to start by looking at** src/graphql/subscriptionManager.ts**:

import { PubSub } from 'graphql-subscriptions';

// In a production server you might want to have some message broker or pubsub implementation like
// rabbitMQ, redis or kafka logic here
// you can use one of the graphql subscription implementations to do it easily
//
// Redis: https://github.com/davidyaha/graphql-redis-subscriptions
// Kafka: https://github.com/ancashoria/graphql-kafka-subscriptions
// Rabbitmq: https://github.com/cdmbase/graphql-rabbitmq-subscriptions

export const pubsub = new PubSub();

This is the file where you could handle all of the pubsub tools like kafka/reds/rabbitmq. The comments have leads for libraries to help you with that kind of task.

But we are going to use a local pubsub since we are not doing a microservices architecture here.

graphql-subscriptions have lots of other useful tools for managing subscriptions, but we will keep it simple for this tutorial.

Next we will see how to implement a simple subscription:

Let's take a look at src/graphql/schemaShards/posts.ts. We will first look at the GraphQL schema there:

extend type Query {
    " get all posts "
    getPosts: [Post]
}

extend type Mutation {
    " create a new post "
    createPost(input: InputCreatePost!): Post
}

extend type Subscription {
    " called when a new post is created "
    postCreated: Post
}

" input to create a new post "
input InputCreatePost {
    text: String
    userId: ID
}

type Post {
    id: ID
    userId: ID
    text: String
    user: PublicUser
    timestamp: String
}

As you can see this schema is pretty much the same. We only added a Subscription type, and it has an event named postCreated that returns an object of type Post.

It means that the client can subscribe to this postCreated event and get the new post.

Now we have a pretty simple resolver for our subscription:

Subscription: {
      postCreated: {
        subscribe: (root, args, context) => {
          return pubsub.asyncIterator('postCreated');
        },
      },
    },

But in order for this subscription to do anything, we need to publish to it. We can examine the createPost mutation for that:

Mutation: {
      // create a post
      createPost:  async (root, { input }: GQL.MutationToCreatePostArgs, context) => {
        // get the user from the context
        const user = await authenticateContext(context);
        // create a new post in the database
        const post = await createPost(input, user.id);
        // publish the post to the subscribers
        pubsub.publish('postCreated', {
          postCreated: post,
        });
        return post;
      },
    }

We used the authenticateContext function to get the user from its context. If no user exists, we can just let it throw an error and let Apollo catch it.

For the subscription, we use pubsub.publish. We pass the name of the subscription, and we need to pass an object that has a key with the name of the subscription, and a value of whatever we want the subscription to send.

Type resolvers

Type resolvers are an easy way to emulate an SQL "join" like you may do for the database. GraphQL is designed in a way that enables it to work well with microservices. Let's pretend we keep the posts in one microservice and the users in another.

You can see that our Post has 2 variables that are useful for us: user and userId.

Post: {
  user: (post: Partial<GQL.Post>) => getPublicUser(post.userId),
},

Instead of a generic root argument we now have a post argument. This is because we now have a type resolver with an actual type. We have a Partial since it is not the full Post object, and we just need to return the user, or a promise for a user.

Playing in the playground

Now we are pretty much done with building our little server. We have good type definitions and are now able to modularize our app. Adding and editing resolvers and our schemas is a breeze.

But what does all of this allow us to do? Let's take a look at how to work with the playground and how to read the documentation that we created without even knowing.

After you open the playground you can create a new user. The new user requires us to pass in a name, email and a password in order to create it. We can find out how to do it by looking at the documentation.

Click the green button on the right side of the playground (it says SCHEMA).

Click the query you want to use (registerUser in this case).

Click on the arguments or variables (input) in this case.

And you will get more information about the query, what variables it can return, what arguments it accepts, and we can easily write documentation about what each variable does.

Let's create a user now. This is how we pass variables to the playground and you should also have the autocomplete option.

Click the play button to make the query.

To understand exactly what the playground sends to the server we can check out the network using the debugger. This is what the request looks like:

As you can see, we sent a simple POST request with some variables, a query and an operation name. The operation name can be useful for debugging, but it can have any name you want.

Now to see how our subscription works, we can call it with a simple query and with no variables. As you can see I chose not to return the userId as we don't need it.

subscription{
  postCreated{
    text
    user{
      name
    }
  }
}

Press the play button, and open another tab. In the other tab we can create a new Post. You need to copy the token from the database and pass it as a header:

Query

mutation createPost($input: InputCreatePost!){
  createPost(input:$input){
    id
    text
    user{
      name
    }
  }
}

Headers (goes into the HTTP HEADERS tab)

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImNjZjQxMDdmLThjOGMtNDBhNy04NzE5LThkZjNjNjI5NDcwNiIsImlhdCI6MTU0OTIxODkwNn0.E8tTQxmzrkHpksgXq0egP4JDjz6N-Lr31PegRc9BJIQ"
}

Variables

{
  "input": {
    "text": "hello world"
  }
}

Now the server should have sent data to the subscription, and it should be updated.

Summary

I hope that this tutorial showed you how easy it is to create a GraphQL server with Apollo, and that synchronizing your TypeScript and schema is not that difficult either.

We can gain so much from using GraphQL in terms of performance, documentation and stability.

Thanks for reading !
Originally published by Liron Navon at hashnode.com

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

How to Use Express.js, Node.js and MongoDB.js

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Creating a Node Application

To get started I would recommend creating a new database that will contain our application. For this demo I am creating a directory called node-demo. After creating the directory you will need to change into that directory.

mkdir node-demo
cd node-demo

Once we are in the directory we will need to create an application and we can do this by running the command
npm init

This will ask you a series of questions. Here are the answers I gave to the prompts.

The first step is to create a file that will contain our code for our Node.js server.

touch app.js

In our app.js we are going to add the following code to build a very simple Node.js Application.

var express = require("express");
var app = express();
var port = 3000;
 
app.get("/", (req, res) => {
&nbsp;&nbsp;res.send("Hello World");
});
 
app.listen(port, () => {
  console.log("Server listening on port " + port);
});

What the code does is require the express.js application. It then creates app by calling express. We define our port to be 3000.

The app.use line will listen to requests from the browser and will return the text “Hello World” back to the browser.

The last line actually starts the server and tells it to listen on port 3000.

Installing Express

Our app.js required the Express.js module. We need to install express in order for this to work properly. Go to your terminal and enter this command.

npm install express --save

This command will install the express module into our package.json. The module is installed as a dependency in our package.json as shown below.

To test our application you can go to the terminal and enter the command

node app.js

Open up a browser and navigate to the url http://localhost:3000

You will see the following in your browser

Creating Website to Save Data to MongoDB Database

Instead of showing the text “Hello World” when people view your application, what we want to do is to show a place for user to save data to the database.

We are going to allow users to enter a first name and a last name that we will be saving in the database.

To do this we will need to create a basic HTML file. In your terminal enter the following command to create an index.html file.

touch index.html

In our index.html file we will be creating an input filed where users can input data that they want to have stored in the database. We will also need a button for users to click on that will add the data to the database.

Here is what our index.html file looks like.

<!DOCTYPE html>
<html>
  <head>
    <title>Intro to Node and MongoDB<title>
  <head>

  <body>
    <h1>Into to Node and MongoDB<&#47;h1>
    <form method="post" action="/addname">
      <label>Enter Your Name<&#47;label><br>
      <input type="text" name="firstName" placeholder="Enter first name..." required>
      <input type="text" name="lastName" placeholder="Enter last name..." required>
      <input type="submit" value="Add Name">
    </form>
  <body>
<html>

If you are familiar with HTML, you will not find anything unusual in our code for our index.html file. We are creating a form where users can input their first name and last name and then click an “Add Name” button.

The form will do a post call to the /addname endpoint. We will be talking about endpoints and post later in this tutorial.

Displaying our Website to Users

We were previously displaying the text “Hello World” to users when they visited our website. Now we want to display our html file that we created. To do this we will need to change the app.use line our our app.js file.

We will be using the sendFile command to show the index.html file. We will need to tell the server exactly where to find the index.html file. We can do that by using a node global call __dirname. The __dirname will provide the current directly where the command was run. We will then append the path to our index.html file.

The app.use lines will need to be changed to
app.use("/", (req, res) => {   res.sendFile(__dirname + "/index.html"); });

Once you have saved your app.js file, we can test it by going to terminal and running node app.js

Open your browser and navigate to “http://localhost:3000”. You will see the following

Connecting to the Database

Now we need to add our database to the application. We will be connecting to a MongoDB database. I am assuming that you already have MongoDB installed and running on your computer.

To connect to the MongoDB database we are going to use a module called Mongoose. We will need to install mongoose module just like we did with express. Go to your terminal and enter the following command.
npm install mongoose --save

This will install the mongoose model and add it as a dependency in our package.json.

Connecting to the Database

Now that we have the mongoose module installed, we need to connect to the database in our app.js file. MongoDB, by default, runs on port 27017. You connect to the database by telling it the location of the database and the name of the database.

In our app.js file after the line for the port and before the app.use line, enter the following two lines to get access to mongoose and to connect to the database. For the database, I am going to use “node-demo”.

var mongoose = require("mongoose"); mongoose.Promise = global.Promise; mongoose.connect("mongodb://localhost:27017/node-demo");

Creating a Database Schema

Once the user enters data in the input field and clicks the add button, we want the contents of the input field to be stored in the database. In order to know the format of the data in the database, we need to have a Schema.

For this tutorial, we will need a very simple Schema that has only two fields. I am going to call the field firstName and lastName. The data stored in both fields will be a String.

After connecting to the database in our app.js we need to define our Schema. Here are the lines you need to add to the app.js.
var nameSchema = new mongoose.Schema({   firstName: String,   lastNameName: String });

Once we have built our Schema, we need to create a model from it. I am going to call my model “DataInput”. Here is the line you will add next to create our mode.
var User = mongoose.model("User", nameSchema);

Creating RESTful API

Now that we have a connection to our database, we need to create the mechanism by which data will be added to the database. This is done through our REST API. We will need to create an endpoint that will be used to send data to our server. Once the server receives this data then it will store the data in the database.

An endpoint is a route that our server will be listening to to get data from the browser. We already have one route that we have created already in the application and that is the route that is listening at the endpoint “/” which is the homepage of our application.

HTTP Verbs in a REST API

The communication between the client(the browser) and the server is done through an HTTP verb. The most common HTTP verbs are
GET, PUT, POST, and DELETE.

The following table explains what each HTTP verb does.

HTTP Verb Operation
GET Read
POST Create
PUT Update
DELETE Delete

As you can see from these verbs, they form the basis of CRUD operations that I talked about previously.

Building a CRUD endpoint

If you remember, the form in our index.html file used a post method to call this endpoint. We will now create this endpoint.

In our previous endpoint we used a “GET” http verb to display the index.html file. We are going to do something very similar but instead of using “GET”, we are going to use “POST”. To get started this is what the framework of our endpoint will look like.

app.post("/addname", (req, res) => {
 
});
Express Middleware

To fill out the contents of our endpoint, we want to store the firstName and lastName entered by the user into the database. The values for firstName and lastName are in the body of the request that we send to the server. We want to capture that data, convert it to JSON and store it into the database.

Express.js version 4 removed all middleware. To parse the data in the body we will need to add middleware into our application to provide this functionality. We will be using the body-parser module. We need to install it, so in your terminal window enter the following command.

npm install body-parser --save

Once it is installed, we will need to require this module and configure it. The configuration will allow us to pass the data for firstName and lastName in the body to the server. It can also convert that data into JSON format. This will be handy because we can take this formatted data and save it directly into our database.

To add the body-parser middleware to our application and configure it, we can add the following lines directly after the line that sets our port.

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Saving data to database

Mongoose provides a save function that will take a JSON object and store it in the database. Our body-parser middleware, will convert the user’s input into the JSON format for us.

To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user’s input. Once we have it then we just need to enter the command “save”.

Mongoose will return a promise on a save to the database. A promise is what is returned when the save to the database completes. This save will either finish successfully or it will fail. A promise provides two methods that will handle both of these scenarios.

If this save to the database was successful it will return to the .then segment of the promise. In this case we want to send text back the user to let them know the data was saved to the database.

If it fails it will return to the .catch segment of the promise. In this case, we want to send text back to the user telling them the data was not saved to the database. It is best practice to also change the statusCode that is returned from the default 200 to a 400. A 400 statusCode signifies that the operation failed.

Now putting all of this together here is what our final endpoint will look like.

app.post("/addname", (req, res) => {
  var myData = new User(req.body);
  myData.save()
    .then(item => {
      res.send("item saved to database");
    })
    .catch(err => {
      res.status(400).send("unable to save to database");
    });
});
Testing our code

Save your code. Go to your terminal and enter the command node app.js to start our server. Open up your browser and navigate to the URL “http://localhost:3000”. You will see our index.html file displayed to you.

Make sure you have mongo running.

Enter your first name and last name in the input fields and then click the “Add Name” button. You should get back text that says the name has been saved to the database like below.

Access to Code

The final version of the code is available in my Github repo. To access the code click here. Thank you for reading !

Deno vs Node.js: Deno Will Replace Node.JS?

Deno vs Node.js: Deno Will Replace Node.JS?

Deno vs Node.js: Deno Will Replace Node.JS? What’s Deno, and how is it different from Node.js? Node.js is Dead – Long live Deno! The goal of Deno is not to replace Node.js, but to offer an alternative.

A decade after Node.js was first announced, JavaScript and the web platform have evolved, and TypeScript has changed the way JS applications are developed. Deno is a new JavaScript/TypeScript runtime that was designed with all those new capabilities in mind.