Open spenserg92 opened 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
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
ok, now let me see the form you use for updating the platforms
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
Share the actual form, if ya don't mind
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
ok, let me see the platform model its relationship to games
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)
Weird, it really shouldn't be overwriting the games array
we'll have to look in a 1:1
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?
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