Sink/server/api/link/edit.put.ts
ccbikai e7d71b35d3 feat: add short link to edit link response
Enhances link edit endpoint by including a fully-qualified short link URL in the response, constructed from request protocol and host alongside the slug
2024-12-08 14:44:03 +08:00

36 lines
1.2 KiB
TypeScript

import type { z } from 'zod'
import { LinkSchema } from '@/schemas/link'
export default eventHandler(async (event) => {
const { previewMode } = useRuntimeConfig(event).public
if (previewMode) {
throw createError({
status: 403,
statusText: 'Preview mode cannot edit links.',
})
}
const link = await readValidatedBody(event, LinkSchema.parse)
const { cloudflare } = event.context
const { KV } = cloudflare.env
const existingLink: z.infer<typeof LinkSchema> | null = await KV.get(`link:${link.slug}`, { type: 'json' })
if (existingLink) {
const newLink = {
...existingLink,
...link,
id: existingLink.id, // don't update id
createdAt: existingLink.createdAt, // don't update createdAt
updatedAt: Math.floor(Date.now() / 1000),
}
const expiration = getExpiration(event, newLink.expiration)
await KV.put(`link:${newLink.slug}`, JSON.stringify(newLink), {
expiration,
metadata: {
expiration,
},
})
setResponseStatus(event, 201)
const shortLink = `${getRequestProtocol(event)}://${getRequestHost(event)}/${link.slug}`
return { link: newLink, shortLink }
}
})