Cannot convert value of type 'URLRequest' to expected argument type 'URL' from my request object

37 Views Asked by At

This is my join group function where I am trying to pass the request that is in the wrong form:

 do {
                // Assuming you have the API endpoint URL for joining a group
                let apiUrlString = "http://localhost/api/joinGroup/\(carpoolID)"
                guard let apiUrl = URL(string: apiUrlString) else {
                    // Handle the case where the URL is not valid
                    completion(.failure(WebService.NetworkError.invalidRequest))
                    return
                }

                // Create the request body
                let requestBody: [String: Any] = ["firebase_user_id": firebaseUserID]

                // Convert the request body to Data
                guard let requestData = try? JSONSerialization.data(withJSONObject: requestBody) else {
                    completion(.failure(WebService.NetworkError.invalidRequest))
                    return
                }
                guard let firebaseUserId = Auth.auth().currentUser?.uid else {
                    // Handle the case where there is no logged-in user
                    completion(.failure(WebService.NetworkError.invalidResponse))
                    return
                }

                // Make the request
                var request = URLRequest(url: apiUrl)
                request.httpMethod = "POST"
                request.addValue("application/json", forHTTPHeaderField: "Content-Type")
                request.httpBody = requestData
                request.addValue(firebaseUserId, forHTTPHeaderField: "firebase-user-id")

                do {
                    let (data, response) = try await URLSession.shared.data(from: request)

the error occurs on the let (data, response) = try await URLSession.shared.data(from: request) line

I have tried using request.url! but then I do not get the information required. I am trying to fetch information from my api from this endpoint:

app.post('/api/joinGroup/:carpool_id', express.json(), async (req, res) => {
    const result = joinGroupSchema.validate(req.body);

    if (result.error) {
        return res.status(400).json({ error: result.error.details[0].message });
    }

    const carpoolID = req.params.carpool_id;
    const firebaseUserID = req.body.firebase_user_id;

    try {
        console.log('Join Group Request Body:', req.body);

        const groupId = parseInt(carpoolID);

        // Check if the group (carpool) exists
        const groupExists = carpools.some(c => c.carpoolID === groupId);
        if (!groupExists) {
            console.log('Group does not exist:', groupId);
            return res.status(404).json({ error: 'The group with the given ID was not found.' });
        }

        // Check if the user is already a member of the group
        const userExistsInGroup = await db.query('SELECT 1 FROM user_carpools WHERE firebase_user_id = $1 AND carpool_id = $2', [firebaseUserID, groupId]);
        if (userExistsInGroup.rows.length > 0) {
            console.log('User is already a member of the group:', firebaseUserID, groupId);
            return res.status(400).json({ error: 'User is already a member of the group.' });
        }

        // Add user to the group
        const addUserToGroupQuery = 'INSERT INTO user_carpools(firebase_user_id, carpool_id) VALUES ($1, $2)';
        await db.query(addUserToGroupQuery, [firebaseUserID, groupId]);

        console.log('User added to the group successfully:', firebaseUserID, groupId);
        return res.status(200).json({ message: 'User added to the group successfully' });
    } catch (err) {
        console.error(err);
        return res.status(500).json({ error: 'Internal Server Error' });
    }
});

Any help is appreciated! Thank you!

0

There are 0 best solutions below