crud application for cars in typescript

To create a CRUD application for cars in TypeScript, we can start by setting up the required dependencies and creating the server:

# create a new Node.js project
npm init

# install required dependencies
npm install express mongoose body-parser

# install TypeScript and required TypeScript types
npm install typescript @types/node @types/express @types/mongoose @types/body-parser
251 chars
9 lines

Once the dependencies are installed, create a new file server.ts:

index.ts
import bodyParser from 'body-parser';
import express from 'express';
import mongoose from 'mongoose';

// create express app
const app = express();

// connect to MongoDB database
mongoose.connect('mongodb://localhost:27017/car_database', { useNewUrlParser: true, useUnifiedTopology: true });

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// parse requests of content-type - application/json
app.use(bodyParser.json());

// define a simple route
app.get('/', (req, res) => {
    res.json({ message: 'Welcome to Car API!' });
});

// listen for requests
app.listen(3000, () => {
    console.log('Server is listening on port 3000');
});
713 chars
26 lines

In the above code, we have created an Express app, connected to a MongoDB database, and defined a simple route.

Next, we can define the car schema and model using Mongoose:

index.ts
import mongoose from 'mongoose';

// define car schema
const CarSchema = new mongoose.Schema({
    make: String,
    model: String,
    year: Number,
    price: Number
});

// create car model
const CarModel = mongoose.model('Car', CarSchema);
244 chars
13 lines

Now that we have the car model, we can define the CRUD endpoints:

index.ts
// create a car
app.post('/cars', async (req, res) => {
    const car = new CarModel(req.body);

    try {
        await car.save();
        res.send(car);
    } catch (error) {
        res.status(500).send(error);
    }
});

// read all cars
app.get('/cars', async (req, res) => {
    try {
        const cars = await CarModel.find();
        res.send(cars);
    } catch (error) {
        res.status(500).send(error);
    }
});

// read a single car
app.get('/cars/:id', async (req, res) => {
    try {
        const car = await CarModel.findById(req.params.id);
        res.send(car);
    } catch (error) {
        res.status(500).send(error);
    }
});

// update a car
app.put('/cars/:id', async (req, res) => {
    try {
        const car = await CarModel.findByIdAndUpdate(req.params.id, req.body, { new: true });
        res.send(car);
    } catch (error) {
        res.status(500).send(error);
    }
});

// delete a car
app.delete('/cars/:id', async (req, res) => {
    try {
        await CarModel.findByIdAndDelete(req.params.id);
        res.send({ message: 'Car deleted successfully!' });
    } catch (error) {
        res.status(500).send(error);
    }
});
1171 chars
52 lines

With the above endpoints in place, we can now test the API using a tool like Postman or cURL. We can send a POST request to /cars to create a new car, a GET request to /cars to retrieve all cars, a GET request to /cars/:id to retrieve a single car, a PUT request to /cars/:id to update a car, and a DELETE request to /cars/:id to delete a car.

That's it! We have successfully created a CRUD application for cars in TypeScript using Node.js, Express, Mongoose, and MongoDB.

gistlibby LogSnag