Files
2026-10-11 07:55:36 -07:00

35 lines
1.1 KiB
JavaScript
Executable File

'use strict'
// Small HTTP helpers shared by every route module.
function setCors(res) {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
}
function sendJson(res, code, obj) {
res.writeHead(code, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(obj))
}
/** Resolves to the parsed JSON body (or {} on empty/invalid). Caps at 100 KB. */
function readBody(req) {
return new Promise((resolve) => {
let body = ''
req.on('data', (c) => {
body += c
if (body.length > 1e5) req.destroy()
})
req.on('end', () => {
try { resolve(JSON.parse(body || '{}')) } catch { resolve({}) }
})
})
}
const ok = (res, extra = {}) => sendJson(res, 200, { ok: true, ...extra })
const bad = (res, msg = 'bad request') => sendJson(res, 400, { error: msg })
const unavailable = (res, msg = 'SoundCloud client not ready — sign in first') => sendJson(res, 503, { error: msg })
module.exports = { setCors, sendJson, readBody, ok, bad, unavailable }