39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import { Router, Response } from 'express';
|
|
import { z } from 'zod';
|
|
import db from '../db.js';
|
|
import { AuthRequest } from '../middleware/auth.js';
|
|
|
|
const router = Router();
|
|
|
|
const registerSchema = z.object({
|
|
device_name: z.string().min(1),
|
|
});
|
|
|
|
router.post('/register', (req: AuthRequest, res: Response) => {
|
|
const parsed = registerSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
res.status(400).json({ error: parsed.error.errors });
|
|
return;
|
|
}
|
|
|
|
const { device_name } = parsed.data;
|
|
|
|
const existing = db
|
|
.prepare('SELECT id FROM devices WHERE user_id = ? AND device_name = ?')
|
|
.get(req.userId!, device_name);
|
|
|
|
if (existing) {
|
|
db.prepare('UPDATE devices SET last_sync_at = CURRENT_TIMESTAMP WHERE id = ?').run((existing as any).id);
|
|
res.json({ deviceId: (existing as any).id });
|
|
return;
|
|
}
|
|
|
|
const result = db
|
|
.prepare('INSERT INTO devices (user_id, device_name, last_sync_at) VALUES (?, ?, CURRENT_TIMESTAMP)')
|
|
.run(req.userId!, device_name);
|
|
|
|
res.status(201).json({ deviceId: result.lastInsertRowid });
|
|
});
|
|
|
|
export default router;
|