mirror of
https://github.com/MedzikUser/gatsby-pingbot
synced 2024-08-15 03:20:27 +00:00
104 lines
2.2 KiB
TypeScript
104 lines
2.2 KiB
TypeScript
import { VercelRequest, VercelResponse } from '@vercel/node'
|
|
import axios from 'axios'
|
|
import dbConnect from '../lib/dbConnect'
|
|
import URLModel from '../lib/schema'
|
|
|
|
export default async (request: VercelRequest, response: VercelResponse) => {
|
|
const { method } = request
|
|
await dbConnect()
|
|
|
|
switch (method) {
|
|
case 'POST':
|
|
if (!request.body || !request.body.url) {
|
|
return response.status(400).json(
|
|
{
|
|
success: false,
|
|
message: 'Invalid body'
|
|
}
|
|
)
|
|
}
|
|
|
|
try {
|
|
await axios.get(request.body.url)
|
|
} catch (err) {
|
|
console.error(err)
|
|
return response.status(400).json(
|
|
{
|
|
success: false,
|
|
message: 'Invalid URL'
|
|
}
|
|
)
|
|
}
|
|
|
|
try {
|
|
const url = new URLModel({
|
|
url: request.body.url
|
|
})
|
|
|
|
await url.save()
|
|
|
|
return response.status(200).json(
|
|
{
|
|
success: true,
|
|
url: request.body.url
|
|
}
|
|
)
|
|
} catch (err) {
|
|
console.error(err)
|
|
return response.status(400).json(
|
|
{
|
|
success: false,
|
|
message: 'Error Inserting to DB'
|
|
}
|
|
)
|
|
}
|
|
case 'DELETE':
|
|
if (!request.query.url) {
|
|
return response.status(400).json(
|
|
{
|
|
success: false,
|
|
message: 'Invalid body'
|
|
}
|
|
)
|
|
}
|
|
|
|
try {
|
|
const url = request.query.url
|
|
|
|
if (typeof url != 'string') {
|
|
return response.status(400).json(
|
|
{
|
|
success: false,
|
|
message: 'Query URL isn\'t string'
|
|
}
|
|
)
|
|
}
|
|
|
|
await URLModel.deleteOne({
|
|
url
|
|
})
|
|
|
|
return response.status(200).json(
|
|
{
|
|
success: true,
|
|
message: 'Deleted!',
|
|
url
|
|
}
|
|
)
|
|
} catch (err) {
|
|
console.error(err)
|
|
return response.status(400).json(
|
|
{
|
|
success: false,
|
|
message: 'Error Deleting from DB'
|
|
}
|
|
)
|
|
}
|
|
default:
|
|
response.status(200).json({
|
|
db: await URLModel.find()
|
|
})
|
|
|
|
break
|
|
}
|
|
}
|