In my previous post I showed how to create an Express server in TypeScript. Let’s now extend things…
To start with, create some folders (the names are not important, in that this is not using convention based folder names). We’re going to set things up in a similar way to I’ve done for C# and Java…
- Add a new folder controllers
- Add a new folder models
Create a file server.ts in the root folder. Here’s the code from the previous post plus some extras
import express from "express";
import bodyParser from "body-parser";
const server = express();
server.use(bodyParser.json());
server.get("/", (request, response) => {
response.send("<h1>Hello World</h1>");
});
const port = 4000;
server.listen(port,
() => console.log(`Server on port ${port}`)
);
The body-parser exposes middleware etc. in this case we’re adding the ability to work with JSON content type.
Now let’s change the existing route / and add some more, below is the additional code required in server.ts
import * as indexController from "./controllers/indexController";
server.get('/', indexController.index);
server.get('/users', indexController.users);
server.get('/users/create', indexController.create);
// POST implementation
// server.post('/users/create', indexController.create);
We now need to implement the model and the controller, so starting with the model, create the file user.ts within the models folder and it should look like this
export default class User {
constructor(public firstName: string, public lastName: string) {
}
}
export const stubData = [
new User('Scooby', 'Doo'),
new User('Fred', 'Jones'),
new User('Velma', 'Dinkley'),
new User('Daphne', 'Blake'),
new User('Shaggy', 'Rogers'),
];
The stubData ofcourse is just here to give us some data to start things off.
In the controllers folder, add a new file named indexController.ts and the file should look like this
import { Request, Response } from "express";
import User, { stubData } from '../models/user';
export const index = (req: Request, res: Response) => {
res.send("<h1>Methods are</h1><ul><li>users</li><li>create</li></ul>")
};
export const users = (req: Request, res: Response) => {
res.json(stubData);
};
export const create = (req: Request, res: Response) => {
const newUser = new User(req.query.firstName, req.query.lastName);
stubData.push(newUser);
res.json(newUser);
};
// POST implementation
// export const create = (req: Request, res: Response) => {
// const newUser = new User(req.body.firstName, req.body.lastName);
// stubData.push(newUser);
// res.json(newUser);
// };
The scripts for package.json should also be taken from the previous post.
If you now run yarn build then yarn start your server will be up and running. Using the following URL’s
- http://localhost:4000/
- http://localhost:4000/users
- http://localhost:4000/users/create?firstName=Miner&lastName=FortyNiner
will result in, the first URL returning a simple help screen using HTML, the second will list the current array of users using JSON and finally the third URL will create a new user, the response will show the new user as JSON, but if you call the users method again you will see the newly added user.
I’ve also listed the POST implementations which you’d probably more likely use for mutations, but the GET implementations are fine in this instance and easier to test via our preferred browser.