Skip to content

Commit

Permalink
[WIP] Add support for POST on api/webs
Browse files Browse the repository at this point in the history
DinerIsmail committed Nov 16, 2023
1 parent 3f0c3a1 commit 761b7af
Showing 2 changed files with 61 additions and 33 deletions.
2 changes: 1 addition & 1 deletion pages/api/listings/[id].ts
Original file line number Diff line number Diff line change
@@ -129,7 +129,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
break
}
default: {
res.status(500)
res.status(400)
res.json({
error: `Method ${req.method} not supported at this endpoint`,
})
92 changes: 60 additions & 32 deletions pages/api/webs/index.ts
Original file line number Diff line number Diff line change
@@ -5,44 +5,72 @@ import type { Result } from '../type.d'
import { stringToBoolean } from '@helpers/utils'

interface Data {
webs: null | Web[]
error?: string
data: null | Web[] | Web
webs: Web[] // temporary to not break build
}

const handler = async (
req: NextApiRequest,
res: NextApiResponse<Result<Data>>,
) => {
const withListings = req.query.withListings
? stringToBoolean(req.query.withListings as string)
: false

const onlyPublished = req.query.published

try {
const webs: Data['webs'] = await prisma.web.findMany({
where: {
...(onlyPublished
? {
published: true,
}
: {}),
},
include: withListings
? {
listings: {
select: {
id: true,
webId: true,
},
},
}
: null,
})

res.status(200).json({ webs })
} catch (e) {
res.status(500).json({ error: `Unable to fetch webs - ${e}` })
console.error(`[RW] Unable to fetch webs - ${e}`)
switch (req.method) {
case 'GET': {
const withListings = req.query.withListings
? stringToBoolean(req.query.withListings as string)
: false

const onlyPublished = req.query.published

try {
const webs = await prisma.web.findMany({
where: {
...(onlyPublished
? {
published: true,
}
: {}),
},
include: withListings
? {
listings: {
select: {
id: true,
webId: true,
},
},
}
: null,
})

res.status(200).json({ data: webs, webs })
break
} catch (e) {
res.status(500).json({ error: `Unable to fetch webs - ${e}` })
console.error(`[RW] Unable to fetch webs - ${e}`)
}
}
case 'POST': {
const web = await prisma.web.create({
data: {
title: 'Cambridge',
slug: 'cambridge',
published: false,
},
})

res.status(201)
res.json({ data: web, webs: null })

break
}
default: {
res.status(500)
res.json({
error: `Method ${req.method} not supported at this endpoint`,
})
break
}
}
}

1 comment on commit 761b7af

@vercel
Copy link

@vercel vercel bot commented on 761b7af Nov 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.