Merge pull request 'payload-validation' () from payload-validation into staging

Reviewed-on: 
This commit is contained in:
Otto 2025-04-02 09:47:26 +00:00
commit 069a708ac3
5 changed files with 42 additions and 23 deletions

@ -45,11 +45,11 @@ nostrRouter.post('/', async (req: Request, res: Response) => {
const { id, pubkey, created_at, kind, tags, content } = event
const events = await collections.nostrEvents
?.find({ nostrId: id })
.toArray()
const existingEvent = await collections.nostrEvents?.findOne({
nostrId: id
})
if (events?.length) {
if (existingEvent) {
throw new Error('nostr event with provided "id" exists')
}

@ -1,6 +1,8 @@
import express, { Request, Response } from 'express'
import { collections } from '../services/database.service'
import { Review } from '../models'
import { reviewValidation, handleReqError, handleReqSuccess } from '../utils'
import Joi from 'joi'
// Global Config
export const reviewsRouter = express.Router()
@ -25,22 +27,28 @@ reviewsRouter.get('/', async (_req: Request, res: Response) => {
// POST
reviewsRouter.post('/', async (req: Request, res: Response) => {
try {
const review = req.body as Review
const {
error,
value: review
}: { error: Joi.ValidationError | undefined; value: Review } =
reviewValidation(req.body)
if (error) {
throw error.details[0].message
}
const existingReview = await collections.reviews?.findOne({
eventId: review.eventId
})
if (existingReview) {
throw new Error('review with provided "eventId" exists')
}
const result = await collections.reviews?.insertOne(review)
if (result) {
res
.status(201)
.send(`Successfully created a new review with id ${result.insertedId}`)
} else {
res.status(500).send('Failed to create a new review.')
}
handleReqSuccess(res, result, 'review')
} catch (error: unknown) {
console.error(error)
if (error instanceof Error) {
res.status(400).send(error.message)
}
handleReqError(res, error)
}
})

@ -40,18 +40,18 @@ usersRouter.post('/', async (req: Request, res: Response) => {
}
if (typeof newUser.npub === 'string') {
const users = await collections.users
?.find({ npub: newUser.npub })
.toArray()
const existingUser = await collections.users?.findOne({
npub: newUser.npub
})
if (users?.length) {
if (existingUser) {
throw new Error('user with provided "npub" exists')
}
} else {
for (const npub of newUser.npub) {
const users = await collections.users?.find({ npub }).toArray()
const existingUser = await collections.users?.findOne({ npub })
if (users?.length) {
if (existingUser) {
throw new Error('user with provided "npub" exists')
}
}

@ -1,2 +1,3 @@
export * from './user'
export * from './nostr'
export * from './review'

@ -0,0 +1,10 @@
import Joi from 'joi'
export const reviewValidation = (data: unknown): Joi.ValidationResult =>
Joi.object({
eventId: Joi.string().required(),
productId: Joi.string().required(),
rating: Joi.number().required(),
reviewText: Joi.string().required(),
tastingNotes: Joi.array().items(Joi.string())
}).validate(data)