import { Application, Request, Response } from 'express' import UserService from '../services/userService' import jwt from 'jsonwebtoken' import config from './config' import { loginAccountSchema, registerAccountSchema } from './zodTypes' import fs from 'fs' import { httpLogger } from './logger' import { getPublicPath } from './storage' import zoneRepository from '../repositories/zoneRepository' async function addHttpRoutes(app: Application) { /** * Login * @param req * @param res */ app.post('/login', async (req: Request, res: Response) => { const { username, password } = req.body try { loginAccountSchema.parse({ username, password }) } catch (error: any) { return res.status(400).json({ message: error.errors[0]?.message }) } const userService = new UserService() const user = await userService.login(username, password) if (user && typeof user !== 'boolean') { const token = jwt.sign({ id: user.id }, config.JWT_SECRET, { expiresIn: '4h' }) return res.status(200).json({ token }) } return res.status(400).json({ message: 'Failed to login' }) }) /** * Register * @param req * @param res */ app.post('/register', async (req: Request, res: Response) => { const { username, email, password } = req.body try { registerAccountSchema.parse({ username, email, password }) } catch (error: any) { return res.status(400).json({ message: error.errors[0]?.message }) } const userService = new UserService() const user = await userService.register(username, email, password) if (user) { return res.status(200).json({ message: 'User registered' }) } return res.status(400).json({ message: 'Failed to register user' }) }) /** * Get all tiles from a zone as an array of ids * @param req * @param res */ // app.get('/assets/tiles/:zoneId', async (req: Request, res: Response) => { // const zoneId = req.params.zoneId // // // Check if zoneId is valid number // if (!zoneId || parseInt(zoneId) === 0) { // return res.status(400).json({ message: 'Invalid zone ID' }) // } // // // Get zone by id // const zone = await zoneRepository.getById(parseInt(zoneId)) // if (!zone) { // return res.status(404).json({ message: 'Zone not found' }) // } // // let tiles = zone.tiles; // // // Convert to array // tiles = JSON.parse(JSON.stringify(tiles)) as string[] // // // Flatten the array // tiles = [...new Set(tiles.flat())] // // // Remove duplicates // tiles = tiles.filter((value, index, self) => self.indexOf(value) === index); // // // Return the array // res.json(tiles) // }) /** * Get a specific asset * @param req * @param res */ app.get('/assets/:type/:spriteId?/:file', (req: Request, res: Response) => { const assetType = req.params.type const spriteId = req.params.spriteId const fileName = req.params.file let assetPath if (assetType === 'sprites' && spriteId) { assetPath = getPublicPath(assetType, spriteId, fileName) } else { assetPath = getPublicPath(assetType, fileName) } if (!fs.existsSync(assetPath)) { httpLogger.error(`File not found: ${assetPath}`) return res.status(404).send('Asset not found') } res.sendFile(assetPath, (err) => { if (err) { httpLogger.error('Error sending file:', err) res.status(500).send('Error downloading the asset') } }) }) httpLogger.info('Web routes added') } export { addHttpRoutes }