» Node.js: Building Full-Text Search API with ElasticSearch » 2. Index Documents » 2.1 Express Server

Express Server

Create your project folder named lr_fulltext_search_node.

Create a package

Run the npm init command to create a package.json file for your application.

npm init

This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them except the entry point.

We prefer to use main.js rather than index.js.

Its result should be similar to this:

package name: (lr_fulltext_search_node) 
version: (1.0.0) 
description: Example project: building full-text search API in Node.js.
entry point: (index.js) main.js
test command: 
git repository: 
keywords: literank,full-text,search
author: literank.com
license: (ISC) MIT

{
  "name": "lr_fulltext_search_node",
  "version": "1.0.0",
  "description": "Example project: building full-text search API in Node.js.",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "literank",
    "full-text",
    "search"
  ],
  "author": "literank.com",
  "license": "MIT"
}

This command creates a package.json file in which dependencies you add will be listed for tracking.

Install Express

npm install express

This command updates the package.json file and creates a package-lock.json file in your project.

Create main.js:

const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.json({ status: "ok" });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Run the program like this:

node main.js

You will get a line like below:

Server is running on port 3000

Your server is runnong on port 3000 now.

Try visiting the URL http://localhost:3000/ in your browser or curl. It should display the json:

{
  "status": "ok"
}

Use TypeScript

Using TypeScript in a Node.js project offers several benefits:

  1. Static Typing: TypeScript allows you to define types for variables, parameters, and return values. This helps catch type-related errors during development rather than at runtime, leading to more robust and predictable code.
  2. Improved Code Readability: With type annotations, code becomes more self-documenting, making it easier for developers to understand the codebase and collaborate effectively. Type information serves as additional documentation, especially for large projects.
  3. Enhanced IDE Support: TypeScript provides better tooling support in IDEs like Visual Studio Code, offering features such as code navigation, auto-completion, and inline documentation, which can improve productivity and code quality.

So, let's transform it.

Run the following command to install typescript dependencies:

npm install typescript ts-node @types/node @types/express --save-dev

The --save-dev flag ensures that these dependencies are saved as devDependencies, as they are only required during the development process.

Create tsconfig.json in your root directory:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "CommonJS",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

Move main.js to src/main.ts, and add types.

import express, { Request, Response } from "express";

const app = express();
const port = 3000;

app.get("/", (req: Request, res: Response) => {
  res.json({ status: "ok" });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Changes in package.json:

@@ -4,7 +4,8 @@
   "description": "Example project: building full-text search API in Node.js.",
   "main": "main.js",
   "scripts": {
-    "test": "echo \"Error: no test specified\" && exit 1"
+    "dev": "ts-node src/main.ts",
+    "build": "tsc"
   },
   "keywords": [
     "literank",
@@ -15,5 +16,11 @@
   "license": "MIT",
   "dependencies": {
     "express": "^4.19.2"
+  },
+  "devDependencies": {
+    "@types/express": "^4.17.21",
+    "@types/node": "^20.12.7",
+    "ts-node": "^10.9.2",
+    "typescript": "^5.4.5"
   }
 }

Run the new program like this:

npm run dev

Now, try to visit the URL http://localhost:3000/ again.

If the result looks good, that means your TypeScript version server is doing well.

Data model: Book

Data models represent the structure of the data that the API deals with.

Create src/domain/model/book.ts:

Folder structures like domain/model/... is using 4 Layers Architecture Pattern, read more here.

export interface Book {
  title: string;
  author: string;
  published_at: string;
  content: string;
}

Create src/domain/model/index.ts:

export { Book } from "./book";