Skip to content

Commit

Permalink
upsert shared challenge
Browse files Browse the repository at this point in the history
  • Loading branch information
dlopezalvas committed Nov 29, 2023
1 parent a348590 commit 7f5c43e
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/api/routes/creatorChallenges.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import * as express from 'express'
import { syncHandler, AuthenticatedRequest } from './utils'
import { tokenAuth, tryy, onlyIfAuth } from './middlewares'
import { CreatorChallenge, CreatorChallengeModel } from '../../models/creatorChallenge'
import { CreatorChallengeModel } from '../../models/creatorChallenge'

const router = express.Router()

const upsertChallenge = async (_id, user, body) => {
let challenge = await CreatorChallengeModel.findOne({ _id, user }).exec()
if (!challenge) {
challenge = await CreatorChallengeModel.create({ ...body })
} else {
await challenge.set(body).save()
}
return challenge
}

router.post('/share', tryy(tokenAuth), onlyIfAuth, syncHandler(async (req: AuthenticatedRequest, res) => {
const { user, body } = req
body.user = user

res.json(await CreatorChallengeModel.create({...body}))
res.json(await CreatorChallengeModel.create({ ...body }))
}))

router.get('/sharedChallenge/:_id', (async (req: AuthenticatedRequest, res) => {
Expand All @@ -20,9 +29,8 @@ router.get('/sharedChallenge/:_id', (async (req: AuthenticatedRequest, res) => {

router.put('/share/:_id', tryy(tokenAuth), onlyIfAuth, syncHandler(async (req: AuthenticatedRequest, res) => {
const { _id } = req.params as any
const challenge = await CreatorChallengeModel.findOne({ _id }).exec()
await challenge.set(req.body).save()
res.json(challenge)
const { user, body } = req
res.json(await upsertChallenge(_id, user, body))
}))


Expand Down

0 comments on commit 7f5c43e

Please sign in to comment.