Debug typescript in Node JS

demo download

Create REST API with Typescript


mkdir Und-TSC-sec15
cd Und-TSC-sec15

Create Node Project
npm init
You’ll then have a package.json file.


You’ll then have a tsconfig.json file.

In tsconfig.json:

Now let’s install the needed modules:

standard web server independencies:
npm install –save express body-parser

development independencies:
npm install –save-dev nodemon

create src folder:
mkdir src
cd src
touch app.ts

When you are done, type tsc to compile the typescript into javascript.

Then you can debug it. Put a breakpoint there and make sure you’re on the index file. In our file, we’re on app.ts.

Once you’re on that file, go to Run > Start Debugging. You’ll see the bottom status bar turn orange. This means the server is running.

Click on View > Terminal, and you’ll see the terminal pop up. Then click on debug console. You’ll be able to see the console log from the node js app appear.

Creating Routes


cd src/routes
touch todos.ts

We extract Router from express. We can then register routes to hit functionality.
We set up the router to receive POST, GET, PATCH, and DELETE on ‘/’.
Each HTTP request will get mapped to certain functionalities that we declare in controllers/todos file.

routes/todos.ts

Finally, we need to connect our router to our server for endpoint /todos.

app.ts

Add additional routes

First, we create a class Todos so we have a structure to work with. We export a class Todo so other modules can import it, and then new it to create an instance of Todo.

Then import the class so that we get a simple data structure going.

We create functionality by implementing a function createTodo.
Note that we use RequestHandler interface, which contracts us to use
req, res, and next parameters.

controllers/todo.ts

Since it takes care of a POST request, we use parse the body property in the request
object to get the body data. The body data’s key is text.

In order do that we need to import the body-parser package in app.ts, and then extract json.
This is so that we parse the body using json.

app.ts

Open up your postman and query it like so: