sei-ec-remote / project-4-issues

Open an issue to receive help on project 4
0 stars 0 forks source link

Updating Resources #303

Open spenserg92 opened 9 months ago

spenserg92 commented 9 months ago

What stack are you using?

(ex: MERN(mongoose + react), DR(django + react), PEN, etc.)

MERN

What's the problem you're trying to solve?

When I update my platforms resource it causes the game to get deleted or it sends me an unauthorized error even though I'm logged in as the right user.

Post any code you think might be relevant (one fenced block per file)

If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

Screenshot 2024-02-15 at 9 23 38 AM

What is your best guess as to the source of the problem?

Probably my auth stuff

What things have you already tried to solve the problem?

removing require ownership from the game resource.

Paste a link to your repository here https://github.com/spenserg92/GameHub https://github.com/spenserg92/Client-GameHub

timmshinbone commented 9 months ago

Share the entire contents of your routes file for that resource, and share the api function call + react component that is making the api call

spenserg92 commented 9 months ago
import apiUrl from '../apiConfig'
import axios from 'axios'

// READ -> Index
export const getAllPlatforms = () => {
    return axios(`${apiUrl}/platforms`)
}

// READ -> Show
export const getOnePlatform = (id) => {
    return axios(`${apiUrl}/platforms/${id}`)
}

// CREATE -> Platform
export const createPlatform = (user, newPlatform) => {
    return axios({
        url: `${apiUrl}/platforms`,
        method: 'POST',
        headers: {
            Authorization: `Token token=${user.token}`
        },
        data: { platform: newPlatform }
    })
}

// UPDATE -> Adjust a platform
export const updatePlatform = (user, updatedPlatform) => {
    return axios({
        url: `${apiUrl}/platforms/${updatedPlatform._id}`,
        method: 'PATCH',
        headers: {
            Authorization: `Token token=${user.token}`
        },
        data: { platform: updatedPlatform }
    })
}

// DELETE -> Delete platform
export const removePlatform = (user, id) => {
    return axios({
        url: `${apiUrl}/platforms/${id}`,
        method: 'DELETE',
        headers: {
            Authorization: `Token token=${user.token}`
        }
    })
}
const express = require('express')
const passport = require('passport')
const Platform = require('../models/platform')
const customErrors = require('../../lib/custom_errors')
const handle404 = customErrors.handle404
const requireOwnership = customErrors.requireOwnership
const removeBlanks = require('../../lib/remove_blank_fields')
const requireToken = passport.authenticate('bearer', { session: false })
const router = express.Router()

// INDEX
// GET /platforms
router.get('/platforms', (req, res, next) => {
    Platform.find()
        .populate('owner')
        .then((platforms) => {
            return platforms.map((platform) => platform.toObject())
        })
        .then((platforms) => res.status(200).json({ platforms: platforms }))
        .catch(next)
})

router.get('/platforms/mine', requireToken, (req, res, next) => {
    Platform.find({owner: req.user.id})
        .then((platforms) => {
            return platforms.map((platform) => platform.toObject())
        })
        .then((platforms) => res.status(200).json({ platforms: platforms }))
        .catch(next)
})

// SHOW
// GET /platforms/5a7db6c74d55bc51bdf39793
router.get('/platforms/:id', (req, res, next) => {
    Platform.findById(req.params.id)
        .populate('owner')
        .then(handle404)
        .then((platform) => res.status(200).json({ platform: platform.toObject() }))
        .catch(next)
})

// CREATE
// POST /platforms
router.post('/platforms', requireToken, (req, res, next) => {
    req.body.platform.owner = req.user.id

    Platform.create(req.body.platform)
        .then((platform) => {
            res.status(201).json({ platform: platform.toObject() })
        })
        .catch(next)
})

// UPDATE
// PATCH /platforms/5a7db6c74d55bc51bdf39793
router.patch('/platforms/:id', requireToken, removeBlanks, (req, res, next) => {
    delete req.body.platform.owner
    Platform.findById(req.params.id)
        .then(handle404)
        .then((platform) => {
            requireOwnership(req, platform)
            return platform.updateOne(req.body.platform)
        })
        .then(() => res.sendStatus(204))
        .catch(next)
})

// DESTROY
// DELETE /platforms/5a7db6c74d55bc51bdf39793
router.delete('/platforms/:id', requireToken, (req, res, next) => {
    Platform.findById(req.params.id)
        .then(handle404)
        .then((platform) => {
            requireOwnership(req, platform)
            platform.deleteOne()
        })
        .then(() => res.sendStatus(204))
        .catch(next)
})

