Files
resman/backend/routes/subdomains.js
T
2026-04-06 17:50:00 +02:00

153 lines
2.6 KiB
JavaScript

const express = require("express")
const router = express.Router()
const db = require("../db")
const clean = (value) => value === "" ? null : value
const mapSubdomainError = (err, fallbackMessage) => {
let message = fallbackMessage
let status = 500
if(err.code === "ER_DUP_ENTRY"){
status = 400
message = "Subdomain existiert bereits"
}
return {status, message}
}
/* alle Subdomains laden */
router.get("/", async (req,res)=>{
try{
const [rows] = await db.query(`
SELECT
s.id,
s.subdomain,
s.ip_address,
d.domain_name,
s.domain_id
FROM subdomains s
JOIN domains d ON s.domain_id=d.id
`)
res.json(rows)
}catch(e){
console.error("SUBDOMAIN LIST error:",e)
res.status(500).json({error:"Subdomains konnten nicht geladen werden"})
}
})
/* Subdomains einer Domain */
router.get("/domain/:id", async (req,res)=>{
try{
const [rows] = await db.query(
"SELECT * FROM subdomains WHERE domain_id=?",
[req.params.id]
)
res.json(rows)
}catch(e){
console.error("SUBDOMAIN DOMAIN error:",e)
res.status(500).json({error:"Subdomains der Domain konnten nicht geladen werden"})
}
})
router.delete("/:id", async (req,res)=>{
try{
await db.query("DELETE FROM subdomains WHERE id=?",[req.params.id])
res.json({success:true})
}catch(e){
console.error("DELETE subdomain error:",e)
res.status(500).json({error:"Subdomain konnte nicht geloescht werden"})
}
})
router.post("/", async (req,res)=>{
try{
const domainId = clean(req.body.domain_id)
const subdomain = req.body.subdomain ? String(req.body.subdomain).trim() : ""
const ipAddress = clean(req.body.ip_address)
if(!domainId){
return res.status(400).json({error:"Domain fehlt"})
}
if(!subdomain){
return res.status(400).json({error:"Subdomain darf nicht leer sein"})
}
await db.query(`
INSERT INTO subdomains
(domain_id, subdomain, ip_address)
VALUES (?,?,?)
`,[domainId, subdomain, ipAddress])
res.json({success:true})
}catch(e){
console.error("CREATE subdomain error:",e)
const {status, message} = mapSubdomainError(e, "Subdomain konnte nicht gespeichert werden")
res.status(status).json({error:message})
}
})
router.put("/:id", async (req,res)=>{
try{
const subdomain = req.body.subdomain ? String(req.body.subdomain).trim() : ""
const ipAddress = clean(req.body.ip_address)
if(!subdomain){
return res.status(400).json({error:"Subdomain darf nicht leer sein"})
}
await db.query(`
UPDATE subdomains
SET subdomain=?, ip_address=?
WHERE id=?
`,[subdomain, ipAddress, req.params.id])
res.json({success:true})
}catch(e){
console.error("UPDATE subdomain error:",e)
const {status, message} = mapSubdomainError(e, "Subdomain konnte nicht gespeichert werden")
res.status(status).json({error:message})
}
})
module.exports = router