DEV Community

Stillnoturdad
Stillnoturdad

Posted on

API OVERVIEW

In this article, we’ll walk through a simple event ticketing system built with Node.js and Express. This system allows users to view discount codes, send event tickets, and manage tickets (such as claiming or deleting them). Let's break down how the API works!

  1. Get All Discount Codes (GET /discounts) Imagine you have a bunch of discount codes for events, and you want users to be able to see them. This endpoint does exactly that by fetching all available discount codes from the database.
app.get('/discounts', async (req, res, next) => {
    try {
        let discounts = await DiscountCode.findAll();
        res.status(200).json(discounts);
    } catch (error) {
        next(error);
    }
});

Enter fullscreen mode Exit fullscreen mode

The GET /discounts route retrieves all discount codes from the DiscountCode model.
If everything goes smoothly, it returns the discount codes in JSON format with a 200 OK status.
In case of an error (e.g., database issues), it passes the error to the error-handling middleware.

  1. Send an Event Ticket (POST /tickets/:discountId) This endpoint allows a user to send an event ticket to someone else, using a discount code. The user can send a custom message along with the ticket.
app.post('/tickets/:discountId', async (req, res, next) => {
    try {
        let { message, quantity, recipientId } = req.body;
        let { discountId } = req.params;
        let discount = await DiscountCode.findByPk(discountId);
        if (!discount) throw ({ name: "Custom", status: 404, message: "Discount not found" });

        let ticket = await EventTicket.create({
            message,
            senderId: req.member.id,
            quantity,
            discountId: discount.id,
            recipientId
        });
        res.status(201).json(ticket);
    } catch (error) {
        next(error);
    }
});

Enter fullscreen mode Exit fullscreen mode

The user provides the discountId (via URL parameter), recipientId, a message, and the number of tickets (quantity) in the request body.
The discount code is fetched from the database to ensure it exists. If not, the API throws an error.
If everything checks out, the event ticket is created with the sender's ID, recipient's ID, and the associated discount code.
The response contains the newly created ticket, with a 201 Created status.

  1. Get Event Tickets Received (GET /tickets) This endpoint fetches all the event tickets a user has received. It also includes details about the discount associated with each ticket.
app.get('/tickets', async (req, res, next) => {
    try {
        let tickets = await EventTicket.findAll({
            include: {
                model: DiscountCode,
                as: "discount",
                attributes: ["id", "title", "description"]
            },
            where: {
                recipientId: req.member.id
            }
        });
        if (tickets.length === 0) throw({ name: "Custom", status: 404, message: "Tickets not found" });
        res.status(200).json(tickets);
    } catch (error) {
        next(error);
    }
});
Enter fullscreen mode Exit fullscreen mode

This route fetches all tickets where the current user is the recipient (recipientId matches the logged-in user).
The response includes details about the discount code associated with each ticket (ID, title, and description).
If no tickets are found, a 404 Not Found error is returned.
Otherwise, the tickets are returned with a 200 OK status.

  1. Claim an Event Ticket (PATCH /tickets/:id/claim) Once a user has received a ticket, they can claim it. This endpoint marks a ticket as "claimed."
app.patch('/tickets/:id/claim', authorization, async (req, res, next) => {
    try {
        await EventTicket.update({ status: "claimed" }, {
            where: { id: req.params.id }
        });
        res.status(200).json({ message: "Ticket has been claimed" });
    } catch (error) {
        next(error);
    }
});
Enter fullscreen mode Exit fullscreen mode

The route accepts a ticket ID (:id) and updates the status of that ticket to "claimed."
The authorization middleware ensures the user is authorized to claim the ticket.
After successfully updating the status, the server responds with a 200 OK and a success message.

  1. Delete an Event Ticket (DELETE /tickets/:id) This route allows the user to delete a specific event ticket.

Code:
javascript
Copy code
app.delete('/tickets/:id', authorization, async (req, res, next) => {
try {
await EventTicket.destroy({ where: { id: req.params.id } });
res.status(200).json({ message: "Ticket has been deleted" });
} catch (error) {
next(error);
}
});

The ticket is deleted based on its ID.
The authorization middleware ensures that only the rightful owner of the ticket can delete it.
After successful deletion, a 200 OK status is returned along with a confirmation message.

Top comments (0)