module.exports = router
timmshinbone commented 9 months ago

ok, now let me see the form you use for updating the platforms

spenserg92 commented 9 months ago
import React, { useState } from 'react'
import { Modal } from 'react-bootstrap'
import PlatformForm from '../shared/PlatformForm'
import messages from '../shared/AutoDismissAlert/messages'

const EditPlatformModal = (props) => {
    const { user, show, handleClose, updatePlatform, msgAlert, triggerRefresh } = props
    const [platform, setPlatform] = useState(props.platform)

    const onChange = (e) => {
        e.persist()
        setPlatform(prevPlatform => {
            const updatedName = e.target.name
            let updatedValue = e.target.value
            if (e.target.type === 'number') {
                updatedValue = parseInt(e.target.value)
            }
            const updatedPlatform = { [updatedName] : updatedValue }
            return {
                ...prevPlatform, ...updatedPlatform
            }
        })
    }

    const onSubmit = (e) => {
        e.preventDefault()
        updatePlatform(user, platform)
            .then(() => handleClose())
            .then(() => {
                msgAlert({
                    heading: 'Oh Yeah!',
                    message: messages.updatePlatformSuccess,
                    variant: 'success'
                })
            })
            .then(() => triggerRefresh())
            .catch(() => {
                msgAlert({
                    heading: 'Oh no!',
                    message: messages.generalError,
                    variant: 'danger'
                })
            })
    }

    return (
        <Modal show={show} onHide={handleClose}>
            <Modal.Header closeButton />
            <Modal.Body>
                <PlatformForm 
                    platform={platform}
                    handleChange={onChange}
                    handleSubmit={onSubmit}
                    heading="Update Platform"
                />
            </Modal.Body>
        </Modal>
    )
}

export default EditPlatformModal
timmshinbone commented 9 months ago

Share the actual form, if ya don't mind

spenserg92 commented 9 months ago

Apologies

import { Form, Button, Container } from 'react-bootstrap'

const PlatformForm = (props) => {
    const { platform, handleChange, handleSubmit, heading } = props

    return (
        <Container className="justify-content-center">
            <h3>{heading}</h3>
            <Form onSubmit={handleSubmit}>
                <Form.Group className='m-2'>
                    <Form.Label>Name: </Form.Label>
                    <Form.Control 
                        placeholder="What is the platform?"
                        id="name"
                        name="name"
                        value={ platform.name }
                        onChange={handleChange}
                    />
                </Form.Group>
                <Form.Group className='m-2'>
                    <Form.Label>Manufacturer: </Form.Label>
                    <Form.Control 
                        placeholder="What is the manufacturer?"
                        id="manufacturer"
                        name="manufacturer"
                        value={ platform.manufacturer }
                        onChange={handleChange}
                    />
                </Form.Group>
                <Form.Group className='m-2'>
                    <Form.Label>Release Year: </Form.Label>
                    <Form.Control 
                        type="number"
                        placeholder="Year of Release?"
                        id="releaseYear"
                        name="releaseYear"
                        value={ platform.releaseYear }
                        onChange={handleChange}
                    />
                </Form.Group>
                <Form.Group className='m-2'>
                <Form.Label>MSRP: </Form.Label>
                    <Form.Control
                        type="number"
                        placeholder="What is the MSRP of this platform?"
                        id="price"
                        name="price"
                        value={ platform.price }
                        onChange={handleChange}
                    />
                </Form.Group>
                <Button className="m-2" type="submit">Submit</Button>
            </Form>
        </Container>
    )
}

export default PlatformForm 
timmshinbone commented 9 months ago

ok, let me see the platform model its relationship to games

spenserg92 commented 9 months ago
const mongoose = require('mongoose')
const gameSchema = require('./game')
const platformSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: true,
        },
        releaseYear: {
            type: String,
            min: 4,
            max: 4,
        },
        manufacturer: {
            type: String,
            required: true,
        },
        price: {
            type: Number,
            required: true,
        },
        games: [gameSchema],
        owner: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
        },
    },
    {
        timestamps: true,
    }
)

module.exports = mongoose.model('Platform', platformSchema)
timmshinbone commented 9 months ago

Weird, it really shouldn't be overwriting the games array

timmshinbone commented 9 months ago

we'll have to look in a 1:1