Commits

firefly committed d062f7a

Translated app.coffee to JavaScript.

  • Participants
  • Parent commits a364d25

Comments (0)

Files changed (2)

src/app.coffee

-###########################################################
-#### Wyke ExpressJS implementation ########################
-###########################################################
-
-express   = require 'express'
-Mongolian = require 'mongolian'
-wykeUtils = require './wyke'
-
-basename = __dirname.replace /\/[^\/]+$/, ''
-
-# Init the Express web server
-app = express.createServer()
-app.use express.bodyParser()
-app.use express.cookieParser()
-app.use express.session secret: "there is no_secret!"
-app.use express.static basename + '/res'
-
-# Setup the database...
-database = (new Mongolian 'localhost', 27017).db 'wyke'
-database = require('./fakedb').create basename + '/res/testdb.json'
-database.load()
-
-pages       = database.collection 'pages'
-namespaces  = database.collection 'namespaces'
-
-# Create the Wyke instance
-wyke = new wykeUtils.Wyke {database: database}
-
-# Catch all /wyke/anything/ident URLs, even when ident contains '/' characters.
-app.all /^\/wyke\/[^\/]+(?:\/(.*))?/, (req, res, next) ->
-	req.ident = req.params[0] or "Index"
-	req.addr  = req.connection.remoteAddress or "???"
-	do next
-
-app.all /^\/(?!wyke)(.*)/, (req, res) ->
-	req.ident = "Page:#{req.params[0] or 'Index'}"
-	getRaw req, res
-
-# app.get '/?',      (req, res) -> res.redirect '/wyke/view/Index'
-app.get '/wyke/?', (req, res) -> res.redirect '/wyke/view/Index'
-
-#### /wyke/view/:ident ####################################
-app.get '/wyke/view/*?', (req, res) ->
-	console.log "[#{req.addr}] [  view] #{req.ident}"
-	
-	wyke.getPage req.ident, (err, page) ->
-		if err and err.errno == 404
-			# TODO: Add proper 404 page.
-			res.send "Page not found: #{req.ident}", 404
-			return
-		
-		page.getNamespace (err, ns) ->
-			wyke.renderPage page, (err, result) ->
-				if err
-					res.send "<pre>Error:\n" + err.message + "</pre>"
-				else
-					res.send result
-
-#### /wyke/raw/:ident #####################################
-# FIXME: Join with the above function.
-app.get '/wyke/raw/*', getRaw = (req, res) ->
-	console.log "[#{req.addr}] [  raw ] #{req.ident}"
-	
-	wyke.getPage req.ident, (err, page) ->
-		if err and err.errno == 404
-			res.send "Page not found: #{req.ident}", 404
-			return
-		
-		page.getNamespace (err, ns) ->
-			if err
-				res.send "<pre>Error:\n" + err.message + "</pre>"
-			else
-				res.contentType(ns.mimetype)
-				res.send page.body
-
-#### /wyke/edit/:ident ####################################
-app.get '/wyke/edit/*', (req, res) ->
-	console.log "[#{req.addr}] [  edit] #{req.ident}"
-	wyke.getPage req.ident, (err, page) ->
-		if err
-			if err.errno == 404
-				page = {	# TODO: Better way to create a "default page"
-					ident : req.ident
-					title : wykeUtils.parseIdent req.ident
-					body  : ""
-				}
-			
-			else
-				throw err
-		
-		entify = (str) ->
-			str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
-		
-		body = """
-			<form action="/wyke/edit/#{page.ident}" method="POST">
-				<div class="editor-wrapper">
-					<textarea class="editor" name="page[body]" rows="25" cols="80">#{entify page.body}</textarea>
-				</div>
-				<input type="submit" value="Save" />
-			</form>
-		"""
-		
-		opts = {
-			ident    : page.ident
-			title    : "Editing #{page.title.pretty}"
-			body     : body
-			internal : false
-		}
-		
-		wyke.renderInternalPage opts, (err, result) ->
-				res.send result
-
-app.post '/wyke/edit/*', (req, res) ->
-	throw new Error "Something went wrong!" if not req.body.page
-	console.log "[#{req.addr}] [# SAVE] #{req.ident}"
-
-	content = req.body.page.body.replace /\r\n/g, '\n'
-	
-	wyke.storePage req.ident, content, (err, page) ->
-		throw err if err
-		res.redirect "/wyke/view/#{page.ident}"
-
-#### /wyke/internal #######################################
-app.get '/wyke/internal', (req, res) ->
-	namespaces.find().toArray (err, namespaces) ->
-		pages.find().toArray (err, pages) ->
-			throw err if err
-			
-			jsPrint = (obj) ->
-				JSON.stringify(obj, 0, 4).replace /[<>&]/g, (chr) ->
-					("<": "&lt;", ">": "&gt;")[chr]
-			
-			pagelist = pages.map (page) ->
-				"	<li><a href=\"/wyke/view/#{page.ident}\">#{page.title.pretty}</a></li>"
-			
-			body = """
-				<h2 id="pagelist">Pagelist</h2>
-				<ul>
-				#{pagelist.join "\n"}
-				</ul>
-			"""
-			
-			opts = {
-				ident : "--internal:internal"
-				title : "Internal status"
-				body  : body
-			}
-			
-			wyke.renderInternalPage opts, (err, result) ->
-				res.send result
-
-app.get '/wyke/internal-save-db', (req, res) ->
-	database.save()
-
-	opts = {
-		ident : "--internal:save-db"
-		title : "Saving database"
-		body  : """
-			<p>Database saved successfully!</p>
-		"""
-	}
-
-	wyke.renderInternalPage opts, (err, result) ->
-		res.send result
-
-#### /wyke/settings #######################################
-app.all '/wyke/settings', (req, res) ->
-	sendBack = ->
-		namespaceMap = {}
-
-		namespaces.find().toArray (err, namespaces) ->
-			namespaceList = namespaces.map (ns) ->
-				namespaceMap[ns.name] = ns
-				extra = (val for key,val of ns when key not in ['_id', 'name'])
-				"<li data-name=\"#{ns.name}\">#{ns.name} : #{extra.join ' : '}</li>"
-			
-			body = """
-				<h2>Namespaces</h2>
-				<p>These namespaces already exist:</p>
-				<ul id="templates">
-					#{namespaceList.join "\n"}
-				</ul>
-				
-				<form action="/wyke/settings" method="POST">
-					<fieldset>
-						<legend>Add or update namespace</legend>
-						
-						<label for="name">Name:</label>
-						<input type="text" name="newNS[name]" id="name" />
-						<label for="includer">Includer:</label>
-						<input type="text" name="newNS[includer]" id="includer" />
-						<label for="renderer">Renderer:</label>
-						<input type="text" name="newNS[renderer]" id="renderer" />
-						<label for="mimetype">Mime type:</label>
-						<input type="text" name="newNS[mimetype]" id="mimetype" />
-						
-						<input type="submit" value="Update" />
-					</fieldset>
-				</form>
-				<script>
-				function $e(str) {return document.getElementById(str)}
-				
-				window.addEventListener('load', function () {
-					lis = $e('templates').getElementsByTagName('li')
-					Array.prototype.forEach.call(lis, function (li) {
-						li.addEventListener('click', function () {
-							var name = this.getAttribute('data-name')
-							var ns   = namespaces[name]
-							
-							for (var k in ns) {
-								if ($e(k)) {
-									$e(k).value = ns[k]
-								}
-							}
-						}, false)
-					})
-				}, false)
-				</script>
-				<script>
-				var namespaces = #{JSON.stringify namespaceMap}
-				</script>
-			"""
-			
-			opts = {
-				ident : "--internal:settings"
-				title : "Settings"
-				body  : body
-			}
-			
-			console.log "Rendering internal page..."
-			wyke.renderInternalPage opts, (err, result) ->
-				res.send result
-	
-	if req.body and req.body.newNS
-		ns = req.body.newNS
-		ns["includer"] or= "Internal:DefaultIncluder"
-		ns["renderer"] or= "Internal:DefaultRenderer"
-		ns["mimetype"] or= "text/html"
-		
-		wyke.storeNamespace ns.name, ns, true, sendBack
-
-	else
-		do sendBack
-
-app.listen 8124
-
-console.log "Server up and running!"
+//-------------------------------------------------------------------
+//-- Wyke ExpressJS implementation ----------------------------------
+//-------------------------------------------------------------------
+
+var express   = require('express')
+  , Mongolian = require('mongolian')
+  , wykeUtils = require('./wyke')
+
+var basename = __dirname.replace(/\/[^\/]+$/, '')
+
+// Init the Express web server
+var app = express.createServer()
+app.use(express.bodyParser())
+app.use(express.cookieParser())
+app.use(express.session({secret: "there is no_secret!"}))
+app.use(express.static(basename + '/res'))
+
+// Setup the database...
+var database = (new Mongolian('localhost', 27017)).db('wyke')
+//var database = require('./fakedb').create(basename + '/res/testdb.json')
+//database.load()
+
+var pages       = database.collection('pages')
+  , namespaces  = database.collection('namespaces')
+
+// Create the Wyke instance
+var wyke = new wykeUtils.Wyke({database: database})
+
+// Catch all /wyke/anything/ident URLs, even when ident contains '/'
+// characters.
+app.all(/^\/wyke\/[^\/]+(?:\/(.*))?/, function(req, res, next) {
+	req.ident = req.params[0]                || "Index"
+	req.addr  = req.connection.remoteAddress || "???"
+	next()
+})
+
+app.all(/^\/(?!wyke)(.*)/, function(req, res) {
+	req.ident = "Page:" + (req.params[0] || 'Index')
+	getRaw(req, res)
+})
+
+//app.get('/?',      function(req, res) { res.redirect('/wyke/view/Index') })
+app.get('/wyke/?', function(req, res) { res.redirect('/wyke/view/Index') })
+
+//-- /wyke/view/:ident ----------------------------------------------
+app.get('/wyke/view/*?', function(req, res) {
+	console.log("[" + req.addr + "] [  view] " + req.ident)
+	
+	wyke.getPage(req.ident, function(err, page) {
+		if (err && err.errno == 404) {
+			// TODO: Add proper 404 page.
+			res.send("Page not found: " + req.ident, 404)
+			return
+		}
+		
+		page.getNamespace(function(err, ns) {
+			wyke.renderPage(page, function(err, result) {
+				if (err) {
+					res.send("<pre>Error:\n" + err.message + "</pre>")
+				} else {
+					res.send(result)
+				}
+			})
+		})
+	})
+})
+
+//-- /wyke/raw/:ident -----------------------------------------------
+// FIXME: Join with the above function.
+app.get('/wyke/raw/*', function getRaw(req, res) {
+	console.log("[" + req.addr + "] [  raw ] " + req.ident)
+	
+	wyke.getPage(req.ident, function(err, page) {
+		if (err && err.errno == 404) {
+			res.send("Page not found: " + req.ident, 404)
+			return
+		}
+		
+		page.getNamespace(function(err, ns) {
+			if (err) {
+				res.send("<pre>Error:\n" + err.message + "</pre>")
+			} else {
+				res.contentType(ns.mimetype)
+				res.send(page.body)
+			}
+		})
+	})
+})
+
+//-- /wyke/edit/:ident ----------------------------------------------
+app.get('/wyke/edit/*', function(req, res) {
+	console.log("[" + req.addr + "] [  edit] " + req.ident)
+	wyke.getPage(req.ident, function(err, page) {
+		if (err) {
+			if (err.errno == 404) {
+				page = {	// TODO: Better way to create a "default page"
+					ident : req.ident,
+					title : wykeUtils.parseIdent(req.ident),
+					body  : ""
+				}
+			} else {
+				throw err
+			}
+		}
+		
+		function entify(str) {
+			return str.replace(/&/g, '&amp;')
+			     .replace(/</g, '&lt;' )
+			     .replace(/>/g, '&gt;' )
+		}
+		
+		var body =
+			[ '<form action="/wyke/edit/' + page.ident + '" method="POST">'
+			, ' <div class="editor-wrapper">'
+			, '  <textarea class="editor" name="page[body]" rows="25" cols="80">'
+					+ entify(page.body) + '</textarea>'
+			, ' </div>'
+			, ' <input type="submit" value="Save" />'
+			, '</form>'
+			].join("\n")
+		
+		var opts = {
+			ident    : page.ident,
+			title    : "Editing " + page.title.pretty,
+			body     : body,
+			internal : false
+		}
+		
+		wyke.renderInternalPage(opts, function(err, result) {
+			res.send(result)
+		})
+	})
+})
+
+app.post('/wyke/edit/*', function(req, res) {
+	if (!req.body.page) throw new Error("Something went wrong!")
+	console.log("[" + req.addr + "] [# SAVE] " + req.ident)
+
+	var content = req.body.page.body.replace(/\r\n/g, "\n")
+	
+	wyke.storePage(req.ident, content, function(err, page) {
+		if (err) throw err
+		res.redirect("/wyke/view/" + page.ident)
+	})
+})
+
+//-- /wyke/internal -------------------------------------------------
+app.get('/wyke/internal', function(req, res) {
+	namespaces.find().toArray(function(err, namespaces) {
+		pages.find().toArray(function(err, pages) {
+			if (err) throw err
+			
+			function jsPrint(obj) {
+				return JSON.stringify(obj, 0, 4).replace(/[<>&]/g, function(chr) {
+					return {
+						"<": "&lt;",
+						">": "&gt;"
+					}[chr]
+				})
+			}
+			
+			var pagelist = pages.map(function(page) {
+				return '	<li><a href="/wyke/view/' + page.ident + '">' +
+						page.title.pretty + '</a></li>'
+			})
+			
+			var body =
+				[ '<h2 id="pagelist">Pagelist</h2>'
+				, '<ul>'
+				, pagelist.join("\n")
+				, '</ul>'
+				].join("\n")
+			
+			var opts = {
+				ident : "--internal:internal",
+				title : "Internal status",
+				body  : body
+			}
+			
+			wyke.renderInternalPage(opts, function(err, result) {
+				res.send(result)
+			})
+		})
+	})
+})
+
+app.get('/wyke/internal-save-db', function(req, res) {
+	database.save()
+
+	var opts = {
+		ident : "--internal:save-db",
+		title : "Saving database",
+		body  : "<p>Database saved successfully!</p>"
+	}
+
+	wyke.renderInternalPage(opts, function(err, result) {
+		res.send(result)
+	})
+})
+
+//-- /wyke/settings -------------------------------------------------
+app.all('/wyke/settings', function(req, res) {
+	function sendBack() {
+		var namespaceMap = {}
+
+		namespaces.find().toArray(function(err, namespaces) {
+			var namespaceList = namespaces.map(function(ns) {
+				namespaceMap[ns.name] = ns
+				var extra = Object.keys(ns).filter(function(key) {
+					return ['_id', 'name'].indexOf(key) < 0
+				}).map(function(key) {return ns[key]})
+
+				//extra = (val for key,val of ns when key not in ['_id', 'name'])
+				return '<li data-name="' + ns.name + '">' + ns.name + ' : ' +
+						extra.join(" : ") + '</li>'
+			})
+			
+			var body =
+				[ '<h2>Namespaces</h2>'
+				, '<p>These namespaces already exist:</p>'
+				, '<ul id="templates">'
+				, namespaceList.join("\n")
+				, '</ul>'
+				, ''
+				, '<form action="/wyke/settings" method="POST">'
+				, '	<fieldset>'
+				, '		<legend>Add or update namespace</legend>'
+				, '		',
+				, '		<label for="name">Name:</label>'
+				, '		<input type="text" name="newNS[name]" id="name" />'
+				, '		<label for="includer">Includer:</label>'
+				, '		<input type="text" name="newNS[includer]" id="includer" />'
+				, '		<label for="renderer">Renderer:</label>'
+				, '		<input type="text" name="newNS[renderer]" id="renderer" />'
+				, '		<label for="mimetype">Mime type:</label>'
+				, '		<input type="text" name="newNS[mimetype]" id="mimetype" />'
+				, '		'
+				, '		<input type="submit" value="Update" />'
+				, '	</fieldset>'
+				, '</form>'
+				, '<script>'
+				, ''
+				, 'function $e(str) {return document.getElementById(str)}'
+				, '	'
+				, 'window.addEventListener("load", function () {'
+				, '	lis = $e("templates").getElementsByTagName("li")'
+				, '	Array.prototype.forEach.call(lis, function (li) {'
+				, '		li.addEventListener("click", function () {'
+				, '			var name = this.getAttribute("data-name")'
+				, '			var ns   = namespaces[name]'
+				, '			'
+				, '			for (var k in ns) {'
+				, '				if ($e(k)) {'
+				, '					$e(k).value = ns[k]'
+				, '				}'
+				, '			}'
+				, '		}, false)'
+				, '	})'
+				, '}, false)'
+				, '</script>'
+				, '<script>'
+				, 'var namespaces = ' + JSON.stringify(namespaceMap)
+				, '</script>'
+				].join("\n")
+			
+			var opts = {
+				ident : "--internal:settings",
+				title : "Settings",
+				body  : body
+			}
+			
+			console.log("Rendering internal page...")
+			wyke.renderInternalPage(opts, function(err, result) {
+				res.send(result)
+			})
+		})
+	}
+	
+	if (req.body && req.body.newNS) {
+		var ns = req.body.newNS
+		ns["includer"] || (ns["includer"] = "Internal:DefaultIncluder")
+		ns["renderer"] || (ns["renderer"] = "Internal:DefaultRenderer")
+		ns["mimetype"] || (ns["mimetype"] = "text/html")
+		
+		wyke.storeNamespace(ns.name, ns, true, sendBack)
+	} else {
+		sendBack()
+	}
+})
+
+var port = 8124
+
+app.listen(port)
+console.log("Server up and running on port " + port + "!")