March 9, 2022

Node.js – REST API With TypeScript (Part 3 – POST/PUT/DELETE)

In this part, we would write the functions to POST, PUT and delete a country record from the database.

  1. Make a POST Request
  2. Make an UPDATE
  3. DELETE A Country

 

1. Make a POST Request

The service method:

export const saveCountry = async (country: any) => {
    return await db.one('INSERT INTO Country(capital, code, continent, description, nationality) ' +
        'VALUES ($1, $2, $3, $4, $5)',
        [country.capital, country.code, country.continent, country.description, country.nationality])
}

 

The controller method:

router.post('/countries', (req: Request, res: Response) => {
    console.log(req.body);
    countryService.saveCountry(req.body).then(
        () => {
            res.status(200).json({
                message: "Country was Inserted"
            });
        }
    ).catch((error)=>{
            res.status(303).json({
                message: "Error occured" + error.message
            })
    });
});

 

2. Make an UPDATE (PUT Request)

The update method in the country-service.ts file

export const updateCountry = async (id:number, country: any) => {
    return await db.one('UPDATE Country SET capital = $1, code = $2, continent = $3, description = $4, nationality = $5 ' +
        'WHERE id = $6',
        [country.capital, country.code, country.continent, country.description, country.nationality, id])
}

 

The update method in the country-controller.ts file

router.put('/countries/:id', (req: Request, res: Response) => {
    countryService.updateCountry(parseInt(req.params.id), req.body).then(
        () => {
            res.status(200).json({
                message: "Country was successfully updated!"
            });
        }
    ).catch((error)=>{
        res.status(303).json({
            message: "Error occured" + error.message
        })
    });
});

 

3. DELETE A Country

The service method for delete

export const deleteCountry = async (id:number) => {
    return await db.any('SELECT FROM Country WHERE id = $1', [id])
}

 

The controller method

router.delete('/countries/:id', (req: Request, res: Response) => {
    countryService.deleteCountry(parseInt(req.params.id)).then(
        (country) => {
            res.send(country);
        }).catch((error) => res.send(error.message))
    ;
});

 

At this point, you can run the application. Then use Postman to test the API endpoints.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments