Express
Add Express, Cors and Dotenv
yarn add express cors dotenv
yarn add @types/express @types/cors
Create .env.example and .env
code ./.env.example
PORT=4000
cp ./.env.example ./.env
Create routes for articles
mkdir ./src/routes
code ./src/routes/articles.ts
import { Router } from 'express';
import { articlesController } from '../controllers/articles';
export const articlesRoutes = (router: Router) => {
const { findAll, findOne, create, update, remove } = articlesController();
router.get('/articles', findAll);
router.get('/articles/:id', findOne);
router.post('/articles', create);
router.put('/articles/:id', update);
router.delete('/articles/:id', remove);
return router;
};
Create generic controller
mkdir ./src/controllers
code ./src/controllers/records.ts
import { Request, Response } from 'express';
export const recordsController = () => {
const findAll = async (req: Request, res: Response) => {
// return all records
res.send('all records will be returned');
};
const findOne = async (req: Request, res: Response) => {
// return one record by id
};
const create = async (req: Request, res: Response) => {
// create a new record
};
const update = async (req: Request, res: Response) => {
// update a record by a given id
};
const remove = async (req: Request, res: Response) => {
// delete a record by a given id
};
return { findAll, findOne, create, update, remove };
};
Create controler for Articles
code ./src/controllers/articles.ts
import { recordsController } from './records';
export const articlesController = () => {
return recordsController();
}
Initialize Express
code ./src/app.ts
import express from 'express';
import cors from 'cors';
import { articlesRoutes } from './routes/articles';
export const app = async (port: number) => {
// create and setup express app
const app = express();
app.use(express.json());
app.use(cors());
app.set('trust proxy', 1); // required for Heroku
const router = express.Router();
app.use(articlesRoutes(router));
// start express server
app.listen(port);
};
Application root file
code ./src/index.ts
import { config as configDotenv } from 'dotenv';
import { app } from './app';
configDotenv();
const port = parseInt(process.env.PORT);
const run = async () => {
await app(port);
};
run();
Validate Express
yarn dev
curl http://localhost:4000/articles
# all records will be returned
Commit
git add .
git commit -m "Express"