In this TypeScript starter tutorial we’ll setup a node api that stores and retrieve his data from a mangoDB backend.
For the lazy ones, the full code can be found on my github repo under:
1) Install the prerequisites
First you need NodeJs. If you haven’t already TypeScript installed:
$npm install -g typescript
To Install MongoDB on your dev box, follow the instructions on: https://docs.mongodb.com/manual/installation/
You can query and configure mongoDb through the command line but I prefer to use Robomango.
2) Create and configure the Node project
A) Create a new node project from the command line:
$ mkdir mango-node$ cd mango-node$ npm init
You can just accept all the proposed values by hitting enter. npm will create a new package.json file.
B) Download the npm packages
We’ll use 3 npm packages inside our app:
- Mongoose, it’s a sort of driver for MongoDB and it provides a schema-based way to model your solution.
- express: the most used web framework for node
- body-parser: let us pull POST content from our HTTP request.
Install the npm packages:
$ npm install mongoose —save$ npm install express —save$ npm install body-parser —save
C) Install the TypeScript definitions
To enable manage and install TypeScript definitions we’ll use Typings. Therefore you need typings to be installed as a global package:
$ sudo npm install -g typings
To install the typings packages:
$ typings install mongoose$ typings install dt~express –save —-global$ typings install dt~body-parser –save —-global$ typings install dt~node –save —global$ typings install mime —save$ typings install dt~express-serve-static-core –save —global$ typings install dt~serve-static –save –global
D) Add a TypeScript configuration file tsconfig.json:
3) Implement the server
A) Create a index.ts file:
B) Test that you can compile and start your server:
$ node index.js
To combine these steps in one command you can use the “scripts” section of your package.json file:
4) Define the entity and his mongoose schema
We need to define a User entity and his mongoose schema. Create a user.ts file:
5) Implement the REST API
Finally we implement our api logic.
A) Open the index.ts file and import our user entity:
import * as User from “./User”
B) Setup the http endpoints
Just after the setup of the bodyParser middleware, configuration the app to handle the http verbs, get and post:
6) Test the app.
A) download Postman , it’s a tool to help you test and document your api’s.
C) Launch Postman and configure a post request with Postman.
Then configure provide the body of your request:
Push send, you should get something like this in the response body:
That’s all, now you can populate as many users you want and try to retrieve all or a specific one.