|
| 1 | +#!/usr/bin/swift sh |
| 2 | + |
| 3 | +import MacroExpress // @Macro-swift ~> 0.0.3 |
| 4 | +import cows // @AlwaysRightInstitute ~> 1.0.0 |
| 5 | + |
| 6 | +let app = express() |
| 7 | + |
| 8 | +app.use(logger("dev")) |
| 9 | +app.use(bodyParser.urlencoded()) |
| 10 | +app.use(cookieParser()) |
| 11 | +app.use(session()) |
| 12 | +app.use(serveStatic(__dirname() + "/public")) |
| 13 | + |
| 14 | +// MARK: - Express Settings |
| 15 | + |
| 16 | +app.set("view engine", "html") // really mustache, but we want to use .html |
| 17 | +app.set("views", __dirname() + "/views") |
| 18 | + |
| 19 | + |
| 20 | +// MARK: - Session View Counter |
| 21 | + |
| 22 | +app.use { req, _, next in |
| 23 | + req.session["viewCount"] = req.session[int: "viewCount"] + 1 |
| 24 | + next() |
| 25 | +} |
| 26 | + |
| 27 | + |
| 28 | +// MARK: - Routes |
| 29 | + |
| 30 | +let taglines = [ |
| 31 | + "Less than Perfect.", |
| 32 | + "Das Haus das Verrückte macht.", |
| 33 | + "Rechargeables included", |
| 34 | + "Sensible Server Side Swift aS a Successful Software Service Solution" |
| 35 | +] |
| 36 | + |
| 37 | + |
| 38 | +// MARK: - Form Handling |
| 39 | + |
| 40 | +app.get("/form") { _, res, _ in |
| 41 | + res.render("form") |
| 42 | +} |
| 43 | +app.post("/form") { req, res, _ in |
| 44 | + let user = req.body[string: "u"] |
| 45 | + console.log("USER IS: \(user)") |
| 46 | + |
| 47 | + let options : [ String : Any ] = [ |
| 48 | + "user" : user, |
| 49 | + "nouser" : user.isEmpty, |
| 50 | + "viewCount" : req.session["viewCount"] ?? 0 |
| 51 | + ] |
| 52 | + res.render("form", options) |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +// MARK: - JSON & Cookies |
| 57 | + |
| 58 | +app.get("/json") { _, res, _ in |
| 59 | + res.json([ |
| 60 | + [ "firstname": "Donald", "lastname": "Duck" ], |
| 61 | + [ "firstname": "Dagobert", "lastname": "Duck" ] |
| 62 | + ]) |
| 63 | +} |
| 64 | + |
| 65 | +app.get("/cookies") { req, res, _ in |
| 66 | + // returns all cookies as JSON |
| 67 | + res.json(req.cookies) |
| 68 | +} |
| 69 | + |
| 70 | + |
| 71 | +// MARK: - Cows |
| 72 | + |
| 73 | +app.get("/cows") { _, res, _ in |
| 74 | + res.send("<html><body><pre>\(cows.vaca())</pre></body></html>") |
| 75 | +} |
| 76 | + |
| 77 | + |
| 78 | +// MARK: - Main page |
| 79 | + |
| 80 | +app.get("/") { req, res, _ in |
| 81 | + let tagline = taglines.randomElement()! |
| 82 | + |
| 83 | + let values : [ String : Any ] = [ |
| 84 | + "tagline" : tagline, |
| 85 | + "viewCount" : req.session["viewCount"] ?? 0, |
| 86 | + "cowOfTheDay" : cows.vaca() |
| 87 | + ] |
| 88 | + res.render("index", values) |
| 89 | +} |
| 90 | + |
| 91 | + |
| 92 | +// MARK: - Start Server |
| 93 | + |
| 94 | +app.listen(1337) { |
| 95 | + console.log("Server listening: \($0)") |
| 96 | +} |
0 commit comments