Files
snakkimo-API/src/routes/user-names.js
admin 10570786e9 Add languages, user_names, users_public tables and routes; fix _se→_sv rename
- Fix broken rename migration array (sed had corrupted from values to _sv)
- Add languages table with status lifecycle and trilingual titles
- Add user_names table with unique lowercase index
- Add users_public table linking to user_names and languages (native/target)
- Wire all three new routes under /api/languages, /api/user-names, /api/users-public

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 13:47:52 +02:00

68 lines
2.3 KiB
JavaScript

const router = require('express').Router();
const { query } = require('../db');
// GET /api/user-names
router.get('/', async (req, res, next) => {
try {
const { limit = 50, offset = 0 } = req.query;
const result = await query(
`SELECT * FROM user_names ORDER BY created_at DESC LIMIT $1 OFFSET $2`,
[Math.min(parseInt(limit), 500), parseInt(offset)]
);
res.json(result.rows);
} catch (err) { next(err); }
});
// GET /api/user-names/:id
router.get('/:id', async (req, res, next) => {
try {
const result = await query('SELECT * FROM user_names WHERE id = $1', [req.params.id]);
if (!result.rows.length) return res.status(404).json({ error: 'Not found' });
res.json(result.rows[0]);
} catch (err) { next(err); }
});
// POST /api/user-names
router.post('/', async (req, res, next) => {
try {
const { username } = req.body;
if (!username) return res.status(400).json({ error: 'username is required' });
const result = await query(
`INSERT INTO user_names (username, username_lowercase) VALUES ($1, $2) RETURNING *`,
[username, username.toLowerCase()]
);
res.status(201).json(result.rows[0]);
} catch (err) {
if (err.code === '23505') return res.status(409).json({ error: 'Username already taken' });
next(err);
}
});
// PATCH /api/user-names/:id
router.patch('/:id', async (req, res, next) => {
try {
const { username } = req.body;
if (!username) return res.status(400).json({ error: 'No valid fields provided' });
const result = await query(
`UPDATE user_names SET username = $1, username_lowercase = $2 WHERE id = $3 RETURNING *`,
[username, username.toLowerCase(), req.params.id]
);
if (!result.rows.length) return res.status(404).json({ error: 'Not found' });
res.json(result.rows[0]);
} catch (err) {
if (err.code === '23505') return res.status(409).json({ error: 'Username already taken' });
next(err);
}
});
// DELETE /api/user-names/:id
router.delete('/:id', async (req, res, next) => {
try {
const result = await query('DELETE FROM user_names WHERE id = $1 RETURNING id', [req.params.id]);
if (!result.rows.length) return res.status(404).json({ error: 'Not found' });
res.status(204).end();
} catch (err) { next(err); }
});
module.exports = router;