mirror of
https://github.com/Azgaar/Fantasy-Map-Generator.git
synced 2025-12-16 17:31:24 +01:00
This commit adds a comprehensive external API system that allows external tools (wikis, web UIs, etc.) to control and synchronize with Fantasy Map Generator. New Features: - External API Bridge (modules/external-api.js) - Event-driven architecture with EventEmitter - Map lifecycle control (create, load, save) - Data access methods (rivers, cultures, states, burgs) - Data mutation methods with auto-redraw - Export support (SVG, PNG, JSON) - Change detection with automatic event emission - PostMessage Communication Layer - Auto-enables when FMG is embedded in iframe - Bidirectional message passing - Request/response pattern with promise support - Automatic event forwarding to parent window - REST API Server (api-server/) - Express.js server with full CRUD operations - WebSocket support via Socket.IO for real-time updates - File upload support for map and CSV import - In-memory storage (can be replaced with database) - CORS enabled for cross-origin requests - Comprehensive endpoints for all map data - Client Library (api-server/client.js) - Simple JavaScript client for REST API - Promise-based async methods - Works in browser and Node.js - Demo Pages (demos/) - PostMessage integration demo with full UI - REST API demo with interactive testing - WebSocket demo for real-time events - Documentation - Comprehensive integration guide (EXTERNAL_API_INTEGRATION.md) - API reference with TypeScript interfaces - Multiple integration examples - Troubleshooting guide Integration Methods: 1. PostMessage Bridge - For iframe embedding 2. REST API - For server-side integration 3. Direct JavaScript API - For same-origin apps Use Cases: - Wiki pages that need to display and control maps - Web UIs that want to edit map data - External tools that need to sync with FMG - Real-time collaborative map editing - Batch operations and automation Technical Details: - Zero dependencies for external-api.js (pure JS) - Auto-initializes on DOMContentLoaded - Throttled change detection (500ms debounce) - Deep cloning for data access (prevents mutations) - Error handling throughout - Version tagged (v1.0.0) Updated Files: - index.html: Added script tag to load external-api module All APIs are backward compatible and don't affect existing functionality.
4.3 KiB
4.3 KiB
Fantasy Map Generator - REST API Server
A Node.js/Express server that provides REST API endpoints and WebSocket support for the Fantasy Map Generator.
Features
- ✅ RESTful API with full CRUD operations
- ✅ WebSocket support for real-time updates
- ✅ Map storage and management
- ✅ CSV import for rivers and other data
- ✅ Export support (SVG, PNG, JSON)
- ✅ CORS enabled for cross-origin requests
- ✅ File upload support
Quick Start
Installation
npm install
Run Server
# Production
npm start
# Development (with auto-reload)
npm run dev
Server will start on http://localhost:3000
API Documentation
Visit http://localhost:3000 after starting the server to see the full API documentation.
Quick Examples
Create a Map
curl -X POST http://localhost:3000/api/maps \
-H "Content-Type: application/json" \
-d '{"seed": "my-world"}'
Response:
{
"success": true,
"mapId": "map_1234567890_abc123",
"message": "Map creation initiated",
"pollUrl": "/api/maps/map_1234567890_abc123"
}
Get Map Data
curl http://localhost:3000/api/maps/map_1234567890_abc123
Update Rivers
curl -X PUT http://localhost:3000/api/maps/map_1234567890_abc123/rivers \
-H "Content-Type: application/json" \
-d '{"rivers": [{"i":1,"name":"Mystic River","type":"River"}]}'
Import Rivers from CSV
curl -X POST http://localhost:3000/api/maps/map_1234567890_abc123/rivers/import \
-F "file=@rivers.csv"
WebSocket
Connect
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.on('connect', () => {
console.log('Connected!');
});
Events
Server Events (listen):
map:creating- Map creation startedmap:created- Map creation completedmap:updated- Map data updatedmap:deleted- Map deletedrivers:updated- Rivers updatedrivers:imported- Rivers imported from CSVburg:added- New burg added
Client Events (emit):
map:update- Update map datamap:created- Notify map creation completeexport:completed- Export completed
Configuration
Environment Variables
# Port (default: 3000)
PORT=3000
Storage
By default, maps are stored in memory. For production, replace the Map with a database:
// Replace this in server.js
const maps = new Map();
// With this (example with MongoDB)
const maps = await db.collection('maps');
Deployment
Docker
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
Build and run:
docker build -t fmg-api .
docker run -p 3000:3000 fmg-api
Production Considerations
- Database: Replace in-memory storage with MongoDB, PostgreSQL, etc.
- Authentication: Add JWT or OAuth for protected endpoints
- Rate Limiting: Add express-rate-limit
- Validation: Add input validation with joi or express-validator
- Logging: Add morgan or winston
- Monitoring: Add health checks and metrics
Architecture
Client (Browser/Wiki)
↓
REST API / WebSocket
↓
Server (Express + Socket.IO)
↓
Storage (In-memory Map / Database)
Dependencies
- express: Web framework
- socket.io: WebSocket server
- cors: Cross-origin resource sharing
- multer: File upload handling
- body-parser: Request body parsing
Development
Add New Endpoint
// In server.js
app.get('/api/maps/:id/custom', async (req, res) => {
try {
const {id} = req.params;
// Your logic here
res.json({success: true, data: {}});
} catch (error) {
res.status(500).json({success: false, error: error.message});
}
});
Add WebSocket Event
// In server.js
io.on('connection', (socket) => {
socket.on('custom:event', (data) => {
// Handle event
io.emit('custom:response', data);
});
});
Testing
Manual Testing
Use the demo pages:
- REST API:
http://localhost:3000/demos/rest-api-demo.html - WebSocket:
http://localhost:3000/demos/websocket-demo.html
Automated Testing
# Install test dependencies
npm install --save-dev mocha chai supertest
# Run tests
npm test
License
MIT - Same as Fantasy Map Generator
Support
For issues and questions, see the main repository.