]> git.cworth.org Git - empires-server/blob - lmno.js
Incorporate empires.js as a sub-app within lmno.js
[empires-server] / lmno.js
1 const express = require("express");
2 const cors = require("cors");
3 const body_parser = require("body-parser");
4
5 const app = express();
6 app.use(cors());
7
8 /* Load each of our game mini-apps. */
9 var empires = require("./empires");
10
11 class LMNO {
12   constructor() {
13     this.ids = {};
14   }
15
16   generate_id() {
17     return [null,null,null,null].map(() => LMNO.letters.charAt(Math.floor(Math.random() * LMNO.letters.length))).join('');
18   }
19
20   create_game(engine) {
21     do {
22       var id = this.generate_id();
23     } while (id in this.ids);
24
25     const game = new empires.Game();
26
27     this.ids[id] = {
28         id: id,
29         engine: engine,
30         game: game
31     };
32
33     return id;
34   }
35 }
36
37 /* Some letters we don't use in our IDs:
38  *
39  * 1. Vowels (AEIOU) to avoid accidentally spelling an unfortunate word
40  * 2. Lowercase letters (replace with corresponding capital on input)
41  * 3. N (replace with M on input)
42  * 4. P (replace with B on input)
43  * 5. S (replace with F on input)
44  */
45 LMNO.letters = "BCDFGHJKLMQRTVWXYZ";
46
47 const lmno = new LMNO();
48
49 app.post('/new/:game_engine', (request, response) =>  {
50   const game_engine = request.params.game_engine;
51   const game_id = lmno.create_game(game_engine);
52   response.send(JSON.stringify(game_id));
53 });
54
55 /* Redirect any requests to a game ID at the top-level.
56  *
57  * Specifically, after obtaining the game ID (from the path) we simply
58  * lookup the game engine for the corresponding game and then redirect
59  * to the engine- and game-specific path.
60  */
61 app.get('/[a-zA-Z0-9]{4}', (request, response) => {
62   const game_id = request.path.replace(/\//g, "");
63
64   const game = lmno.ids[game_id];
65   if (game === undefined) {
66       response.sendStatus(404);
67       return;
68   }
69   response.redirect(301, `/${game.engine}/${game.id}/`);
70 });
71
72 /* LMNO middleware to lookup the game. */
73 app.use('/empires/:game_id([a-zA-Z0-9]{4})', (request, response, next) => {
74   request.game = lmno.ids[request.params.game_id].game;
75   if (request.game === undefined) {
76     response.sendStatus(404);
77     return;
78   }
79   next();
80 });
81
82 /* Mount sub apps. only _after_ we have done all the middleware we need. */
83 app.use('/empires/[a-zA-Z0-9]{4}/', empires.app);
84
85 app.listen(4000, function () {
86   console.log('LMNO server listening on localhost:4000');
87 });