Merge pull request #126 from toeydevelopment/master
feat: Add upsert API endpoint for link management
This commit is contained in:
commit
a166c30532
1 changed files with 38 additions and 0 deletions
38
server/api/link/upsert.post.ts
Normal file
38
server/api/link/upsert.post.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
import { LinkSchema } from '@/schemas/link'
|
||||||
|
|
||||||
|
export default eventHandler(async (event) => {
|
||||||
|
const link = await readValidatedBody(event, LinkSchema.parse)
|
||||||
|
const { caseSensitive } = useRuntimeConfig(event)
|
||||||
|
|
||||||
|
if (!caseSensitive) {
|
||||||
|
link.slug = link.slug.toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
const { cloudflare } = event.context
|
||||||
|
const { KV } = cloudflare.env
|
||||||
|
|
||||||
|
// Check if link exists
|
||||||
|
const existingLink = await KV.get(`link:${link.slug}`, { type: 'json' })
|
||||||
|
|
||||||
|
if (existingLink) {
|
||||||
|
// If link exists, return it along with the short link
|
||||||
|
const shortLink = `${getRequestProtocol(event)}://${getRequestHost(event)}/${link.slug}`
|
||||||
|
return { link: existingLink, shortLink, status: 'existing' }
|
||||||
|
}
|
||||||
|
|
||||||
|
// If link doesn't exist, create it
|
||||||
|
const expiration = getExpiration(event, link.expiration)
|
||||||
|
|
||||||
|
await KV.put(`link:${link.slug}`, JSON.stringify(link), {
|
||||||
|
expiration,
|
||||||
|
metadata: {
|
||||||
|
expiration,
|
||||||
|
url: link.url,
|
||||||
|
comment: link.comment,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
setResponseStatus(event, 201)
|
||||||
|
const shortLink = `${getRequestProtocol(event)}://${getRequestHost(event)}/${link.slug}`
|
||||||
|
return { link, shortLink, status: 'created' }
|
||||||
|
})
|
||||||
Loading…
Reference in a new issue